SQL syntax error but copied from MYSQL - mysql

i have an SQL query which i copied from MYSQL and i removed the quotations however, it doesnt seem to work.
conn = connect();
selectStatement = "UPDATE student SET Item ? = ?, Type ? = ? WHERE ID = ?";
System.out.println(selectStatement);
if(conn != null)
{
preparedStatement = conn.prepareStatement(selectStatement);
preparedStatement.setString(2, id);
preparedStatement.setInt(1, location);
preparedStatement.setInt(3, location);
preparedStatement.setString(4, type);
preparedStatement.setString(5, userId);
preparedStatement.executeUpdate();
return true;
I am not sure why it does not work as the exception thrown is this
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 '1 = 'sad', Type 1 = 'asd' WHERE ID = 'student1'' at line 1

In the end this worked.
conn = connect();
selectStatement = "UPDATE student SET `Item " + location + "` = ? , `Type " + location + "` = ? WHERE ID = ?";
System.out.println(selectStatement);
if(conn != null)
{
preparedStatement = conn.prepareStatement(selectStatement);
preparedStatement.setString(1, id);
preparedStatement.setString(2, type);
preparedStatement.setString(3, userId);
preparedStatement.executeUpdate();
return true;
}

Related

Atomicity in Spring Boot JDBC and MySQL

I am sure there are various similar questions regarding this. But I am still not sure about the atomicity in Spring boot JDBC.
So my project is a Basic Online Cloth Store. Where the user adds some products into the cart and then checkout. Each user has some credits (virtual money).
So to implement checkout I need to execute Atomic operation on the Database. Basically, there are two things that I have to check while checkout.
User has enough credits while checkout.
There is enough stock.
So instead of doing normal JDBCtemplate.update(), I performed the queries and update by obtaining Connection and Then using Prepared statement. Below is my code for the checkout function.
public boolean validCart(String username) throws SQLException {
Connection conn = DataSourceUtils.getConnection(template.getDataSource());
try {
conn.setAutoCommit(false);
PreparedStatement ps = conn.prepareStatement("SELECT credits from user where username = ?");
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
rs.next();
int credits = rs.getInt(1);
ps = conn.prepareStatement("SELECT cart.quantity*stock.price from cart,stock where cart.username = ? and stock.cloth_id = cart.cloth_id and stock.size = cart.size");
ps.setString(1, username);
rs = ps.executeQuery();
rs.next();
int cost = rs.getInt(1);
Boolean flag = false;
if(credits >= cost){
String sql = "SELECT COUNT(*) from cart,stock where cart.username = ? and cart.size = stock.size and cart.cloth_id = stock.cloth_id and cart.quantity > stock.quantity";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
rs = ps.executeQuery();
rs.next();
int bad = rs.getInt(1);
sql = "SELECT COUNT(*) FROM cart WHERE username = ? and (cloth_id,size) NOT IN (SELECT cloth_id,size from stock)";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
rs = ps.executeQuery();
rs.next();
bad += rs.getInt(1);
if(bad == 0){
sql = "UPDATE cart INNER JOIN stock on cart.cloth_id = stock.cloth_id and stock.size = cart.size SET stock.quantity = stock.quantity - cart.quantity where cart.username = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.executeUpdate();
sql = "UPDATE user SET credits = credits - ? where username = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, cost);
ps.setString(2, username);
ps.executeUpdate();
sql = "INSERT INTO order_details(username,cloth_id,size,quantity,price) SELECT cart.username,cart.cloth_id,cart.size,cart.quantity,stock.price from cart,stock where cart.username = ? and cart.cloth_id = stock.cloth_id and cart.size = stock.size";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.executeUpdate();
sql = "DELETE FROM cart WHERE username = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.executeUpdate();
flag = true;
}
}
conn.commit();
conn.setAutoCommit(true);
return flag;
} catch (SQLException e) {
conn.rollback();
e.printStackTrace();
}
return false;
}
But I am still not sure If operations are atomic that is the problem of race condition will not happen here.
And what should be the best method to perform this type of operation in general?.

"JSP First Connection cause second connection not running when it had ended"

I'm trying to get two data(GenreID & GameID) from two different tables(genre & games) and insert them into another table(games_genre). However, it will close the connection to the database after inserting the GenreID successfully even though i had created another new connection to the database.
I have tried to create connection1 and connection2 to the same database. Connection1 is used to insert GenreID and connection2 is used to insert GameID
<%# page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
String gametitle = request.getParameter("gametitle");
String [] checkbox1 = request.getParameterValues("checkbox");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(connURL);
Connection conn2 = DriverManager.getConnection(connURL);
Statement stmt = conn.createStatement();
if (checkbox1!= null){
for(String s: checkbox1){
String sqlStr2 = "Select * FROM genre WHERE GenreName='" + s + "'";
ResultSet rs = stmt.executeQuery(sqlStr2);
while(rs.next()){
String genreid = rs.getString("GenreID");
String sqlStr3 = "INSERT INTO games_genre(GenreID) VALUES ('" + genreid + "')";
int j = stmt.executeUpdate(sqlStr3);
if (j>0) {
out.println("Adding GenreID Successfully!");}
}
}
}
conn.close();
Statement stmt2 = conn2.createStatement();
String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
ResultSet rs2 = stmt2.executeQuery(sqlStr4);
if(rs2.next()){
String gameid = rs2.getString("GameID");
String sqlStr5 = "INSERT INTO games_genre(GameID) VALUES ('" + gameid + "')";
int k = stmt2.executeUpdate(sqlStr5);
if (k>0) {
out.println("Adding GameID Successfully!");
}
}
conn2.close();
} catch (Exception e) {
out.println("Error :" + e);
}
Adding Game Successfully! Adding GenreID Successfully! Error :java.sql.SQLException: Operation not allowed after ResultSet closed
I don't understand that why do you need to create two Connection as you need to access same database . So ,just create multiple Statement to execute multiple query like below :
Statement stmt=null;
Statement stmt2=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(connURL);
stmt = conn.createStatement();
if (checkbox1!= null){
....
}
<!--using same conn object -->
stmt2 = conn.createStatement();
String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
ResultSet rs2 = stmt2.executeQuery(sqlStr4);
if(rs2.next()){
...
}
<!--finally close connection-->
conn.close();
} catch (Exception e) {
out.println("Error :" + e);
}
Note : Also try using PreparedStatement for preventing from Sql Injection as concatenating values into a query string is unsafe .

