Java Preparedstatement error when reading from MySql Database - java

I'm working on a simple application that pulls data from a local database. The below code works fine when I use a string for the SQL query, but I can not get it to work with PreparedStatement. I have reviewed similar problems posted here but most of those were caused by doing this, preparedStmt.executeQuery(query); instead of this preparedStmt.executeQuery(); Here is the code,
private final String POSTTITLE= "posttitle"; // DB Column name
private final String POSTCONTENT= "content"; // DB Column name
public String getDbContent(){
try{
String query ="select values(?, ?) from blog";
PreparedStatement preparedStmt = this.connect.prepareStatement(query);
preparedStmt.setString (1,POSTTITLE);
preparedStmt.setString (2,POSTCONTENT);
ResultSet rs = preparedStmt.executeQuery();
rs.next();
return(rs.getString(this.POSTCONTENT)); //Will replace with loop to get all content
} catch(Exception e) {
System.err.println("Error Reading database!");
System.err.println(e);
return("Error: "+e);
}
}
This is the error I get:
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 ''posttitle', 'content') from blog' at line 1

Parameters in prepared statements are for values - you're trying to use them to select fields. They just don't work that way.
In this very specific instance, you'll need to make the SQL dynamic. However, you'll want to make sure that whatever code you have to allow your columns to be specified is tightly constrained to avoid SQL injection attacks. (For example, you could have an enum with the columns in, or a whitelist of allowed values.)

Try concatenating select query:
String query ="select "+POSTTITLE+","+POSTCONTENT+" from blog";
Remember that prepared statements are for values, not query parameters, for them we use simply concatenations.

Try this:
String query ="select POSTTITLE, POSTCONTENT from blog";
PreparedStatement preparedStmt = this.connect.prepareStatement(query);
ResultSet rs = preparedStmt.executeQuery();
rs.next();
There is no need to use field names as parameter.

Related

Working on this Java project where I need to be able to delete data from the database on user's request

The query inside MySQL is working:
DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'
I can delete data inside MySQL, but the problem is whenever I try to remove the account_tags from my Java application, it throws an error:
java.sql.SQLSyntaxErrorException: 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 'DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'' at line 2
Here's my Java SQL query:
Statement statement = dbConnection.createStatement();
String sql = "SELECT * FROM "+databaseName+"."+tableName+";\n" +
"DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = '"+AccountTag+"';";
statement.executeQuery(sql);
The error isn't giving me much to work with, so I really have no idea what is wrong with the program.
Did you add the allowMultiQueries=true
If not then you can add that while you sending the connecting request to your database. So you need to append the allowMultiQueries=true in your to database URL.
Like this:
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
String sql = "DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
int updateCount = statement.executeUpdate();
System.out.printf("%s: %d records deleted.%n", tableName, updateCount);
}
The only thing used is the DELETE, for which one should use executeUpdate.
One definitely should use a PreparedStatement as many code checkers will give alarms otherwise. It escapes things like ', handles types of the arguments, and possible conversions, and especially is a security feature against SQL injection.
The System.out usage is bad style, better would be using a logger.
try-with-resources automatically closes the PreparedStatement even with a raised exception or break/return.
When doing both database operations, it seems better to use two (prepared) statements, as the first returns a ResultSet.
So:
String sql = SELECT * FROM "+databaseName+"."+tableName + "\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
try (ResultSet rs = statement.executeQuery()) {
...
}
}
Better to separate statements with an If condition :
String sql1="SELECT * FROM "+databaseName+"."+tableName;
String sql2="DELETE FROM "+databaseName+"."+tableName+" "+
"WHERE account_tags = '"+AccountTag+"';
statement.executeQuery(sql1);
statement.executeUpdate(sql2);

How to set variables into a JDBC statement?

It works when i try to insert variables for example :
String insertStr="INSERT INTO table1(username1,password1) VALUES(\"john\",\"password\")";
but unable to insert using variable
String a=username.getText();
String b=password.getText();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db1","root","");
Statement stmt=con.createStatement();
String insertStr="INSERT INTO table1(username1,password1) VALUES(a,b);";
stmt.executeUpdate(insertStr);
} catch (Exception e) { }
Use [PreparedStatement][1] instead of your way, because your way can be a victim of SQL Injection or Syntax errors :
String insertStr = "INSERT INTO table1(username1,password1) VALUES(?, ?)";
try (PreparedStatement pst = con.prepareStatement(insertStr)) {
pst.setString(1, a);
pst.setString(2, b);
pst.executeUpdate();
}
For reason of security I don't suggest to get password with getText(), instead use getPassword(), so you can use :
pst.setString(1, username.getText());
pst.setString(2, new String(passwordField.getPassword()));
Take a look at this :
getText() vs getPassword()
Why getText() in JPasswordField was deprecated?
[1]: https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html
Since you are inserting "a" and "b" as String, not their variable values.
String insertStr="INSERT INTO table1(username1,password1) VALUES("+a+","+b+");";
should do it, but I would recommend to use a prepared statement here: https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
The most common way to insert variable values into sql is to use the PreparedStatement Object
With this object, you can add variable values into a SQL Query without fearing of SQL injection.
Here an example of PreparedStatement :
//[Connection initialized before]
String insertStr="INSERT INTO table1(username1,password1) VALUES(?,?);";
PreparedStatement myInsert = myConnectionVariable.prepareStatement(insertStr); // Your db will prepare this sql query
myInsert.setString(1, a); //depending on type you want to insert , you have to specify the position of your argument inserted (starting at 1)
myInsert.setString(2, b); // Here we set the 2nd '?' with your String b
myInsert.executeUpdate(); // It will returns the number of affected row (Works for UPDATE,INSERT,DELETE,etc...)
//You can use executeQuery() function of PreparedStatement for your SELECT queries
This is safer than using String concatenation like this : VALUES("+a+","+b+");
Take a look at Java Doc for more information ;)

