Error in SQL Syntax - java

I am trying to connect to database in Java. It's a simple program.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/servlets","root","");
smt = con.createStatement();
query = "select pass from users where uname = "+uname;
System.out.println(query);
rs = smt.executeQuery(query);
if((rs.getString("pass"))==pass){
out.println("correct pass...logged in..");
}
else {
out.println("Incorrect pass...not logged in..");
}
But it says
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 '#gmail.com'
at line 1
I am trying to verify the password for a particular email-id.

At this line
query = "select pass from users where uname = "+uname;
You have not quoted the uname, so if the value is name#gmail.com this results in a syntax error. I.e. the actual statement being sent to the DB is
select pass from users where uname = name#gmail.com
which is invalid. You should be using PreparedStatement instead
query = "select pass from users where uname = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();

Replace this
query = "select pass from users where uname = "+uname;
to
query = "select pass from users where uname = "'+uname+'" ";
or try
query = "select pass from users where uname = ? ";

Related

MySQL Java prepared statement Syntax error

I need to select rows from mysql table based on various criteria, for example Colour= Black, or size= L.
The code works without the preparedstatement and the question marks, but whenever I attempt to use the question marks the code does not run.
I have read something about typing the question mark like \'?'// but I am not sure about the exact format.
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
Statement stmt = con.createStatement();
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
ResultSet rs = stmt.executeQuery(sql);
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
Also, Size is written out in orange colour, but the error happens also when I only use this sql String
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ?;";
I have looked at like 20 different answers, but didnt find anything helpful, so thanks in advance for any help!
You are executing the query using a normal java.sql.Statement, not using a java.sql.PreparedStatement. This won't work because a normal Statement does not support parameterized queries. So, remove the creation and execution of the Statement, and make sure you execute the statement using the PreparedStatement:
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
try (Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement preparedStmt = con.prepareStatement(sql)) {
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
try (ResultSet rs = preparedStmt.executeQuery()) {
// process result set
}
}
Also note the addition of try-with-resources, which will ensure connections, statements and result sets are closed correctly.

How to convert " ' " to " ` " in java

The syntax that from the java code is not applicable to mysql. The setString() from java will come out with ' and not ` which is not accepted in mysql.
I tried in my localhost to run the code, it really not accepting 'doctor' and only accept ``doctor`.
Below are my code:
PreparedStatement ps = con.prepareStatement("SELECT id FROM ? WHERE id = ?");
ps.setString(1, "doctor");
ps.setInt(2, 123);
ResultSet rs = ps.executeQuery();
and there is 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 ''doctor' WHERE id = 123' at line 1
It's because your code produces following query:
SELECT id FROM 'doctor' WHERE id = 123
As you can see table name is used as a String which is invalid SQL Syntax, so you can either hard code table name and or if you really want it to be dynamic you can achieve it like:
String sql = String.format("SELECT id from %s where id = ?", tblName);
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 123);
ResultSet rs = ps.executeQuery();

Error in sql query to fetch data from wamp server [duplicate]

I had tried several times using prepared statements but it returns SQL exception. here is my code:
public ArrayList<String> name(String mobile, String password) {
ArrayList<String> getdata = new ArrayList<String>();
PreparedStatement stmt = null;
try {
String login = "select mobile, password from tbl_1 join tbl_2 on tbl_1.fk_id=2.Pk_ID where mobile=? and password=?";
String data = "select * from tbl_2 where password='" + password + "'";
PreparedStatement preparedStatement = conn.prepareStatement(login);
preparedStatement.setString(1, mobile);
preparedStatement.setString(1, password);
ResultSet rs = preparedStatement.executeQuery(login);
Statement stmts = (Statement) conn.createStatement();
if (rs.next()) {
System.out.println("Db inside RS");
ResultSet data = stmts.executeQuery(data);
while (data.next()) { /* looping through the resultset */
getdata.add(data.getString("name"));
getdata.add(data.getString("place"));
getdata.add(data.getString("age"));
getdata.add(data.getString("job"));
}
}
} catch (Exception e) {
System.out.println(e);
}
return getdata;
}
While running this, I got the following SQL exception:
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.
Any suggestion to make this work?
any piece of code is appreciated.
You need to use:
preparedStatement.executeQuery();
instead of
preparedStatement.executeQuery(login);
when you pass in a string to executeQuery() that query is executed literally and thus the ? is send to the database which then creates the error. By passing query string you are not execution the "cached" prepared statement for which you passed the values.
For both parameter you use preparedStatement.setString(1, ..); so the first parameter is set two times. but you never set the value for second parameter.
so change
preparedStatement.setString(1, mobile);
preparedStatement.setString(1, password);
to
preparedStatement.setString(1, mobile);
preparedStatement.setString(2, password);

PreparedStatement execution says MySQLSyntaxErrorException although works in MySQL console

I've written the following code (snippet):
conn = Pooling.getDataSource().getConnection();
String databaseName = Configuration.getDatabaseName();
String sql = "SELECT * FROM " + databaseName + ".companies WHERE companyemail = ? AND companypassword = MD5(?)";
PreparedStatement prepStat = conn.prepareStatement(sql);
prepStat.setString(1, username);
prepStat.setString(2, password);
System.out.println("LoginService: prepStat = " + prepStat.toString());
ResultSet rs = prepStat.executeQuery(sql);
...
Now, when I execute this, I'm getting a MySQLSyntaxErrorException. The prepStat.toString() prints:
SELECT * FROM dbname.companies WHERE companyemail = 'comp#comp.com' AND companypassword = MD5('passwort')
And a simple copy and paste to SequelPro successfully return a result.
However, the backend still claims that there is an error in the syntax:
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 companypassword = MD5(?)' at line 1
Maybee I'm blind but I do not see an error here? But what is happening here?
Okay, I found out what the problem was. I used:
ResultSet rs = prepStat.executeQuery(sql);
However, I should have used
ResultSet rs = prepStat.executeQuery();
instead.
Try this:
String sql = "SELECT * FROM '" + databaseName + ".companies' WHERE companyemail=? AND companypassword = MD5(?)";
Notice the single quote before the databaseName variable and after .companies . I think that could be the problem.
Or you could do this:
String sql = "SELECT * FROM ? WHERE companyemail =? AND companypassword = MD5(?)";
PreparedStatement prepStat = conn.prepareStatement(sql);
prepStat.setString(1, databaseName);
prepStat.setString(2, username);
prepStat.setString(3, password);
I believe the problem is at the level of parsing the databaseName to the prepared statement.

setting variables against data retrieved from a database

I am building a simple security system using java (eclipse) and I am using the MYSQL statement to pull data from the database
ResultSet rs = statement.executeQuery("select name, username, password from securitysystem.employee where username = '" + username + "' and password = '" + password + "'");
but what if i wanted to create a variable user= name, how would I do that? name is referring to the name retrieved using the statement above.
Firstly, you should never put your parameter right into a query string.
Instead, do this:
PreparedStatement ps = connection.prepareStatement("select name, username, password "+
"from securitysystem.employee where username = ? and password = ?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
To get the results, do this:
if (rs.next()) { //move to 1st result row
String name = rs.getString(1); //first result column
String user = rs.getString(2); //second result column
// ..etc
}
How about:
while(rs.next()) {
String user = rs.getString("name");
}

Categories

Resources