What is reason for following sql code couldn't insert data? - java

My database have two column. One column is auto increment id(Primary Key) and other is 'Sentence' column. Manually type something and I can insert that value. But when I'm trying insert variable value that gives error message. I tried different ways. ('?') /( ? )/(?) Not work anything for me.
int s1=9;
String s2="Kasuni";
String sql = "INSERT INTO sentences (Sentence) VALUES ( ? )";
PreparedStatement pstmtJ = conn.prepareStatement(sql);
//pstmtJ.setInt(1, s1);
pstmtJ.setString(1,s2);
pstmtJ.executeUpdate(sql);
1st value I didn't insert because of that is auto increment value. I just comment and that shows in my above code.
Error message:
Exception in thread "main" 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 '? )' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2642)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1647)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1566)
at TestJsoup.main(TestJsoup.java:66)
When I'm tring following code:
int s1=9;
String s2="Kasuni";
String sql = "INSERT INTO sentences (Sentence) VALUES ('?')";
PreparedStatement pstmtJ = conn.prepareStatement(sql);
//pstmtJ.setInt(1, s1);
pstmtJ.setString(1,s2);
pstmtJ.executeUpdate(sql);
That gives following error messages:
Exception in thread "main" java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3646)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3630)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4481)
at TestJsoup.main(TestJsoup.java:65)

pstmtJ.executeUpdate(sql); → You're sending the original SQL string, since that is calling Statement.executeUpdate(String).
Use pstmtJ.executeUpdate(); instead (PreparedStatement.executeUpdate()) to execute the prepared statement.

Interface Statement
int executeUpdate(String sql)
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement. refer java doc
public interface PreparedStatement extends Statement
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.refer java doc
you are calling executeUpdate(String sql) which is from Statement interface, you have to call executeUpdate() from PreparedStatement interface to resolve issue.
Modified Code :
int s1=9;
String s2="Kasuni";
String sql = "INSERT INTO sentences (Sentence) VALUES ( ? )";
PreparedStatement pstmtJ = conn.prepareStatement(sql);
//pstmtJ.setInt(1, s1);
pstmtJ.setString(1,s2);
pstmtJ.executeUpdate();

Related

escape character for '#' -- JDBC?

I'm making a batch insert to MySQL table:
insert into table1 (field1, field2) values("aa#gmail.com", "f2 value"), ("cc#gmail.com", "another f2 here");
giving error to the character '#' in the value String:
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 buyers (field1, field2) values ('aa#' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3970)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2677)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2073)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2009)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5098)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1994)
How can i get around this - is there some kind of escape charactr for JDBC to work this?
Note: I'm aware of JDBC-batch execution. I'm looking for a solution for the above - if any:
pStat.addBatch();
pStat.executeBatch();
TIA.
Further note: The above insert query runs fine directly on MySQL without JDBC in between. Also note: this isn't an issue when JDBC itself sets up the parameter with pStat.getString("aa#gmail.com"); -- thus the batch execn is a solution.
Try using PreparedStatement. It resolves special characters automatically and avoids sql-injection.
String queryStr = "insert into table1 (field1, field2) values(?, ?);"
try {
PreparedStatement preparedStatement = conn.prepareStatement(queryStr);
preparedStatement.setString(1, "aa#gmail.com");
preparedStatement.setString(2, "f2 value");
preparedStatement.executeUpdate();
} catch (SQLException e) {
// Error
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (conn != null) {
conn.close();
}
}
More examples: https://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/
I don't think the error message is indicating a problem with the '#' at sign character.
MySQL syntax error "right syntax to use near" usually points to the first token where the problem is encountered. In this case, it looks like MySQL is objecting to INSERT.
... near 'insert into buyers (field1, field2) values ('aa#' at line 1 at
I suspect that there is something before that insert in the SQL text, and MySQL is seeing multiple statements. That's just a guess, we're not seeing the actual code.
I recommend displaying the actual contents of the SQL text, before it's executed or prepared.
Use single quotes:
insert into table1 (field1, field2)
values('aa#gmail.com', 'f2 value'), ('cc#gmail.com', 'another f2 here');
Use the UTF-8 code for special characters when running from Java. UTF-8 code for # is \u0040:
insert into table1 (field1, field2) values("aa\u0040gmail.com", "f2 value"), ("cc\u0040gmail.com", "another f2 here");
Was doing two queries separated by ; in one.
all resolved.
nothing wrong with #.
Thanks for the insightful comments&answers.

