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

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 ..."

Related

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.

How to delete row in database in MySQL using JSP?

This is my function. It gets two parameter id of the product and a name. the function delete with MySQL command a row in a database. I know the that there are missing lines in my code, I'm stuck and I don't know how to finish it. I also know that my SQL line is not correct. I'm not sure if combined the String "name" right.
public static deletePro(int cat, String name) {
DB db = new DB();
String sql = "delete from products where pname=+'name' and catid=" + cat;
ResultSet rs = db.getResultSet(sql);
try {
while (rs.next()) {
Products prod = new Products();
prod.setNamePro(rs.getString(name));
prod.setAmount(rs.getInt(cat));
}
rs.close();
db.closeCon();
} catch (SQLException e) {
e.printStackTrace();
}
return
}
String sql = "delete from products where pname=+'name' and catid=" + cat;
This should be:
String sql = "DELETE FROM products WHERE pname='" + name + "' and catid = " + cat;
And the preferred way is to use PreparedStatement, which would alleviate the pain of string manipulation in your query by using placeholders:
String sql = "DELETE FROM products WHERE pname= ? and catid = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, cat);
ps.executeUpdate();
Hope this helps.

SELECT a column from a mySQL table and check validation

I have a mySQL table named userinfo with colums- userId, userName, Password, city, age- userId is Pkey and Autoincremnt
When a user Login on a login.jsp, he submits username and Pasword.
These two parameters of login.jsp are received in UserLogin servlet and then checked in userinfo Table. If matched, he could log in.
I tried SELECT but I get numerous error. What should be the correct way:-
try {
String sql = "Select UserName, UserPW From SocialNetwork.RegisteredUser";
conn = ConnectionFactory.getConnection();
PreparedStatement ptmt = (PreparedStatement) conn
.prepareStatement(sql);
ptmt.executeQuery();
Statement stmt = (Statement) conn.createStatement();
s = connection.prepareStatement("select id_usuario, id_grupo from usuarios_grupos where id_grupo = ?");
//storing user data in ResultSet
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String refName = rs.getString("UserName");
String refPass = rs.getString("UserPW");
if (user.equals(refName) && pw.equals(refPass) ) {
out.println("<html>");
out.println("<body>");
out.println("You are In");
out.println("</body>");
out.println("</html>");
System.out.println("sucess");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
by using Statement interface you can not dynamically set the values. use PreparedStatement interface for second query.
import package in you class import javas.sql.*;
try {
String sql = "Select UserName, UserPW From SocialNetwork.RegisteredUser UserName = ?";
conn = ConnectionFactory.getConnection();
PreparedStatement ptmt =conn.prepareStatement(sql);
ptmt.setString(1, user)
ResultSet rs= ptmt.executeQuery();
while (rs.next()) {
String refName = rs.getString(1);//field index of user name
String refPass = rs.getString(2);//field index of password
if (user.equals(refName) && pw.equals(refPass) ) {
out.println("<html>");
out.println("<body>");
out.println("You are In");
out.println("</body>");
out.println("</html>");
System.out.println("sucess");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
Are you asking for the entire code listing? in your current code you seem to be executing some queries for no reason, then getting a list of all users and iterating through them looking for a match. Try using a query like
sql ="Select UserName, UserPW From SocialNetwork.RegisteredUser where UserName=?"
ResultSet rs = stmt.executeQuery(sql);
then check the password in code
if(rs.next()){
String refPass = rs.getString("UserPW");
if (pw.equals(refPass) )
}

SQL syntax error but copied from 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;
}