MySQLSyntaxErrorException in SQL syntax - java

I am trying to select data from a table using prepared statement. But it seems like I am getting syntax error which I cannot solve alone.
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String dbusername = "root";
String dbpassword = ""; // Change it to your Password
// Setup the connection with the DB
connection = DriverManager.getConnection(url, dbusername,
dbpassword);
String query = "SELECT * FROM admin WHERE username = ? AND password = ?";
try {
// connection.setAutoCommit(false);
selectUser = connection.prepareStatement(query);
selectUser.setString(1, username);
selectUser.setString(2, password);
// Execute preparedstatement
ResultSet rs = selectUser.executeQuery(query);
// Output user details and query
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: " + query);
boolean more = rs.next();
// if user does not exist set the validity variable to true
if (!more) {
System.out
.println("Sorry, you are not a registered user! Please sign up first!");
user.setValid(false);
}
// if user exists set the validity variable to true
else if (more) {
String name = rs.getString("name");
System.out.println("Welcome " + name);
user.setName(name);
user.setValid(true);
}
} catch (Exception e) {
System.out.println("Prepared Statement Error! " + e);
}
} catch (Exception e) {
System.out.println("Log in failed: An exception has occured! " + e);
} finally {
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
System.out.println("Connection closing exception occured! ");
}
connection = null;
}
return user;
}
I get following error.
Prepared Statement 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
But I don't see any error in that code line.

Change
ResultSet rs = selectUser.executeQuery(query);
to
ResultSet rs = selectUser.executeQuery();
when you already prepared the statement in connection.prepareStatement(query); then why to pass the query again in selectUser.executeQuery(query);

what you want to do is use this method
ResultSet rs = selectUser.executeQuery();

You have already loaded your query inside the prepared statement here ,
selectUser = connection.prepareStatement(query);
so execute it by ,
ResultSet rs = selectUser.executeQuery();
Also read ,
How does PreparedStatement.executeQuery work?

Related

rs.next() is always returning false

There are entries in the database but whenever i enter any valid or invalid details in login form it always displays login failed. rs.next() is always returning false. Any solution for this problem ?
Code is as follows:-
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/logindata","root","");
#SuppressWarnings("deprecation")
String sql ="Select * from login Where UserName=' " + textField.getText()+ " 'and Password= ' " + passwordField.getText().toString()+"'";
PreparedStatement stmt =con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
String id=null;
String userId=null;
while(rs.next())
{
id=rs.getString("UserName");
userId=rs.getString("Password");
}
if(id!=null)
System.out.println("Login Success");
else
System.out.println("Login Failed");
con.close();
}
catch(Exception ex) {
System.out.println(ex);
}

Using invalidate table in a prepared statement

I'm attempting to call:
"invalidate metadata " + table_name
If I execute the query directly, I fall foul of a sonarqube rule that states that the code is vulnerable to a SQL Injection attack. (It isn't, as I've validated the table name elsewhere.)
String query = "invalidate metadata " + table;
try (Connection con = hiveConnectionFactory.getConnection(hiveConnDetailsHelperBean)) {
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.execute();
LOGGER.debug("metadata invalidated " + table);
}
} catch (SQLException | MoLiConnectionException e) {
String errorMessage = "Error Running Query: "+ query;
throw new MoLiConnectionException(errorMessage, e);
}
If I attempt to use a prepared statement as suggested by SonarQube I get an exception:
String query = "invalidate metadata ?";
try (Connection con = hiveConnectionFactory.getConnection(hiveConnDetailsHelperBean)) {
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setString(1, table);
stmt.execute();
LOGGER.debug("metadata invalidated " + table);
}
} catch (SQLException | MoLiConnectionException e) {
String errorMessage = "Error Running Query: "+ query;
throw new MoLiConnectionException(errorMessage, e);
}
AnalysisException: Syntax error in line 1:
invalidate metadata 'dru_jhutc.time_test'
^
Encountered: STRING LITERAL
Expected: DEFAULT, IDENTIFIER
CAUSED BY: Exception: Syntax error
My question is: How can I use a prepared statement to get around the sonarqube rule?

JDBC used to validate if a user exists but always returns false?