How can I know what happened to each SQL statement given in execute()? [duplicate]

This question already has answers here:
Multiple queries executed in java in single statement
(6 answers)
Closed 4 years ago.
My jdbc driver for mysql db is of version 5.1.25.
I want to execute sql query like so:
statement.execute("select fullName from user where user_id=1; select fullName from user where user_id=2");
And I always receive exception:
Exception in thread "main" 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 'select fullName from user where user_id=2' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2809)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2758)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:894)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:732)
at dbViewer.model.UserConnectionManager.retrieveRoutinesNames1(UserConnectionManager.java:622)
at dbViewer.model.UserConnectionManager.main(UserConnectionManager.java:637)
BUT when I run this same query(separated by semicolon) from command line it works perfectly and outputs two tables as expected.
Using ; in a query for most databases doesn't work as it is usually not part of the statement syntax itself, but a terminator for command line or script input to separate statements. The command line or script processor sees a semi-colon as the signal that the statement is complete and can be sent to the server.
Also in JDBC a single statement prepare (or execute) should only be one actual statement so multiple statements are not allowed and so there is also no need to have a semi-colon, and as for some (most?) databases the semi-colon isn't part of the statement syntax, it is simply a syntax error to have one included.
If you want to execute multiple statements, you need to use separate executes. Technically, MySQL does have an option to support multiple executions which can be enabled by a connection property. This behavior is not compliant with the JDBC specification/API and makes your code less portable. See allowMultiQueries on Driver/Datasource Class Names, URL Syntax and Configuration Properties for Connector/J
I want to execute sql query like so:
statement.execute("select fullName from user where user_id=1; select fullName from user where user_id=2");
This is possible only when you have set one database connection property to allow multiple queries to execute all at once. And the property name is allowMultiQueries=true. This property has to be set and send along with a database connection request to the server. General syntax is like this:
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
This is additional connection property to those if already exists some, like autoReConnect=true, etc.
Acceptable values for allowMultiQueries property are true, false, yes, and no. Any other value is rejected at runtime with an SQLException.
You have to use execute( String sql ) or its other variants to fetch results of the query execution.
multiQuerySqlString = "select fullName from user where user_id=1; ";
multiQuerySqlString += "select fullName from user where user_id=2; ";
// you can multiple types of result sets
multiQuerySqlString += "select last_login from user_logs where user_id=1; ";
boolean hasMoreResultSets = stmt.execute( multiQuerySqlString );
To iterate through and process results you require following steps:
int rsNumber = 0;
while ( hasMoreResultSets ) {
rsNumber += 1;
Resultset rs = stmt.getResultSet();
// based on the structure of the result set,
// you can handle column values.
if ( rsNumber == 1 ) {
while( rs.next() ) {
// handle your rs here
} // while rs
} // if rs is 1
else if ( rsNumber == 2 ) {
// call a method using this rs.
processMyResultSet( rs ); // example
} // if rs is 2
// ... etc
// check whether there exist more result sets
hasMoreResultSets = stmt.getMoreResults();
} // while results
Refer to:
Multiple queries executed in java in single statement
One of the similar postings on SO, for which I gave an answer.
No you can't. What are you expecting to get by calling statement.execute(...)?
It returns one ResultSet (... which means one table).
You can just call "select fullName from user where user_id in (1, 2)" to geht back both results.
Having semicolons in JDBC statements is very error prone in general. Some JDBC drivers do not support this (e.g. IBM's JDBC driver for DB2 10.x throws an exception if you close your SQL statement with ";").

Inserting into multiple tables using a single query in preparestatement [duplicate]

This question already has answers here:
Can I execute multiple queries separated by semicolon with MySQL Connector/J? [duplicate]
(3 answers)
Closed 6 years ago.
This is my code
String query = "insert into Branch (CompanyID,BranchName,BranchAddress,Email,Phone,ContactPerson) values (?,?,?,?,?,?);insert into Activities(EmployeeID,ActivityType,Activities) values (?,?,?)";
// System.out.println(mobile);//BranchName | BranchAddress | Email | Phone | ContactPerson
pstmt = conn.prepareStatement(query);
pstmt.setString(1, compid);
pstmt.setString(2, name);
pstmt.setString(3, address);
pstmt.setString(4, email);
pstmt.setString(5, mobile);
pstmt.setString(6, contactperson);
pstmt.setString(7, empid);
pstmt.setString(8, acttype);
pstmt.setString(9, activity);
System.out.println(query+"-----"+acttype);
pstmt.execute();
status = true;
If I insert without dynamic values it gets inserted otherwise I get the below 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 'insert into Activities(EmployeeID,ActivityType,Activities) values ('6','createbr' at line 1
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 Activities(EmployeeID,ActivityType,Activities) values ('6','createbr' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155).........
How can I overcome this ??? I am able to insert using this statement below
insert into Branch (CompanyID,BranchName,BranchAddress,Email,Phone,ContactPerson) values ('1','sample','11 cross','fakemail#gmail.com','5467897656','Deigo');insert into Activities(EmployeeID,ActivityType,Activities) values ('6','createdbranch','cearted branch sample');
But I want it to be dynamic.Please help
allowMultiQueries=true&rewriteBatchedStatements=true needs to be added to the connection params to allow execution of multiple queries.
For example, the url may be like:
jdbc:mysql://xxx.xxx.xxx.xxx:nnnnn/db_name?allowMultiQueries=true&rewriteBatchedStatements=true&user=xxxx&password=yyyy

MySQLSyntaxErrorException error in Like clause

I have this function, which gets a List of objects from MySQL, using the like clause, but when testing, returns me a error of MySQLSyntaxErrorException, what i should do?
Code
#Override
public List<Livro> getLista(String nm) {
// TODO Auto-generated method stub
List<Livro> lista = new ArrayList<Livro>();
try {
String query= "SELECT L.*, nmautor, nmeditora FROM tblivro L, tbeditora E,tbautor A "
+ "WHERE nmlivro LIKE ? and L.cdautor = A.cdautor and L.cdeditora = E.cdeditora ";
PreparedStatement stmt = conn.prepareStatement(query);
String like = "%"+nm+"%";
stmt.setString(1, like);
ResultSet rs = stmt.executeQuery(sql);
...
}}
Full Error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'a' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:941)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3870)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3806)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2470)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2617)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2546)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2504)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1370)
at biblioc.dados.LivroDAO.getLista(LivroDAO.java:387)
The error is in this line:
ResultSet rs = stmt.executeQuery(sql);
Replace this with
ResultSet rs = stmt.executeQuery();
To execute a SQL string with JDBC, you only need to pass the SQL string to JDBC once, and when you are using a PreparedStatement that one time is when you prepare the statement. Once you've set all the parameters, calling executeQuery() with no arguments will run the prepared statement with the parameter values you set.
Calling the version of executeQuery that takes a single string parameter will run the SQL in that string, without allowing you to use any parameter values. This is because the PreparedStatement interface inherits this method from the Statement interface.
This behaviour of the MySQL JDBC driver is particularly confusing. You are far from being the first person to make this mistake and wonder what is going on, and I cannot believe that you will be the last. As pointed out in the comments, the JDBC driver is supposed to throw an exception when you call executeQuery with a string on a PreparedStatement. Had it done so, you may well have found a solution to your problem much quicker.
I don't know what your variable sql is. Perhaps it just contains a single letter a - I was able to reproduce your error message by running stmt.executeQuery("a").

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'bro' in 'where clause'

I'm trying to query MySQL database
statement = conn.createStatement();
String sql = "select * from file_post where gas_key='"+commun+"'";
fp =statement.executeQuery(sql);
where commun is
String commun= (String) session.getAttribute("commun");
I'm getting exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'bro' in 'where clause'
bro is the value of commun.
I also tried PreparedStatement, but that also gave me the same exception.
But when I make a query in MySQL command line:
select * from file_post where gas_key='bro';
It's perfect there and returns the exact data.
I can't figure out why it is giving me the exception when using the same query in a Java class.
This exception happens normally when you don't match the ", to avoid problems like this use a PreparedStatement
PreparedStatement st = con.prepareStatement("SELECT * FROM file_post WHERE gas_key=?");
st.setString(1,commun);
rs = st.executeQuery();
Can you try to print preparedStatement after setting variable...just to check what query is building...
System.out.println(preparedStatement);
and what is fp here? ResultSet?

Categories