INSERT SQL in Java

I have a Java application and I want to use a 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 managed to print my values, but when I try to insert a value, nothing happens ...

Here is 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 my problem
ResultSet res = state.executeQuery("SELECT * FROM table");
+3
source share
3 answers

You need to commit (and close ) the connection (and expression) after use. You also need to make sure that you are not swallowing any SQLExceptionthat may cause you to see "nothing."


Nonetheless,

private static Connection connect;

. static . , , . (Connection, Statement ResultSet . .. , .

, PreparedStatement Statement, SQL injection .

, , JDBC.

+3
state2.executeUpdate("INSERT INTO table(field1) VALUES (\"Value\")");

:

state2.executeUpdate("INSERT INTO plateau(field1) VALUES (\"Value\")");
+1

SO-, INSERT INTO (field1) INSERT INTO (1)?

0
source

Source: https://habr.com/ru/post/1747357/


All Articles