Reputation: 11633
I have a Java application and I want to use SQL database. I have a class for my connection :
public class SQLConnection{
private static String url = "jdbc:postgresql://localhost:5432/table";
private static String user = "postgres";
private static String passwd = "toto";
private static Connection connect;
public static Connection getInstance(){
if(connect == null){
try {
connect = DriverManager.getConnection(url, user, passwd);
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Connection Error", JOptionPane.ERROR_MESSAGE);
}
}
return connect;
}
}
And now, in another class I succeeded to print my values but when I attempt to insert a value nothing is happening ...
Here's my code :
try {
Statement state = SQLConnection.getInstance().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
Statement state2 = SQLConnection.getInstance().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
state2.executeUpdate("INSERT INTO table(field1) VALUES (\"Value\")"); // Here's my problem
ResultSet res = state.executeQuery("SELECT * FROM table");
Upvotes: 3
Views: 2875
Reputation: 1108632
You need to commit (and close) the connection (and statement) after use. You also need to ensure that you aren't swallowing any SQLException
s which may cause that you see "nothing" to happen.
That said,
private static Connection connect;
This is a terribly bad idea. You should never declare external resources as static
in your application. Your application will break when the other side decides to close the resource because it's been released for a too long time. You really need to acquire and close those resources (Connection
, Statement
and ResultSet
in the shortest possible scope. I.e. inside the very same method block as where the query is to be executed.
Also, I strongly recommend to use PreparedStatement
instead of Statement
since that will prevent your code from SQL injection attacks.
You may find this article useful to learn more about how to do basic JDBC interaction the right way.
Upvotes: 3
Reputation: 39807
Copuld just be a copy over to SO error, but looking but shoulding INSERT INTO table(field1) be INSERT INTO plateau(field1)?
Upvotes: 0
Reputation: 120917
state2.executeUpdate("INSERT INTO table(field1) VALUES (\"Value\")");
should be:
state2.executeUpdate("INSERT INTO plateau(field1) VALUES (\"Value\")");
Upvotes: 1