简体   繁体   中英

Java - MySQL --> SQLite - unable to insert in SQLite database using java

iv created a program which works really well with MySQL. However, when I convert it to SQLlite, everything works such as Creating tables, getConnection() to the database and such EXCEPT inserting values to the table?? I am unable to insert value to the table using Java (Netbeans) to SQLite database. I can only insert ONE row but not multiple rows? In MySQL, i could insert multiple rows at once, however, I cant in SQLite?

The code is (This works for only ONE row):

       Connection con;
       Statement s= con.CreateStatement();
       String st = "Insert into table1 (10,'abc')";
       s.executeUpdate(st);
       s.close();

If I do something like this (DOES NOT work for more than one row - have no idea why- SQLite):

         Connection con;
         Statement s= con.CreateStatement();
         String st = "Insert into table1 (10,'abc'), (5,'vfvdv')"; //now it doesnt    work since Im inserting more than one row. I can't figure out what Im doing wrong - 
         //Iv also tried Insert into table1(ID, Name) values (10,'abc'), (5,'afb'); but it dont work.
        s.executeUpdate(st);
        s.close();

Could any java expert or anyone help me on this. I cant figure out what Im doing wrong or anything because when I type my commands in the 'SQLite' command line it works fine for ALL. But, In JAVA with SQLite, I can only update one row for some reason? However, Java with MySQL works fine but not SQLlite.

Anyone could clarify what Im doing wrong would be brillant. Thanks alot for reading this and your time.

It's possible that the SQLite JDBC driver doesn't support the multi-insert syntax. This syntax is also not standard, though many databases do support it.

Another option for doing multiple inserts like this is to use the batching mechanism of PreparedStatement.

Connection conn = ....;
PreparedStatement stmt = 
  conn.prepareStatement("INSERT INTO table1(id, name) VALUES (?, ?)");

stmt.setInt(1, 10);
stmt.setString(2, "abc");
stmt.addBatch();

stmt.setInt(1, 5);
stmt.setString(2, "vfvdv");
stmt.addBatch();

stmt.executeBatch();

Typically, you'd use the setInt, setString, addBatch sequence in a loop, instead of unrolled as I've shown here, and call executeBatch after the loop. This will work with all JDBC compliant databases.

Multi row insert is not standard according to the SQL92 standard.

SQLite suports it since version 3.7.11.

If you have a version under this one, you need to make one insert for each row...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM