I am trying to insert values into a table using jdbc driver. In my table, one column is defined as array datatype.
Table as follows
CREATE TABLE userType
(
id bigserial NOT NULL, // auto Inc
type character varying,
userRole bigint[] // array
)
I am having an array in my code, which is converted from arraylist.
List<Long> ids = new ArrayList<Long>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
Long[] idArr = new Long[ids.size()];
idArr = ids.toArray(idArr);
I am using the following code to insert the data in table.
String querys = "insert into userType(type,fk_last_modified_by,userRole)"
+ " values ('Auto',1,"+ idArr+")";
Connection connections = sessionFactory.getCurrentSession().connection();
Statement stmts = connections.createStatement();
int count =stmts.executeUpdate(querys);
System.out.println("count---"+count);
connections.close();
I am getting the following error while executing the above.
org.postgresql.util.PSQLException: ERROR: syntax error at or near "["
Position: 99
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:302)
at org.apache.commons.dbcp.DelegatingStatement.executeUpdate(DelegatingStatement.java:196)
at com.mmf.controllers.UpdateReconcileController.save(com.mmf.controllers.UpdateReconcileController:123)
Then I just followed the solution provided by Jagdesh,
String querys = "insert into userType(type,fk_last_modified_by,userRole)"
+ " values (?,?,?)";
System.out.println(querys);
Connection connections = sessionFactory.getCurrentSession().connection();
CallableStatement stmts = connections.prepareCall(query);
stmts.setString(1, "Auto");
stmts.setInt(2, 1);
stmts.setArray(3, connections.createArrayOf("integer", idArr));
stmts.executeUpdate(querys);;
connections.close();
Now I am getting the following error,
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:53)
at org.postgresql.core.v3.SimpleParameterList.setLiteralParameter(SimpleParameterList.java:114)
at org.postgresql.jdbc2.AbstractJdbc2Statement.bindLiteral(AbstractJdbc2Statement.java:2172)
at org.postgresql.jdbc2.AbstractJdbc2Statement.setLong(AbstractJdbc2Statement.java:1227)
at org.apache.commons.dbcp.DelegatingCallableStatement.setLong(DelegatingCallableStatement.java:252)
Can anyone point me where I am doing mistake?
Instead of above use PreparedStatement
String querys = "insert into reconcile_process (process_type,fk_last_modified_by,fk_bank_stmt_id)"
+ " values (?,?,?)";
Connection connections = sessionFactory.getCurrentSession().connection();
PreparedStatement pstmts = connections.createStatement();
pstmts.SetString("Auto");
pstmts.SetInt(1);
pstmts.setArray(3, conn.createArrayOf("integer", idArr));
pstmts.executeUpdate(querys);
insert into reconcile_process (process_type,fk_last_modified_by,fk_bank_stmt_id) values ('Auto',1,'[Ljava.lang.Long;#b318fc5')
So you cannot just + a long type to a string.
I think you want to use a PreparedStatement, not CallableStatement.
CallableStatements are used for calling a SQL function, and it has kinda weird syntax.
Related
I'm trying to use query to insert the entirety of one table into another (so no where clause). I am using java (exlipse). I want to insert data into JJ from ENTER
My code:
Edit: the ur variable is set at an earlier point so I don't have to type it a million times.
Connection con = DriverManager.getConnection(ur);
String sql = "INSERT INTO JJ ( Date, Account, Amount, DrCr )"
+ "SELECT ENTER.Date, ENTER.Account, ENTER.Amount, ENTER.DrCr"
+ "FROM ENTER;";
I'm getting the error:
CAExc:::5.0.0-SNAPSHOT unexpected token: ; in statement [INSERT INTO JJ ( Date, Account, Amount, DrCr )SELECT ENTER.Date, ENTER.Account, ENTER.Amount, ENTER.DrCrFROM ENTER;]
at net.ucanaccess.jdbc.UcanaccessConnection.prepareStatemen
ok, I am a newbie. I have two ArrayList and I want to insert data from the arralylist to table. one arraylist is for the table parameters to insert and other arraylist for inserting the values of the table.
I have tried searching if there was a dynamic way to insert but could not find any.
ArrayList<String> list= new ArrayList<>();
ArrayList<String> values= new ArrayList<>();
list.add("userid");
list.add("name");
list.add("email");
values.add(userID);
values.add(name);
values.add(email);
String sql = "insert into users (" + list + ") values( " + values + ")";
stmt.executeUpdate(sql);
I want to insert the data into the table. but parameters like userid should be in ''(quotes) and name should be in ''(quotes). but they are not converted automatically. is there any other way to do the same task?
IS there any way to get the data from JSON and insert into tables locally?
You should not not concatenate values like that into a SQL String. Use a PreparedStatement instead:
String sql = "insert into users (userid, name, email) values (?,?,?)";
PreparedStatement pstmt = connection.prepareStatement(sql);
The preferred way to insert multiple rows, is to use batching
for (int i=0; i < values.size(); i++) {
pstmt.setString(i+1, values.get(i);
}
pstmt.executeUpdate();
Passing a value for a column name userid as a String seems to be wrong to begin with. Usually those are stored as integers.
You can use String.join method to compose the query:
String sql = "insert into users (" + String.join(", ", list) + ") values( '" + String.join("', '", values) + "')";
But such by-hand sql composing from raw Strings is dangerous and can be vulnerable to injection attacks. I suggest using other solutions like orm.
I'm trying to insert values into a table (inquiry) the first value is of type Date , and I'm getting an SQL error SQL State S1009. what is the proper way to convert the date , what am I doing wrong?
String sqlStatement = "INSERT INTO inquiry (INQUIRY_DATE,INQUIRY_NOTE,INQUIRER_ID,PROGRAM_ID,CLASS_ID,CORPORATE_ID)\n"
+ "VALUES (?,?,?,?);";
ps = con.prepareStatement(sqlStatement);
java.sql.Date sDate = new java.sql.Date(inquiry.getInquiryDate().getTime());
int parameterIndex = 1;
ps.setDate(parameterIndex, sDate);
ps.setString(parameterIndex++, inquiry.getInquiryNote());
ps.setInt(parameterIndex++, inquiry.getInquirer().getInquirerID());
ps.setInt(parameterIndex++, inquiry.getProgramID());
ps.setInt(parameterIndex++, inquiry.getClassProgramID());
ps.setInt(parameterIndex++, 1);
sqlStatement = "INSERT INTO inquiry (INQUIRY_DATE,INQUIRY_NOTE,INQUIRER_ID,PROGRAM_ID,CLASS_ID,CORPORATE_ID)\n"
+ "VALUES (?,?,?,?);";
The parameterized query doesn't have enough ?, you queried 6 columns with 2 ? missing, it should be VALUES (?,?,?,?,?,?); ? are used for holding the places for your setXXX() column values
I have an insert query for Sybase Db which inserts one varchar value and 2 integer values into a table which is returning a error.
The table column datatypes are Varchar,Int,Int
The query is as shown below
sql_str = "INSERT INTO TempTable VALUES(" +
"'"+ 'Y' +"',"+ "DateDiff(ss,'12/31/1969 19:00:00','"+ secBegin +"')" +","+ "DateDiff(ss,'12/31/1969 19:00:00','"+ secEnd +"')" +")";
and its uses 2 String values i.e. secBegin and secEnd
String secBegin = "04/03/2012 10:08:24";
String secEnd = "04/03/2012 10:09:07";
And I'm getting the following error:
com.sybase.jdbc3.jdbc.SybSQLException: Insert error: column name or number of supplied values does not match table definition.
and its pointing to the insert query shown above as the erreneous line.
Is there any error in the jdbc query shown above.
Hi you can try this should it work :
sql_str = "INSERT INTO TempTable VALUES("Y",DateDiff(ss,'12/31/1969 19:00:00','"+ secBegin +"'),DateDiff(ss,'12/31/1969 19:00:00','"+ secEnd +"'))";
I have an SQL query that i am going to run using a PreparedStatement, and it is
UPDATE tbl_HitsCounter SET count = ? WHERE keyid = (SELECT id FROM tbl_HitsMaster WHERE sitename = '?')
Now when i set the 2nd paramater, which is a string value, i am getting a strange SQLException.
preparedStatement.setInt(1, 99);
preparedStatement.setString(2, masterKey);
As the setString() method is executed, i am getting an SQLException
The column position '2' is out of range. The number of columns for this ResultSet is '1'.
I have no idea what this is about, i havent even executed the executeUpdate() method.
There is only one placeholder in your SQL but you are trying to assign a value for the second. Your problem is that you have quoted the second placeholder, your SQL should look more like this:
UPDATE tbl_HitsCounter
SET count = ?
WHERE keyid = (
SELECT id
FROM tbl_HitsMaster
WHERE sitename = ?
)
Note the lack of quotes in sitename = ?. This is a placeholder: ?. This is an SQL question mark string literal: '?'.