Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC insert statement is not working

Tags:

java

insert

jdbc

I am trying to insert new record, using jdbc. Everything look like ok, I don't have any exception, but new record isn't inserted into the table. Select statement works right.

  public Connection getConnection(){
    Connection conn=null;
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    try {
        conn = DriverManager.getConnection(url);
        conn.setAutoCommit(true);

    } catch (SQLException e) {
        e.printStackTrace();  
    }
    return conn;
}

public void insertDish(String name, float mass, float price, String description,int pizzeria_id) {
        String insertStr = "insert into \"Dish\"(name,mass,price,description,pizzeria_id) values("+"'"+name+"'"+", "+mass+", "+price+", "+"'"+description+"'"+", "+pizzeria_id+")";

      Connection conn = getConnection();

    try {
        Statement sql = conn.createStatement();
        sql.executeUpdate(insertStr);
        sql.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();  
    }
}

What can be wrong?

like image 881
sunny Avatar asked Oct 21 '10 18:10

sunny


People also ask

What is insert into statement?

You can use the INSERT INTO statement to add a single record to a table using the single-record append query syntax as shown above. In this case, your code specifies the name and value for each field of the record.


2 Answers

I have had a similar situation where my DB query software didn't see inserts/updates done from my Java program because they weren't committed, and therefore were not visible to other connections.

Try doing an explicit commit right after executing the statement:

sql.executeUpdate(insertStr);
conn.commit(); // ADDED
sql.close();

If that works you may want to adjust your AutoCommit settings, or just stay with the explicit commit.

like image 141
Stephen P Avatar answered Oct 06 '22 11:10

Stephen P


I would try disabling Auto Commit and doing the transaction manually, see if that helps.

like image 34
Valchris Avatar answered Oct 06 '22 09:10

Valchris