Trying to use JDBC to handle some logic for validating if a user and password are in the DB and correct.
The method should return true if they are in the DB or false if not
I've tried changing the methods and it always either lets any user in, even if they dont exist, or no one in, even if they are in the DB.
Can someone explain how to fix this, funnily enough it was working the other day but I've changed something and unsure what...
JDBC code
public boolean checkUser(String username, String pass) {
boolean valid = false;
try {
//loading drivers for mysql
Class.forName("org.apache.derby.jdbc.ClientDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/workoutDB", "root", "root");
System.out.println("username = " + username);
System.out.println("pass = " + pass);
String sql = "SELECT * FROM users WHERE (username = '" + username + "' AND password = '" + pass + "')";
System.out.println("lo " + sql);
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(sql);
out.println(valid);
if(rs.next()) {
valid = true;
out.println(valid);
} else {
valid = false;
}
} catch (ClassNotFoundException | SQLException e) {
out.println(e);
}
out.println(valid);
return valid;
}
I've included an image of the console output, the username test, with password tes is in the db.
Sorry it was another class which does the same thing I added the prepared too, it also always returns true or false regardless of if the condition is met.
public boolean checkUser(String username, String pass) {
boolean valid = true;
try {
//loading drivers for mysql
Class.forName("org.apache.derby.jdbc.ClientDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/workoutDB", "root", "root");
System.out.println("username = " + username);
System.out.println("pass = " + pass);
//String sql = "SELECT username FROM users WHERE (username = '" + username + "')";
//String sql2 = "SELECT password FROM users WHERE (password = '" + pass + "')";
//System.out.println(sql);
//System.out.println(sql2);
//Statement statement = con.createStatement();
//ResultSet rs = statement.executeQuery(sql);
//ResultSet rs2 = statement.executeQuery(sql2);
PreparedStatement ps = con.prepareStatement("select * from users where username=? and password=?");
ps.setString(1, username);
out.println("ps "+ps);
ps.setString(2, pass);
out.println("ps "+ps);
ResultSet rs = ps.executeQuery();
valid = !rs.next();
} catch (ClassNotFoundException | SQLException e) {
out.println(e);
}
out.println(valid);
return valid;
}

Java sql delete row

Hello I am trying to delete a row from my database. I am getting no errors but it is doing nothing, any help or advice would be great!
public static void DeleteRow(String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = " + name + ";");
st.executeUpdate();
} catch(Exception e) {
System.out.println(e);
}
}
I guess name is a varchar type in DB so do like this
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = '" + name + "';");
enclose name within single quotes '
Also this is not the way you are using is not the proper way of using Preparedstatement
Us the following way:
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = ?");
st.setString(1,name);
st.executeUpdate();
// your full code after Proper PreparedStatement
public static void DeleteRow(String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = ?");
st.setString(1,name);
st.executeUpdate();
} catch(Exception e) {
System.out.println(e);
}
}
You should never create a SQL statement in Java with String concatenation, it will be vulnerable to sql injection. Please do it this way.
String selectSQL = "DELETE FROM Table WHERE name = ?";
connection.prepareStatement(selectSQL);
preparedStatement.setString(1, name);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "MANASH_APPN","MANASH");
PreparedStatement ps = con.prepareStatement("delete from EMP21 where empid = ?");
ps.setInt(1,90);
ps.executeUpdate();
con.commit();
System.out.println("Records Delete Successfully....");
con.close();
try this bro. use Statement
Statement stmt = connection.createStatement();
String SQL = "DELETE FROM Table WHERE name = '"+name+"'";
stmt.executeUpdate(SQL);
Every open connection must be closed, or it won't get implemented and no errors will be displayed. First learned lesson.
public static void DeleteRow(String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = " + name + ";");
st.executeUpdate();
connection.close();
} catch(Exception e) {
System.out.println(e);
}
}
Hope this helps
this will work
String del="DELETE FROM table WHERE name =('" + name + "')";
:)

How to delete a record (string) JAVA and MYSQL

I successfully can delete an integer but when I tried to make it a STRING it says
"unknown column itemtodelete in where clause but my ITEMTODELETE is a STRING declared in the database not an integer how much It doesn't delete a STRING?
below is my code:
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
int del = (prompt):
if (del == JOptionPane.YES_OPTION){
DelCurRec();
}
}
public void DelCurRec() {
String id = field.getText();
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
try {
Class.forName(connectio);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);
}
Statement stmt = null;
Connection con = null;
//Creates connection to database
try {
con = DriverManager.getConnection("Connection");
stmt = con.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);
}
//Execute the SQL statment for deleting records
try {
stmt.executeUpdate(SQL);
//This closes the connection to the database
con.close();
//This closes the dialog
JOptionPane.showMessageDialog(null,"Deleted Succesfully","Delete Successful",JOptionPane.WARNING_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);
}
}
Do NOT use a Statement use a PreparedStatement instead, otherwise your application will be vulnerable to SQL injections. E.g. someone enters a string like: "'; drop table inventory; --"
The corresponding prepared statment would look something like:
String SQL = "DELETE FROM inventory WHERE ItemCode = ? ";
PreparedStatement pstmt = null;
// get a connection and then in your try catch for executing your delete...
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, id);
pstmt.executeUpdate();
try changing the line:
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
to
String SQL = "DELETE FROM inventory WHERE ItemCode = '"+id+"' ";
I think you need to pass Integer.parseInt(id) and not id...assuming your id is int
This worked for me:
Statement stmt=con.createStatement();
stmt.executeUpdate("DELETE FROM student WHERE reg_number='R18854';");

Categories

Resources