Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm writing a Java Swing program for a college library. This program is connected to an MS Access database.
The program has a JTextField where the "Number" has to be entered. Below the TextField, there's a JButton. After the number is entered and the button is clicked, I want the program to print out the respective "Department"
For example :
When the user types the Number "3" in the JTextField and clicks the 'Enter'
button, I want my program to print out "Computers" i.e the data from the adjoining cell.
How do I achieve this? Thanks in advance!
Start by taking a look at JDBC Database Access.
You will need a JDBC driver for MS Access, UCanAccess is reasonable popular.
You will then need to:
Load the JDBC driver
Connect to the database
Execute a SQL query which can select the data you want based on your critera
Retrieve the data from the resulting data set
For example...
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
try (Connection conn = DriverManager.getConnection("jdbc:ucanaccess://<mdb or accdb file path>", user, password)) {
try (PreparedStatement stmt = conn.prepareStatement("SELECT department FROM Table1 WHERE ID = ?")) {
stmt.setInt(1, 3); // Use a variable for the ID
try (ResultSet rs = stmt.executeQuery()) {
// We're only expecting a single row...
if (rs.next()) {
String department = rs.getString(1);
}
}
}
} catch (SQLException exp) {
exp.printStackTrace();
}
} catch (ClassNotFoundException exp) {
exp.printStackTrace();
}
You might also want to take a look at a SQL Tutorial
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to connect to SQL Server from an Android app and after days of struggling, I have finally figured it out. Now I have run into a much simpler problem. My select query only selects the last value from the table. The table only contains string values for now as it is a test table. Here is what I wrote in my code.
public void sqlButton(View view) {
if (connection != null) {
Statement statement = null;
try {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("Select * from [dbo].[Table_1];");
while (resultSet.next()) {
textView.setText(resultSet.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
else {
textView.setText("Connection is null");
}
}
Your problem is probably that you're overwriting your output text each time.
Write this to a multiline text field, so you see all results:
textView.setText(textView.getText() + "\n" + resultSet.getString(1));
Actually, the select query returns all records in your table. However, the problem is in this part
while (resultSet.next()){ textView.setText(resultSet.getString(1));}
the text in the next loop will replace one in the previous. Therefore, you only see the last one.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Good morning . I have a question . I have two screens in my program one is check in that will have special field (check no).The other screen is check out. It also have check no . I want to write a query that relate the check in with check out by using the check no and save it in one row in database . i wrote :
public void actionPerformed(ActionEvent arg0) {
while(textField.getText()==Securityoffcheck.getnumber())
{
try{
String timeStamp = new SimpleDateFormat("dd.MM.yyyy HH.mm.ss").format(new Date());
String sql = "INSERT INTO RECORD(CHECK_OUT)VALUES(?)";
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(12, timeStamp);
pst.execute();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,e);
}
}
}
});
but nothing happen .
Check your parameter index in pst.setString(12, ...). For your SQL statement INSERT INTO RECORD(CHECK_OUT) VALUES(?) you should set the parameter index to 1.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to get some values from my database, but when I click button (void ButtonClick) my app crashes.
That's my code:
public void ButtonClick() throws Exception {
getConnection();
}
public Connection getConnection() throws Exception {
try {
String username = "*******";
String password = "*******";
String url = "jdbc:mysql://http://**.***.***.***:3306/UserDB";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = (Connection) DriverManager.getConnection(url,username,password);
Statement statement = (Statement) conn.createStatement();
String query = "SELECT * FROM TABLE 'UserDB'";
ResultSet result = statement.executeQuery(query);
while (result.next()) {
String name = result.getString("Username");
int id = result.getInt("ID");
int points = result.getInt("Points");
Toast.makeText(this, name + " " + id + " " + points, Toast.LENGTH_SHORT).show();
}
return conn;
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
(I don't know what's the error because my AVD don't work)
Thanks for help!
Starting with Java 7, there is no need to use forName() method. You are creating a new instance in this way and in the same time you are trying to create a connection using DriverManager.getConnection().
So in order to solve this, just remove the instantiation of the driver using forName() method.
Seeing the screen-shot, please note that you can't access a MySQL database from Android natively. Actually you may be able to use JDBC, but it is not recommended. Please see this post
Hope it helps.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need to create a sql sequence in sql server programmatically from Java and I should be able to retrieve the continuous value from the sequence to program. First of all can I do so? If so how?
It's possible as all SQL servers provide some functionality and guarantee ACID rules. Even with very simple old MySql engine which didn't support transactions it's achievable. The easiest and widely supported approach is:
CREATE TABLE SequenceValue (
sequenceIdentifier varchar(124) NOT NULL PRIMARY KEY,
sequenceValue INT NOT NULL;
);
All you need to do in the program is:
Connection con = dataSource.getConnection();
try {
con.setAutoCommit(true);
PreparedStatement st = con.prepareStatement("SELECT sequenceValue SequenceValue WHERE sequenceIdentifier = ?");
st.setString(1, sequenceIdentifier);
SQLException retried = null;
for (;;) {
ResultSet rs = st.executeQuery();
if (!rs.next()) {
if (retried != null)
throw retried;
PreparedStatement ins = con.prepareStatement("INSERT INTO SequenceValue (sequenceIdentifier, sequenceValue) VALUES (?, ?)");
ins.setString(1, sequenceIdentifier);
ins.setLong(2, 0);
try {
ins.executeUpdate();
}
catch (SQLException ex) {
// store the exception and rethrow if next query retry fails
retried = ex;
}
}
else {
long value = rs.getLong(1);
PreparedStatement upd = con.prepareStatement("UPDATE SequenceValue SET sequenceValue = sequenceValue+1 WHERE sequenceIdentifier = ? AND sequenceValue = ?");
upd.setString(1, sequenceIdentifier);
upd.setLong(2, value+1);
if (upd.executeUpdate() == 1)
return value+1;
}
}
}
finally {
con.close();
}
Briefly: The code avoid transactions completely. At the beginning it tries to retrieve the sequence value according to identifier. In case it's not found, it attempts to create it and retries retrieving again. It doesn't fail in case the value was created in the meantime.
If the value is found, it tries to increment it using atomic update on the row. If it succeeds then it returns the incremented value, if not it retries again.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have two kind of methods to remove JTable selected row.
I create this methods in my GUI Class:
First:
public void dellAction() {
if (table.getSelectedRow() > -1) {
int rowToDelete = table.getSelectedRow();
int rowToModel = table.convertRowIndexToModel(rowToDelete);
Object rowId = table.getValueAt(rowToModel, 0);
try {
Connection con;
PreparedStatement ps = null;
con = DriverManager.getConnection(...);
ps = con.prepareStatement("delete from table where id=?");
ps.setObject(1, rowId);
if (ps.executeUpdate() == 1) {
model1.removeRow(rowToModel);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
} else JOptionPane.showMessageDialog(null, "Select A Row");
}
Second:
public void delete(DefaultTableModel model, int modelRow) {
if (table.getSelectedRow() > -1) {
Object rowId = model.getValueAt(modelRow, 0);
try {
Connection con;
PreparedStatement ps = null;
con = DriverManager.getConnection(...);
ps = con.prepareStatement("delete from table where id=?");
ps.setObject(1, rowId);
if (ps.executeUpdate() == 1) {
model.removeRow(modelRow);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Select A Row");
}
}
The question depends on the context of your application. In a perfect world, your TableModel would be modelling data from some kind of factory/controller that was responsible for managing the data, which would read/write to some kind of data source.
This would allow your TableModel the opportunity to simply not care where the data was coming from or going to, only that it had some means of performing these actions.
The same would go for your JTable, it should have no idea about the source of the data, only that the TableModel provides the required contract it needs to fulfill its responsibility.
This, then, raises the question of, who should actually perform what jobs.
In this scenario, I would provide some means for the factory/controller to alert registered listeners to changes. This would decouple the API in such away that any part of the program would then be able to modify the factory/controller without needing to know about everybody else who might be using that factory/controller, but still be able to react to those changes.
So, my answer would generally be neither...but...your second one comes closest to achieving this, but I'm concerned about the need to extract data from the model in this way, but that's me...
This is, of course, is just my opinion, based on the factory, observer, producer-consumer and model-view-controller patterns