org.postgresql.util.PSQLException: ERROR: syntax error near «,» in Java - java

The below is the query generate by a prepareStatement in Java:
insert into schema.table(cedula, actividad, mercado, venta_mensual, fortalezas, crecer,
financiamiento, monto, patente, contador, regimen_tri, problemas, bn_servicios, cursos )
values ('val', 'GAM', 'GAM', '0', 'Calidad', 'Sí', 'Sí', '122', 'Sí', 'Sí', 'ddd', 'aaa','ccc', 'bbb' )
The Java code is:
try {
PreparedStatement pstmt = conexion.prepareStatement(query);
pstmt.setString(1, n.getCedula());
//the rest of the sets of the statement continue here from 1 to 13
pstmt.executeUpdate();
conexion.createStatement().execute(query);
return true
} catch (SQLException e) {
e.printStackTrace(); // This error
return false;
}
The query is executed int the try statement and insert the values properly in the DB, BUT it also throws the below exception, at line 192: here 'val':
org.postgresql.util.PSQLException: ERROR: error de sintaxis en o cerca de «,»
org.postgresql.util.PSQLException: ERROR: syntax error near ',' java
The error trace relate to postgres is here:
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.execute(AbstractJdbc2Statement.java:366)
By the way, the table has a bigserial value and all the others values showed in the query. Thanks in advance!

