Getting SQL error SQL State S1009 - java

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

Related

jsp mysql inserting error

this is y inserting syntax
String add="INSERT INTO time_table VALUES("+coursename+"','"+coursecode+"','"+days+"','"+year+"','"+dep+"','"+time+"','"+hall+"','"+lecturer+"','"+credithours+"')";
ERROR
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '','5','2','2','8','1','9','PA','2')' at line 1
that is what am receiving as an error.
I think correct version of your query is this :
"INSERT INTO time_table VALUES('"+coursename+"','"+coursecode+"','"+days+"','"+year+"','"+dep+"','"+time+"','"+hall+"','"+lecturer+"','"+credithours+"')";
you forgot ' in beginning of +coursename+
Don't ever use this way, it can cause Syntax error, ot SQL Injection, you have to use PreparedStatement instead for example :
String add = "INSERT INTO time_table VALUES(?, ?, ?, ?, ?,?,?,?,?)";
try (PreparedStatement insert = connection.prepareStatement(add)) {
insert.setString(1, coursename);
insert.setString(2, coursecode);
insert.setString(3, days);
insert.setString(4, year);
insert.setString(5, dep);
insert.setString(6, time);
insert.setString(7, hall);
insert.setString(8, lecturer);
insert.setString(9, credithours);
insert.executeUpdate();
}
Note if your attributes are int or float or date or ... in your table, then you have to use the correct set, for example if the year is an in you can use insert.setInt(4, year); instead.
Your real problem is in your query you miss ' here :
INSERT INTO time_table VALUES('" + coursename + "'
//----------------------------^

Insert String in HSQLDB

I try to insert a String into a hsqldb an it gives me this error:
> java.sql.SQLSyntaxErrorException: user lacks privilege or object not
found: S
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(Unknown Source)
the column is set to VARCHAR(50) and the sqlstring is build like this:
String sql = "INSERT INTO Emergency Values(" + Counter.emergencyID + ","+
emergency.status +"," + "\""+ emergency.typeD +"\"" + "," + "\""+
emergency.typeB +"\"" + ","+ emergency.floorID + ")";
this ist how i execute the query:
Statement st = null;
st = con.createStatement(); // statements
int i = st.executeUpdate(sql); // run the query
PS: I know i am open to a sqlInjection like this.
EDIT: values are
sql = "INSERT INTO Emergency Values(0,1,"S","IB",1)"
If i change the string to ;
String sql = "INSERT INTO Emergency Values(" + Counter.emergencyID + ","+
emergency.status +","+ emergency.typeD +","+ emergency.typeB +","+
emergency.floorID +")";
the same error occures
Use a PreparedStatement and you won't have problems:
String sql =
"INSERT INTO Emergency (emergency_id, status, type_d, type_b, floor_id) " +
" Values (?, ?, ?, ?, ?)";
Note that I explicitly listed the column names in the insert statement. Not doing that is considered bad coding style.
I had to guess those names as you didn't show us the definition of your table. You have to replace with the correct column names of your table.
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, Counter.emergencyID);
pstmt.setInt(2, emergency.status);
pstmt.setString(3, emergency.typeD);
pstmt.setInt(4, emergency.typeB);
pstmt.setInt(5, emergency.floorID);
int i = pstmt.executeUpdate(sql); // run the query
The root cause of your problem was the incorrect usage of double quotes: ". String constants have to be put in single quotes in SQL. 'foobar' is a string value. Double quotes are used for identifiers "foobar" is e.g. a column name.
Unrelated, but: the use of Counter.emergencyID lets me think that your are generating (or trying to) unique IDs in your application. Don't do that. Use a sequence or identity column in the database. Do it correctly from the beginning. For a single user application this might not make a difference, but there is no way you can implement that correctly and scalable in an application that is used by multiple users at the same time, with concurrent transactions inserting into the same table.
i found the error in #a_horse_with_no_name 's code
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, Counter.emergencyID);
pstmt.setInt(2, emergency.status);
pstmt.setString(3, emergency.typeD);
pstmt.setInt(4, emergency.typeB);
pstmt.setInt(5, emergency.floorID);
int i = pstmt.executeUpdate(sql); // run the query
note the last line, it should be
int i = pstmt.executeUpdate(); // run the query
please refer to HSQLDB cryptic exception message: "feature not supported"
I know the question is old, but I ran into the same problem and found my a solution without using PreparedStatements.
INSERT INTO TypeA (id) VALUES ("Hello");
failed (user lacks privilege or object not found: Hello ), but
INSERT INTO TYPEA (id) VALUES ('Hello');
worked. So it seems like double quotes are not accepted (see also http://www.hsqldb.org/doc/1.8/guide/ch09.html#expression-section )

UCAExc:::3.0.7 user lacks privilege or object not found: SLIPSET

I have looked through similar threads on this site and none of the suggested answers seem to work. I am writing a java program that interacts with an Access database using SQL. I have successfully connected to the database and pulled information from it. However, I need to update the database and I keep running into this error
UCAExc:::3.0.7 user lacks privilege or object not found: SLIPSET
Why am I not able to successfully update the Access database?
Here is the code relevant to the updates
String sqlSlip ="UPDATE Slip" +
"SET slipOpen = 0 AND boatID =?" +
"WHERE slipNumber = ?";
PreparedStatement slipUpdate = connection.prepareStatement(sqlSlip);
slipUpdate.setDouble(1, boatIDdub);
slipUpdate.setDouble(2, rs.getInt("slipNumber"));
ResultSet updateSlip = slipUpdate.executeQuery();
String sqlCustomer = " INSERT INTO Customer(customerLName, customerFName, slipNumber, boatID, customerNumber)" +
"VALUES (?, ?, ?, ?, ?)";
PreparedStatement custUpdate = connection.prepareStatement(sqlCustomer);
custUpdate.setString(1,custLName);
custUpdate.setString(2, custFName);
custUpdate.setDouble(3, rs.getInt("slipNumber"));
custUpdate.setDouble(4, boatIDdub);
custUpdate.setDouble(5, customerNumber);
ResultSet updateCust = custUpdate.executeQuery();
connection.close()
If you were to inspect the contents of your sqlSlip string you would see that it contains
UPDATE SlipSET slipOpen = 0 AND boatID =?WHERE slipNumber = ?
You need to add a space to the end of each string fragment and use a comma instead of AND ...
String sqlSlip ="UPDATE Slip " +
"SET slipOpen = 0, boatID = ? " +
"WHERE slipNumber = ?";
... so that the string contains
UPDATE Slip SET slipOpen = 0, boatID = ? WHERE slipNumber = ?
Also note that to perform an INSERT query you need to use .executeUpdate(), not .executeQuery().

how to insert array in table using JDBC insert

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.

Java to MySQL: How to update row with a value from variable?

I have a table TotalSales on my database with columns Date(Primary) and Sales. I send query thru my Java Program.
I want to add a row if Date row not exists, and if Date row exists, the value on Sales will be updated. On update, the new value on Sales will be 'current value on Sales' + 'the value of variable totalBill'.
Lets say before execution: row under Sales = 0,
after execution: row under Sales = Sales + totalBill;
I tried this code:
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(date, totalBill)
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+VALUES(totalBill)";
st = con.prepareStatement(query);
st.execute();
But doesn't work:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'totalBill' in 'field list'
Can anyone help?
You need to take advantage of the parameterised nature of PreparedStatements and bind the values you want to apply before you execute the statement, something like...
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(?, ?)
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+?";
st = con.prepareStatement(query);
st.setDate(1, date);
st.setLong(2, totalBill);
st.setLong(3, totalBill);
for example
Take a look at Using Prepared Statements for more details
You are not appending the variable to your insert query, rather simply using a string. So change this:
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(date, totalBill)
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+VALUES(totalBill)";
to
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(" + date + "," + totalBill + ")
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+VALUES(totalBill)";
ADVICE: But for this case, you should learn to use PreparedStatement

Categories