You have an error in your SQL syntax (...) near ;

I got this message, and I couldn't find any error:
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 'where id ='null'' at line 1
I assumed this code was wrong, but it turned out it isn't.
ResultSet rs = stmt.executeQuery("select password" +
"from userinfo where id = '" + id + "';");
This is full code of error file.
private boolean checkLoginInfo(String id, String password) throws ServletException
{
Connection conn = null;
Statement stmt = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/webdb", "root", "1234");
if (conn == null)
throw new Exception("can't connect to database.<BR>");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select password" +
" from userinfo where id = '" + id + "';");
if (!rs.next())
return false;
String correctPassword = rs.getString("password");
if (password.equals(correctPassword))
return true;
else
return false;
}
There is a missing space between password and from:
select password" + "from userinfo where id = '" + id + "';"
Try this:
"SELECT password FROM `userinfo` WHERE id = '"+id+"'"
You should furthermore read about:
Escaping SQL queries
Authentication/Authorization (why do you select the password only?)
Code formatting
Edit 1:
The error messages tells us, you are setting the id to 'null' (String, because of ''), not NULL. If your id is expecting an Integer, but you are providing a String, it will break.

inserting reservation to database

This has been driving me crazy and I'm sure it's something simple. I'm getting a 'values must contain at least one element' error from server when I try to input a reservation from the table that comes up. It's all running ok. No matter if I use quotes in the VALUES section or plus(+)symbols or quotes over the separating commas I get different error messages. When I put quotes over table_num I get and error telling me that you cant insert CHAR into INTEGER. When I remove quotes I get error telling me -
Severe: java.sql.SQLSyntaxErrorException: Column 'TABLE_NUM' is either not in any table in the FROM list or appears within a join specification etc. Could anyone tell me what is going on? Here's the jsp code. Thanks in advance.
<%
int tableNum = 0;
String firstName = null;
String lastName = null;
String Address = null;
int Phone = 0;
java.sql.Date date = null;
int People = 0;
if (request.getParameter("table_num")!=null){
tableNum = Integer.parseInt(request.getParameter("table_num"));
}
if (request.getParameter("first")!=null){
firstName = request.getParameter("first");
}
if (request.getParameter("last")!=null){
lastName = request.getParameter("last");
}
if (request.getParameter("address")!=null){
Address = request.getParameter("address");
}
if (request.getParameter("phone")!=null){
Phone = Integer.parseInt(request.getParameter("phone"));
}
if (request.getParameter("date")!=null){
java.util.Date utilDate = new java.util.Date(request.getParameter("date"));
date = new java.sql.Date(utilDate.getTime());
}
if (request.getParameter("people")!=null){
People = Integer.parseInt(request.getParameter("people"));
}
if(tableNum != 0 && firstName != null && lastName != null && Address != null && Phone != 0 && date != null && People != 0){
String URL = "jdbc:derby://localhost:1527/Reservations";
String USERNAME= "johnpaul";
String PASSWORD= "purlease";
Connection myCon = null;
Statement ste = null;
PreparedStatement preparedStmt = null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Connecting to DB...");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Reservations","johnpaul", "purlease");
System.out.println("Connected successfuly");
System.out.println("Inserting records into table");
Statement st = con.createStatement();
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS(TABLE_NUM,FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE,DATE,NUMBER_IN_PARTY)VALUES(table_num,first,last,address,phone,date,people)";
st.executeUpdate (query);
System.out.println("Records inserted");
}catch(SQLException se){
se.printStackTrace();
}catch(ClassNotFoundException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
%>
Your problem appears to be here:
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (table_num, first,last,address,phone,date,people)";
Two things here:
1. Escape your strings; and
2. Concatenate the values in your variables to the string.
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (" + table_num + ", '" + first + "', '" + last + "', '" + address + "', " + phone + " , '" + date + "', " + people + ");";
You may have to verify the format that your database engine expects the date field.

JDBC4/MySQL syntax error: when retrieving data from mysql table

Is there anything wrong in the code below?
String sql = "SELECT username, password FROM REGCUSTOMERS" + "WHERE username = ? AND password = ?";
I'm trying to get the data from the username and password column of REGCUSTOMERS table.
Eclipse 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 '= ? AND password = ?' at line 1
private boolean isAuthenticated(String userid, String password) {
// JDBC logic to verify from database.
try {
Class.forName(driverName);
Connection conn = null;
PreparedStatement st = null;
String sql = "SELECT username, password FROM REGCUSTOMERS" + "WHERE username = ? AND password = ?";
conn = DriverManager.getConnection(databaseURL, USERNAME, PASSWORD);
st = conn.prepareStatement(sql);
ResultSet rs = st.executeQuery(sql);
if (rs.getString("username") != userid && rs.getString("password") != password) {
return false;
}
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
You have no space between REGCUSTOMERS and WHERE. Add the space and you should be fine:
String sql = "SELECT username, password FROM REGCUSTOMERS " + "WHERE username = ? AND password = ?";
This part:
... FROM REGCUSTOMERS" + "WHERE username ...
Will result in the following SQL:
FROM REGCUSTOMERSWHERE
That of course is wrong.
The + doesn't make sense there, but if you want it, you need a space at least on one side
"... FROM REGCUSTOMERS " + "WHERE username ..."