I am using following prepared statement :
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","root");
String query="select ename from ? ";
st=con.prepareStatement(query);
st.setString(1,"emp");
Here i want to provide table name from UI,on above code i have hardcoded tablename value.when i try to execute this code i got the following excepion.
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 ''emp' where intensive='1000'' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
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:3515)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3447)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2554)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1761)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1912)
at xmlbulkinsertoperation.getConnection.<init>(getConnection.java:42)
at xmlbulkinsertoperation.getConnection.main(getConnection.java:70)
Mar 26, 2012 12:04:30 PM xmlbulkinsertoperation.getConnection <init>
i'm not able to solve this problem,please help me?
Thanks
You cannot have a prepared statement with a table name as one of the parameters. Entities (table names/db names/function names so on) cannot be parameterized in prepared statements.
You'll have to either hard code the table name or concatenate it into the query.
Related
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/exam","root","password");
String q="insert into group"
+"(gname,des)"
+"values(?,?)";
PreparedStatement p=con.prepareStatement(q);
p.setString(1,gname);
p.setString(2,des);
p.executeUpdate();
con.close();
This is my code for adding a group. But the error says that my query syntax is wrong. I have tried single cores with the feilds in my table but still getting that error. Firstly i was using create statement that was also giving the same error. Please tell what us wrong with this query?
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 'group(gname,des)values('Science','')' at line 1
sun.reflect.GeneratedConstructorAccessor16.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
com.mysql.jdbc.Util.getInstance(Util.java:408)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2490)
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
org.apache.jsp.groupreg_jsp._jspService(groupreg_j
Your query, after stripping out the line breaks in your code, is this:
insert into group(gname,des)values(?,?)
In other words, you are trying to insert into a table named group. This is not allowed because GROUP is a reserved word in MySQL.
From the manual:
Most of the reserved words in the table are forbidden by standard SQL as column or table names (for example, GROUP).
You need to pick a different table name (recommended) or surround the word group with backticks, like this:
INSERT INTO `group` (gname, des) VALUES (?, ?)
See the manual entry on Schema Object Names.
Also, make sure you have appropriate spaces; the lack of spacing you have now will cause additional problems in many contexts.
You could have written the complete query in a single line with proper spacing in Java, instead of the SQL way of writing queries. You should be able to identify that the first mistake is with the spacing. This can be corrected from this (what you've used):
String q = "insert into group"
+"(gname,des)"
+"values(?,?)";
to this (the modified query):
String q = "insert into group (gname, des) values(?, ?)";
The above change once made, makes it readable. The next thing as rightly pointed out by #EdCottrell, refrain from using restricted keywords as table names. Depending on the DB type, there could be issues related to this.
Hope this helps!
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
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();
I'm working with EclipseIndigo, EclipseLink and MySQL I have a table called condition I need to keep it with that name but when I execute this command "Query qb = em.createQuery("SELECT c FROM Condition c ")" in eclipse it throws this exception:
Caused by: 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 'condition' at line 1
at sun.reflect.GeneratedConstructorAccessor5.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:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2683)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2144)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2310)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeSelect(DatabaseAccessor.java:931)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:607)
I know that MySQL has a command called condition and that's why this command throws me an exception. The question is: there is a form to keep my table named as condition and I can execute this command "Query qb = em.createQuery("SELECT c FROM Condition c ")"?
Reserved words as identifiers must be quoted with MySQL.
Adding following to Condition entity helps (query can remain as it is):
#Table(name = "`condition`")
I'm using hibernate for all DB operations.
My problem is that, I want to insert an string in table which contains ' e.g. rea9'ea/rea9'ea.
While inserting it I'm getting the following exception
Caused by: 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 'ea/rea9','6a8b2622d3b8ab7de31c0e2496cef2bd',5840,'')' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
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:3515)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3447)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2554) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1761)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2046)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1964)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1949)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
at org.hibernate.engine.query.NativeSQLQueryPlan.performExecuteUpdate(NativeSQLQueryPlan.java:165)
... 8 more
How to solve the problem?
First, have you mapped your table to a POJO? This is, of course, the heart of what makes Hibernate so powerful. If you have, then inserting any String is easy:
MyPOJO m = new MyPOJO();
m.setName("asdf'!##$%^&*()\"1234567890");
HibernateUtil.currentSession().save(m);
If you need to include any string in an HQL statement, then it should be a parameter:
HibernateUtil.currentSession().createQuery("from MyTable where Name=:name")
.setParameter("name","asdf'!##$%^&*()\"1234567890")
.list();