SQL query syntax is wrong - java

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!

Related

MySQLSyntaxErrorException for a join command which is working fine on MySQL workbench

String query = "select Books.BookId, Books.Title, Book_Loans.BranchId, count(Book_Loans.BookLoanId) as NoOfCopies from (Book_Loans join Books"
+ "on (Book_Loans.BookId = Books.BookId)) where Books.BookId = ? group by (Book_Loans.BranchId)";
preparedStatement = connect.prepareStatement(query);
preparedStatement.setLong(1, bookId);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
System.out.println("BookId:"+resultSet.getLong(1)+"\nTitle:"+resultSet.getString(2)+"\nBranchId:"+resultSet.getLong(3)+"\nNoOfCopies:"+resultSet.getInt(4)+"\n");
I am trying to execute the above code snippet but I am getting MySQLSyntaxErrorException as below:
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 '(Book_Loans.BookId = Books.BookId)) where Books.BookId = 75 group by (Book_Loans' 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:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3976)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3912)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1966)
at libraryModel.CopiesCheckedOutFromEachBranchForABook.numberOfCheckedOutCopies(CopiesCheckedOutFromEachBranchForABook.java:36)
at libraryModel.Main.main(Main.java:47)
The tables related to the queries are as below:
Books(BookId, AuthorName, Title, (Publisher)Name)
Book_Loans(BookLoanId, DateOut, DueDate, BranchId, BookId, CardNo)
I am trying to display the number of copies of books checked out from each branch by asking the user to enter the branchId. The query is working fine when I ran it on MySQL workbench but giving me syntax error on Eclipse.
You are missing a space between "books" and "on". Add it and you should be fine.
The SQL query is not correct You got to add a space between Books and on. ALso, there is no need to put additional parenthesis
Use:
String query = "select Books.BookId, Books.Title, Book_Loans.BranchId, count(Book_Loans.BookLoanId) as NoOfCopies from Book_Loans join Books on Book_Loans.BookId = Books.BookId where Books.BookId = ? group by Book_Loans.BranchId";
Your query doesn't make sense. You are saying to aggregate by the branch, and then including information about books. In most databases -- and even in the more recent versions of MySQL -- this would fail.
Your query should look more like this:
select bl.BranchId, count(*) as NumCopies
from Book_Loans bl join
Books b
on bl.BookId = b.BookId
where b.BookId = ?
group by bl.BranchId;
If you want to include information about the book, then the proper way would be to use aggregation functions or to include the columns in the group by:
select bl.BranchId, count(*) as NumCopies, b.BookId, b.Title
from Book_Loans bl join
Books b
on bl.BookId = b.BookId
where b.BookId = ?
group by bl.BranchId, b.BookId, b.Title;
Notes that table aliases make a query easier to write and read.
Of course, once you get the query correct, you need to implement it correctly in your application, including getting the spacing correct around the lines of the query.

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.

SQL Query works in workbench but gives syntax error in java

I ran the query in both sql Workbench and in the executeUpdate() method in java:
in Workbench:
INSERT INTO recentsearches (name) VALUES ("blah");
in java:
statement.executeUpdate("INSERT INTO recentsearches (name) VALUES (\""+name+"\""));
Assuming name = "blah". But I get a syntax error from running the query in java, I've already checked the string value for name. It definitely comes up as "blah", and I didn't forget the speech marks around string values, yet I still get a syntax error.
The error I get in my console is:
check the manual that corresponds to your MySQL server version for the
right syntax to use near '' at line 1
Try to use:
"INSERT INTO recentsearches (name) VALUES("+name+")";
My advice, use PreparedStatement because it has:
-Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.
-Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the values

Delete column from database

I have a database with so many values.How can i delete a specified row using a query.
I am using following query for deletion.I want to delete a row whith the help of colum name=user_name.(user_name=example).
But example named row is not present at the table.is shows error.Any if exist query for this
preparedStatement = (PreparedStatement) connection.prepareStatement("DELETE FROM users WHERE IF EXISTS user_name=example");
preparedStatement.executeUpdate();
The following error occur when i trying to compile
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 'EXISTS user_name='example'' at line 1
remove IF EXISTS
use user_name='example' (with quotes) or even better user_name=? with PreparedStatement
use preparedStatement.executeUpdate()
it shouldnt throw any error even if no result
I think you just forgot the apostrophs that span the String literal 'example':
DELETE FROM users WHERE user_name='example'.
The 'WHERE EXISTS' is unnecessary here!
Greetings
Christopher
I tried here in my computer this way and works fine
PreparedStatement pt =con.prepareStatement("DELETE FROM users WHERE IF EXISTS user_name='"+"example'");
pt.executeUpdate();
I made a temporary table and run it

using combined update and insert with hypersql

I was implementing upsert according to this great post: Insert, on duplicate update in PostgreSQL? and this works really fine with psql. However, I can't fire the same query into hsqldb which i use for testing.
my sql looks like this:
UPDATE account set name = ?, email = ?, type = ?, regts = ?, dao_updated = ? WHERE id = ?;
INSERT INTO account (id, name, email, type, regts, dao_created,dao_updated) SELECT ?,?,?,?,?,?,? WHERE NOT EXISTS (SELECT 1 FROM account WHERE id = ? );
I get the error message:
Caused by: java.sql.SQLSyntaxErrorException: unexpected token: INSERT
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source)
Is this a limitation of hsqldb or am I doing something wrong?
thanks in advance
Leon
HSQLDB supports the MERGE statement for this:
http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_merge_statement
The merge statement is generally more powerful than UPSERT and non-standard alternatives.
Alternatively, you can use CREATE PROCEDURE and define a procedure similar to the PostgreSQL example given in the linked answer.
http://hsqldb.org/doc/2.0/guide/sqlroutines-chapt.html#src_psm_conditional
You can use the GET DIAGNOSTICS statement to find out if the update succeeded.
http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_diagnostics_state
You apparently can't use several statements inside single executeUpdate() call. Please, call twice first time doing UPDATE, next time doing INSERT

Categories