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(?,?)";
Related
The code:
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/smtp_program","root","xxxx");
PreparedStatement stmt =
con.prepareStatement("DELETE FROM smtp_program.users WHERE username=?");
stmt.setString(1,"'"+user+"'");
stmt.executeUpdate();
} catch (Exception e) {
System.out.println(e);
}
variable user is being passed in as a String.
error its returning: [42S22][1054] Unknown column 'test1' in 'where clause'
Remove the single quotes:
stmt.setString(1, user);
the quotes are not needed as executeUpdate() will fix the statement correctly, by checking the type of the parameters and since you have used setString() the final statement will wrap test1 inside single quotes:
DELETE FROM smtp_program.users WHERE username='test1'
Your code passes 'test1' to setString() and this results to:
DELETE FROM smtp_program.users WHERE username='''test1'''
because executeUpdate() escapes the single quotes by adding 2 more at the start and at the end and this is interpreted as the column name/alias 'test1' instead of a string literal.
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")+"')";
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.
Please help.. I have search it. But I still don't know where is my fault. Maybe I just miss something.
Here is the error :
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 '?, ID_JABATAN=?, TANGGAL_MASUK=?, TANGGAL_KELUAR=?, ID_JENIS_KARYAWAN=? WHERE ID' at line 1
And this is my code :
try {
DBConnection knk = new DBConnection();
Connection conn = knk.bukaKoneksi();
String sql = "UPDATE KARYAWAN SET NAMA_KARYAWAN=?, ID_JABATAN=?, TANGGAL_MASUK=?, TANGGAL_KELUAR=?, ID_JENIS_KARYAWAN=? WHERE ID_KARYAWAN=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, karyawan.getNamaKaryawan());
ps.setInt(2, karyawan.getIdJabatan());
ps.setDate(3, karyawan.getTanggalMasuk());
ps.setDate(4, karyawan.getTanggalKeluar());
ps.setInt(5, karyawan.getIdJenisKaryawan());
ps.setInt(6, karyawan.getIdKaryawan());
int hasil = ps.executeUpdate(sql);
return hasil > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
And the column of the table :
Try this:
int hasil = ps.executeUpdate();
remove the Parameter from int hasil = ps.executeUpdate(sql);
if you call it with Parameter, the query will be executet, not the prepared Statement.
See the javadoc:
int executeUpdate(String sql)
throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or
DELETE statement or an SQL statement that returns nothing, such as an
SQL DDL statement. Note:This method cannot be called on a
PreparedStatement or CallableStatement. Parameters:sql - an SQL Data
Manipulation Language (DML) statement, such as INSERT, UPDATE or
DELETE; or an SQL statement that returns nothing, such as a DDL
statement.Returns:either (1) the row count for SQL Data Manipulation
Language (DML) statements or (2) 0 for SQL statements that return
nothingThrows:SQLException - if a database access error occurs, this
method is called on a closed Statement, the given SQL statement
produces a ResultSet object, the method is called on a
PreparedStatement or CallableStatementSQLTimeoutException - when the
driver has determined that the timeout value that was specified by the
setQueryTimeout method has been exceeded and has at least attempted to
cancel the currently running Statement
int executeUpdate()
throws SQLException
Executes the SQL statement in this PreparedStatement object, which
must be an SQL Data Manipulation Language (DML) statement, such as
INSERT, UPDATE or DELETE; or an SQL statement that returns nothing,
such as a DDL statement. Returns:either (1) the row count for SQL Data
Manipulation Language (DML) statements or (2) 0 for SQL statements
that return nothingThrows:SQLException - if a database access error
occurs; this method is called on a closed PreparedStatement or the SQL
statement returns a ResultSet objectSQLTimeoutException - when the
driver has determined that the timeout value that was specified by the
setQueryTimeout method has been exceeded and has at least attempted to
cancel the currently running Statement
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con1=DriverManager.getConnection("jdbc:odbc:MyDatabase");
st1=con1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
System.out.println("Connect database in BallMoves1.java .......");
/*the below line giving error*/
rs1 = st1.executeQuery("insert into highscore" + " (score) " + "values('"+score+"')");
System.out.println("Score is inserted..");
System.out.println("Score......."+score);
}catch(Exception e){ e.printStackTrace();}
/*highscore is table and attributes of table are (sid,score).
the resulting error is:
Connect database in BallMoves1.java .......
java.sql.SQLException: No ResultSet was produced
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:258)
at BallMoves1.move(BallMoves1.java:378)
at BallMoves1.run(BallMoves1.java:223)
at java.lang.Thread.run(Thread.java:744)*/
You're calling executeQuery on something that isn't a query. But instead of calling execute with the same SQL, you should use a PreparedStatement:
String sql = "insert into highscore (score) values (?)";
try (Connection conn = DriverManager.getConnection("jdbc:odbc:MyDatabase");
PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setInt(1, score);
statement.executeUpdate();
conn.commit();
}
Always use parameterized SQL, instead of plugging the values directly into the SQL - that protects you from SQL injection attacks, conversion errors, and hard-to-read code.
Use a try-with-resources statement (as I have) to automatically close the statement and connection at the end of the block.