If the query contains string constant within the values clause, as you have shown in the question:
query = "insert into table(cedula, actividad, mercado) "
+ " values ('val', 'GAM', 'GAM' )";
then this part of code will work fine:
conexion.createStatement().execute(query);
however this part of code won't work:
pstmt.setString(1, n.getCedula());
//the rest of the sets of the statement continue here from 1 to 13
It will throw an PSQLException: The column index is out of range: X, number of columns: 0, because PreparedStatement.setXXX methods expect placeholders ? in the SQL statement.
On the other hand, when the insert statement contains placeholders (I assume that your INSERT does contain placeholders, because you haven't got the above exception):
query = "insert into tabla(cedula, actividad, mercado) "
+ " values ( ?, ?, ? )";
then pstmt.setString... statements will work fine, however this statement:
conexion.createStatement().execute(query);
will throw an exception: PSQLException: ERROR: syntax error near ','
If your intent is to execute the INSERT twice, the first one using placeholders, and the second one using string values, you must do it in this way:
query1 = "insert into tabla(cedula, actividad, mercado) "
+ " values ('val', 'GAM', 'GAM' )";
query2 = "insert into tabla(cedula, actividad, mercado) "
+ " values ( ? , ? , ? )";
PreparedStatement pstmt = conexion.prepareStatement(query2);
pstmt.setString(1, n.getCedula());
//the rest of the sets of the statement continue here from 1 to 13
pstmt.executeUpdate();
conexion.createStatement().execute(query1);

String sql="INSERT INTO travel values(Source,Destination,VehicleType,PhoneNo)"
+" VALUES ('Mysore','Chennai','l',94400000)";

Related

PreparedStatement IF EXISTS throws: org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0

Following code throws exception:
String sql = "DO $$ " +
"BEGIN " +
"IF EXISTS ( SELECT column_name FROM information_schema.COLUMNS WHERE table_name='myTable' AND column_name='myColumn') THEN " +
"UPDATE myTable SET \"myColumn\"=? WHERE \"id\"=1; " +
"END IF; " +
"END " +
"$$; ";
Connection c = DriverManager.getConnection(...);
PreparedStatement pstmt = c.prepareStatement(sql)
pstmt.setString(1, "bla bla"); // <--- EXCEPTION HERE
pstmt.executeUpdate();
If I'm changing sql to this then it's fine:
String sql = "UPDATE myTable SET \"myColumn\"=? WHERE \"id\"=1;";
What am I doing wrong? I want to update some columns only if they exists...
Postgres docs says:
PREPARE name [ ( data_type [, ...] ) ] AS statement
...
statement
Any SELECT, INSERT, UPDATE, DELETE, or VALUES statement.
https://www.postgresql.org/docs/9.6/static/sql-prepare.html
So it seems you can't prepare anonymous code block and I guess your code:
PreparedStatement pstmt = c.prepareStatement(sql)
does not prepare anything. You can check it by making sql request:
select * from pg_prepared_statements;
If you change your code like this:
String sql = "DO $$ whatever $$;";
Connection c = DriverManager.getConnection(...);
PreparedStatement pstmt = c.prepareStatement(sql);
((org.postgresql.PGStatement)pstmt).setPrepareThreshold(1); // <-- Add this line
// pstmt.setString(1, "bla bla"); // comment it out
pstmt.executeUpdate();
you get the actual postgres error about wrong statement to prepare.

MySQL Syntax error exception

I'm not able to execute the query here.It says the above mentioned error.I have tried with 'Select * from customer' query and it is working.I can't figure out where am i going wrong.Please help and thanks in advance.
The full query is- SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,COUNTRY,AGE,GENDER,EMAIL_ADDRESS FROM CUSTOMER WHERE FIRST_NAME='SHIVAM';
The error message is- com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErr orException: Unknown coloumn 'SHIVAM' in 'where clause'
DefaultTableModel model;
model=(DefaultTableModel)tblSearchCustomer.getModel();
try{
Class.forName("java.sql.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/divign","root","password");
Statement stmt=con.createStatement();
String sfld=(String) searchfldCB.getSelectedItem();
//this stands for Search Field(ComboBox)
String op=(String) opCB.getSelectedItem();
//this stands for operator(ComboBox)
String crit=criteriaTF.getText();
//this stands for criteria
String query="SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,COUNTRY,AGE,GENDER,EMAIL_ADDRESS FROM CUSTOMER WHERE" + sfld+""+op+""+crit+" ;";
//This Query is not Executing
ResultSet rs=stmt.executeQuery(query);
while(rs.next()) {
model.addRow (new Object[ ] {
rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getInt(5),
rs.getString(6),rs.getInt(7)
} );
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e.toString());
}
When you generate your query, there are no single quotes in your where statement, which means you'll get WHERE FIRST_NAME=SHIVAM, so it tries to compare first_name to a column called SHIVAM which doesn't exist
So here is the corrected query-
String query="SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,PASSWORD,ADDRESS,COUNTRY,AGE,GENDER,EMAIL_ADDRESS,PHONE_NUMBER FROM CUSTOMER WHERE " +sfld+" "+op+" '"+crit+"' ;";
Notice the inverted commas around crit....now if i type SHIVAM in jTextField (criteriaTF) the name will be executed in MySQL with inverted commas i.e. 'SHIVAM'
String query="SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,COUNTRY,AGE,GENDER,EMAIL_ADDRESS FROM CUSTOMER WHERE" + sfld+""+op+""+crit+" ;";
In the where condition you haven't mentioned the column name to assign the value of sfld+""+op+""+crit.
You have to provide the column name next to where clause.

MySql inserting on multiple table using BEGIN and COMMIT java

Is this query possible on java?
"BEGIN;"
+ "INSERT INTO product(code, name, description, category_id) "
+ "VALUES(?,?,?,?);"
+ "INSERT INTO inventory_item(quantity, price, product_id) "
+ "VALUES(?,?,LAST_INSERT_ID());"
+ "COMMIT;";
I used it on a PreparedStatement and it really eating my time just to figure out the error my dbUnit said there is an error on the statement
com.example.dao.exception.DataAccessException:
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 'INSERT INTO product(code, name, description,
category_id) VALUES('00003','lemon ' at line 1
at
com.example.dao.InventoryDaoImpl.addInventoryItem(InventoryDaoImpl.java:126)
I can't print the PreparedStatement on the console I tried
PreparedStatement statement =
connection.prepareStatement( FIND_INVENTORY_ITEM_BY_PRODUCT_CODE_QUERY );
System.out.print( statement );
Can you guys give me a hand figure out the error?
May not be the way, but this has always worked for me:
List<String> sqlStatements = new ArrayList<String>();
// stuff your statements into this list
// (I'm often reading them from some file. The file often
// contains blank lines, comments and semicolons, which I
// strip out.)
Statement stmt = null;
try {
dbConn.setAutoCommit(false);
stmt = dbConn.prepareStatement();
for ( String sql : sqlStatements ) {
logger.debug("\t"+sql);
stmt.addBatch(sql);
}
stmt.executeBatch();
dbConn.commit();
} catch ( Exception e ) {
// handle exceptions
} finally {
// close statement
}

Using Oracle sequence to insert log id into 2 tables from jdbc?

I am using oracle sequence for inserting log id into tableA as follows,
String SQL_PREP_INSERT = "INSERT INTO tableA (LOG_ID,USER_ID,EXEC_TIME) VALUES"
+ " (logid_seq.nextval, ?, ?)";
Then getting the recently inserted value,
String SQL_PREP_SEL = "SELECT max(LOG_ID) FROM tableA ";
stmt = con.prepareStatement(SQL_PREP_SEL);
stmt.execute();
ResultSet rs = stmt.getResultSet();
if (rs.next()) {
logid = rs.getInt(1);
}
And inserting it into tableB,
String SQL_PREP_INSERT_DETAIL = "INSERT INTO tableB (LOG_ID, RESPONSE_CODE, RESPONSE_MSG) VALUES"
+ " (?, ?)";
stmt = con.prepareStatement(SQL_PREP_INSERT_DETAIL);
stmt.setInt(1, logid);
stmt.setString(2, respCode);
stmt.setString(3, respMsg);
stmt.execute();
Is there a way to generate sequence in Java instead of Oracle and insert into both tables at once, instead of selecting from tableA and inserting into tableB?
In general, selecting the MAX(log_id) is not going to give you the same value that logid_seq.nextval provided. Assuming that this is a multi-user system, some other user could have inserted another row with a larger log_id value than the row you just inserted before your query is executed.
Assuming that both INSERT statements are run in the same session, the simplest option is probably to use the logid_seq.currval in the second INSERT statement. currval will return the last value of the sequence that was returned to the current session so it will always return the same value that was generated by the nextval call in the first statement.
INSERT INTO tableB (LOG_ID, RESPONSE_CODE, RESPONSE_MSG)
VALUES( logid_seq.currval, ?, ? )
Alternatively, you could use the RETURNING clause in your first statement to fetch the sequence value into a local variable and use that in the second INSERT statement. But that is probably more work than simply using the currval.
String QUERY = "INSERT INTO students "+
" VALUES (student_seq.NEXTVAL,"+
" 'Harry', 'harry#hogwarts.edu', '31-July-1980')";
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// get database connection from connection string
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:sample", "scott", "tiger");
// prepare statement to execute insert query
// note the 2nd argument passed to prepareStatement() method
// pass name of primary key column, in this case student_id is
// generated from sequence
PreparedStatement ps = connection.prepareStatement(QUERY,
new String[] { "student_id" });
// local variable to hold auto generated student id
Long studentId = null;
// execute the insert statement, if success get the primary key value
if (ps.executeUpdate() > 0) {
// getGeneratedKeys() returns result set of keys that were auto
// generated
// in our case student_id column
ResultSet generatedKeys = ps.getGeneratedKeys();
// if resultset has data, get the primary key value
// of last inserted record
if (null != generatedKeys && generatedKeys.next()) {
// voila! we got student id which was generated from sequence
studentId = generatedKeys.getLong(1);
}
}

Help needed for inserting values to a mysql table

I have created a table using mysql:
CREATE TABLE JobCard (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
JobNo Long,
RegNo VARCHAR(20),
Service_Type VARCHAR(20),
Customer_Complaints VARCHAR(100)
);
in cmd.
From Eclipse, i coded for inserting the values using prepared Statement for the table. Since ID is a auto_increment, i didn't include it in the insert statement.
String Query =
"INSERT INTO JobCard (JobNo, RegNo, Service_Type, Customer_Complaints)
VALUES (?,?,?,?)";
But the output shows me :
java.sql.SQLException: Parameter index out of range
(5 > number of parameters, which is 4).
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at
com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3717)
at
com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3701)
at
com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4552)
at
example.Connect.DoInsertIntoDB(Connect.java:40)
Can anyone please tell me how to pass the parameter list? Please help me resolve this error!!
Update:
Here is my code:
The method call is:
System.out.println(strLine);
String[] dbColumnValues = strLine.split("%");
Connect.DoInsertIntoDB(Long.parseLong(dbColumnValues[0]),dbColumnValues[1],dbColumnValues[2], dbColumnValues[3]);
The method definition:
public static void DoInsertIntoDB(Long JobNo, String RegNo, String Service_Type, String Customer_Complaints){
String Query = "INSERT INTO JobCard (JobNo, RegNo, Service_Type, Customer_Complaints) VALUES (?,?,?,?)";
try {
Connection conn = toConnect();
PreparedStatement pstmt = conn.prepareStatement(Query);
pstmt.setLong(2, JobNo);
pstmt.setString(3, RegNo);
pstmt.setString(4, Service_Type);
pstmt.setString(5, Customer_Complaints);
pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Need to read your stack trace. In your code (on line 40 of Connect.java) you're attempting to set a value into the 5th ? but there are only 4 ?s in your prepared statement.
When you set the parameters, you are starting with 2, and it must be 1.
If you see, the last parameter is the index 5, and you don't have a 5° parameter,
Because of this java say the exception "Parameter index out of range".
You must start in 1.
PS: Sorry for my english.
Prepare statement parameter begin from 1 number, based on your code the parameter should be 1 to 4
but you ended with 5.
it cause parameter index out of range
Your try should look like this,
try {
Connection conn = toConnect();
PreparedStatement pstmt = conn.prepareStatement(Query);
pstmt.setLong(1, JobNo);
pstmt.setString(2, RegNo);
pstmt.setString(3, Service_Type);
pstmt.setString(3, Customer_Complaints);
pstmt.executeUpdate();
pstmt.close();
conn.close();
}
and that should solve the problem....

Categories