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.
Related
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 .
I am attempting to use the following "Select" statement to set the Session TimeZone before selecting from a Table. The Code below gives me the following exception when executed:
"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 IsActive, HID as EmpNum, NameFirst, NameLast, FROM_UNIXTIME(timeIn) as Ti' at line 1"
Here is the Select statement in context:
private static List<EventLog> getTimeIPEventLog(String date) throws ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {
final String sql =
"SET time_zone='UTC'; Select IsActive, HID as EmpNum, NameFirst, NameLast, FROM_UNIXTIME(timeIn) as TimeIn, FROM_UNIXTIME(timeOut) as TimeOut, ##session.time_zone TimeZone, ##global.time_zone\n" +
"from eventLog el\n" +
"join users u\n" +
"on (u.usersID = el.usersID)\n" +
"where Date(FROM_UNIXTIME(timeIn)) = '" + date + "'\n" +
"order by timeIn desc";
String url = MainApp.HRMSApplicationProperties.getProperty("timeIPJDBCString") + "?user=" + MainApp.timeIPCredentials.getKey() + "&password=" + MainApp.timeIPCredentials.getValue();
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection(url + "&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
List<EventLog> list = FXCollections.observableList(new ArrayList<>(0));
while (resultSet.next()) {
list.add(new EventLog(resultSet.getString("EmpNum"), resultSet.getString("NameFirst"), resultSet.getString("NameLast"), resultSet.getTimestamp("TimeIn"), resultSet.getTimestamp("TimeOut"), resultSet.getString("TimeZone")));
}
return list;
}
I appreciate your assistance
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.
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;
}
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 ..."