Getting MySQLSyntaxErrorException? - java

I have this code :
String check="SELECT COUNT(*) as check FROM recordstudent WHERE STUDENT_ID="+T_STUDENT_ID+" AND COURSE_ID="+T_COURSE_ID+" AND PACKAGE_ID="+T_PACKAGE_ID+" AND ACTIVITY_ID="+T_ACTIVITY_ID+" AND DATE="+T_DATE+ ";";
rs=myStmt.executeQuery(check);
int ch=0;
while(rs.next()){
ch=Integer.parseInt(rs.getString("check"));
}
if(ch==0)
{
String insertRecord="insert into recordstudent"+
"(STUDENT_ID,COURSE_ID,PACKAGE_ID,ACTIVITY_ID,TEST_NAME,DATE,SCORE,TOTAL_MARKS,PERCENTAGE,CORRECT_ANSWER,TOTAL_QUESTIONS,STUDENT_NAME,SCORE_PER_DIVISION,ATTEMPTS)"+
"VALUES("+
"'"+T_STUDENT_ID+"',"+
"'"+T_COURSE_ID+"',"+
"'"+T_PACKAGE_ID+"',"+
"'"+T_ACTIVITY_ID+"',"+
"'"+T_TEST_NAME+"',"+
"'"+T_DATE+"',"+
"'"+T_SCORE+"',"+
"'"+T_TOTAL_MARKS+"',"+
"'"+T_PERCENTAGE+"',"+
"'"+T_CORRECT_ANSWERS+"',"+
"'"+T_TOTAL_QUESTIONS+"',"+
"'"+T_STUDENT_NAME+"',"+
"'"+T_SCORE_PER_DIVISION+"',"+
"'"+t+"'"
+");";
myStmt.execute(insertRecord);
}
This snippet should insert the data in database only if the ch=0 .But I am getting this 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
'check FROM recordstudent WHERE STUDENT_ID=11 AND COURSE_ID=2 AND PACKAGE_ID=11 A'
at line 1
Can Anyone help me and solve my problem ?

Fundamentally: don't build your SQL this way. I notice that you've put quotes round the values in the "insert" SQL statement - but not in the "select" one. That's the start of the problem - but you shouldn't be including values like this in your SQL to start with. You should use parameterized SQL via PreparedStatement, and set values for the parameters. Benefits:
You can see your actual SQL more easily, so you'll be able to spot syntax errors. (This is basically keeping your code separate from your data.)
(Very important) You won't be open to SQL injection attacks
You won't need to worry about conversion issues for numbers, dates and times etc
There are other problems in your SQL (such as spaces and check being a reserved word in MySQL), but the very first thing you should fix is how you use values. Until you've done that, your code is inviting security problems.
(You should then start using more conventional variable names than T_STUDENT_NAME etc, but that's a different matter.)

check is a reserved word. Surround it with backticks: `check`

Try this
SELECT COUNT(*) as 'check' FROM recordstudent....
instead of
SELECT COUNT(*) as check FROM recordstudent....
I think check is a keyword

Related

INSERT INTO Statement automatically adds thousand separators to java integer starting at 1000k

I encountered a weird problem:
I have a column "MaxDealtDamage" which is for instance lower then 1000000 (1000k).
code is like this:
class xyz = PlayerData.GetData(player);
xyz.LoginTimes++;
PlayerData.SetData(xyz, player);
When it is 1000000 (1000k) or higher this error is beeing send:
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 '.000, MaxDefense = 0 WHERE UUID='d839d1f0-ad5b-4922-841c-1d6ee05d9f56'' at line 1
Its behaving like it would try to give him a String containing "4.000.000" but its an integer with the value "4000000" (4000k). For beeing sure the output in runtime is 4000000 I doublechecked it.
Here the query:
MessageFormat.format("INSERT INTO PlayerData(UUID,VIPExpirationDate,IPv4,FirstPlayTime,LastPlayTime,TotalPlayTime,TotalLogins,MaxDealtDamage,MaxDefense) "
+ "VALUES(''{0}'',''{1}'',''{2}'',''{3}'',''{4}'',{5},{6},{7},{8});", data.UUID.toString(), DBDateFormat.format(data.VIPExpirationDate), data.IPv4, DBDateFormat.format(data.FirstPlayTime), DBDateFormat.format(data.LastPlayTime), data.TotalPlayTime, data.TotalLogins, data.MaxDealtDamage, data.MaxDefense);
MessageFormat is not a tool for creating SQL statements. It's a simple utility for building text messages with correct formatting.
You are supposed to use PreparedStatement with bind parameters as explained in the Using Prepared Statements tutorial. JDBC will take care of escaping and formatting the supplied values so they can be received by the database server while preventing SQL Injections.

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

Java + MySQL - Syntax error but the statement is correct

My program executes INSERT query. When I run it, I get an 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 words(lang1, lang2, category, lang2_code, user) SELECT 'ahoj', 'hell' at line 1
I tried to print the actual statement to the stdout:
SET #lang:='Angličtina', #categ:='Nová';
INSERT INTO words(lang1, lang2, category, lang2_code, user)
SELECT 'ahoj', 'hello', c.id, l.id, 1 FROM categories c, languages l
WHERE c.name = #categ AND l.name = #lang;
As you can see, the statement is altered in the log. 'hell' instead of 'hello'. When I copy that into the mysql command line and execute, it works just fine so I assume the problem is in the JDBC somewhere.
That's not one statement. If you want to use more than one statement at a time, don't use a PreparedStatement but for example addBatch but it seems that here you should simply issue 2 JDBC statements, one after the other.

I have stuck with the simplest SQL query in java

I can't find the correct syntax of the following query in java,please help me.
String st = "SELECT COUNT('"+id+"') FROM '"+selected_table+"' ";
String st = "SELECT COUNT('"+id+"') FROM '"+selected_table+"'";
I think that the mistake is how to end the query...
Since I got the error Check the manual that corresponds to your MySQL server version for the right syntax to use near ''Customer'' at line 1
when I choose Customer table
You want to use backticks instead of single quotes around your object names.
String st = "SELECT COUNT(`"+id+"`) FROM `"+selected_table+"` ";
Table names should be surrounded by tick marks (`), not single quotes (')
String st = "SELECT COUNT('"+id+"') FROM `"+selected_table+"`";
^ use tick marks ^
What are the values of id and selected_table? What is the actual query string that is sent to the database?
Also, it's rarely a good idea to manually build a query like this using string concatenation. This makes it very easy for a bug to result in a gaping security hole, and it's a lot more difficult (and risky) to try to secure this approach than it is to just do it right.
Looks from your query that you are enclosing your id and selected_table in single quotes... For example, SELECT COUNT('ID') FROM 'CUSTOMER' which is wrong. should be in backtics `` or nothing...

Categories