How to inject a SQL command to drop a table in java

My java code for SQL Query is
String sqlSt="INSERT INTO users(id,name,place) values ("+null+",'"+request.getParameter("name")+"','"+request.getParameter("place")+"');";
I have tried out
name= a'); DROP TABLE users; --
as well as
place =a'); DROP TABLE users; --
but it returns an Ecxeption as below
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 'DROP TABLE users; --','chennai')' at line 1
Note: when i tried the same in mysql command line. It worked!!!! i don't know what happens in jdbc
The real problem is actually JDBC, it only allows one sql if you dont tell it otherwise.
Look at this question for more info:
Multiple queries executed in java in single statement
But also i would try this instead, name =
a',''); DROP TABLE users; --
Since you specificed 3 columns in your insert:
(id,name,place)
You need to provide 3 values for the sql to be valid, not just 2.
Also you can sent the text null, sending a java null value is not necessary and i am not even sure how that works. I think this might be better:
String sqlSt="INSERT INTO users(id,name,place) values (null,'"+request.getParameter("name")+"','"+request.getParameter("place")+"');";
Instead of null, use an empty string ''
String sqlSt = "INSERT INTO users(id, name, place) values ('', '" + request.getParameter("name") + "', '" + request.getParameter("place") + "');";
It's better to use prepared statements to avoid confusion.
String sqlSt = "INSERT INTO users(id, name, place) values ('', ?, ?)";
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(query);
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("place"));
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
ps.close();
}
The real problem is with your Query. It is better to use a PreparedStatement for executing a query.
Your Code should be :
String sqlSt="INSERT INTO users(id,name,place) values (?,?,?)";
PreparedStatement pstmt = null;
try{
pstmt = dbConnection.prepareStatement(sqlSt);
pstmt.setString(1,null);
pstmt.setString(2,request.getParameter("name"));
pstmt.setString(3,request.getParameter("place"));
pstmt.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
}
If you don't want to use a PreparedStatement, just remove last ; from your query.
So your query will be :
String sqlSt="INSERT INTO users(id,name,place) values ("+null+",'"+request.getParameter("name")+"','"+request.getParameter("place")+"')";

Using PrepareStatement to get data with configurable table name

I'm trying to get some data from Oracle 11.2 using java and jdbc driver.
My goal is to get data from database using CallableStatement, but with no luck - I'm not able to put table name as parameter. I would like to have configurable table name in query. However, it would be good to keep it sanitized.
Here is an example..
public void getData() throws SQLException {
Connection conn = Config.getSQLConnection();
String query = "SELECT * FROM ?";
PreparedStatement st = conn.prepareStatement(query);
st.setString(1, Config.DATATABLE_NAME);
ResultSet rs = st.executeQuery();
if (rs.next()) {
System.out.println("SUCCESS");
System.out.println("ID:" + rs.getString("ID"));
} else {
System.out.println("FAILURE");
}
}
Is this the way it should work? Or am I missing something, or misused it?
A CallableStatement is used to make call to stored procedures.
From javadoc:
The interface used to execute SQL stored procedures
Use a PreparedStament instead for a normal select.
As an additional note don't pass the name of the table as parameter.
Create the query using concatenation.
Instead of
String query = "SELECT * FROM ?";
use
String query = "SELECT * FROM " + Config.DATATABLE_NAME;
You should use PreparedStatement instead of CallableStatement.
CallableStatement is an interface which is used to call stored procedures.

why this mysql insert is failing in java JDBC

try
{
String sql="INSERT INTO `task`(`task`,`time`) VALUES(?,?)";
PreparedStatement stmt=this.connection.prepareStatement(sql);
stmt.setString(1, this.task);
stmt.setInt(2, this.time);
//stmt.
Boolean res= stmt.execute(sql);
}
catch(Exception e)
{
System.err.println(e);
}
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 '?,?)' at line 1
Don't use
stmt.execute(sql);
use
stmt.execute();
to execute your PreparedStatement.
The first one you are using tries to execute the given string, which is obviously not what you want to execute due to the placeholder '?' values in it (it is a method of the java.sql.Statement interface).
The second one is a method from java.sql.PreparedStatement and executes the PreparedStatement with the values you entered through the setXXX() methods.
Also, in your case you don't need ticks in your string, you can just write
String sql="INSERT INTO task(task,time) VALUES(?,?)";

Categories

Resources