I am trying to insert an array variable into the table. The code is shown below
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
class PostgreSQLJDBC {
public static void main(String args[]) {
Connection c = null;
Statement stmt = null;
Statement stmt1 = null;
int id[] = new int[3];
int no = 1;
id[0] = 2;
id[1] = 14;
id[2] = 4;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/ass2",
"postgres", "post");
c.setAutoCommit(true);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql1 = "INSERT INTO COMPANY (NO,ID) "
+ "VALUES (7, id);";
stmt1 = c.createStatement();
stmt1.executeUpdate(sql1);
stmt1.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
This code compiles but gives an PSQLexception.
Could someone please help in fixing this
idis hard-coded in your query. Also consider usingPreparedStatementwith placeholders . Finally, you are creating twoStatementobjects but only using one .Companytable. From what I see, you will have to execute 1 sql query for each of the ID value.