I am trying to insert data in to MySQL in encrypted format using prepared statement. But I am getting this error. I think my query is correct.
Connection con=null;
PreparedStatement psmt1=null;
String tit=request.getParameter("tit");
String min=request.getParameter("minvalue");
String max=request.getParameter("maxvalue");
String disc=request.getParameter("disc");
System.out.println(tit);
String [] title=tit.split(":");
try{
con=databasecon.getconnection();
psmt1=con.prepareStatement("insert into medication(tid,titname,minvalue,maxvalue,disc) values(AES_ENCRYPT(?, 'key'),AES_ENCRYPT(?, 'key'),AES_ENCRYPT(?, 'key'),AES_ENCRYPT(?, 'key'),AES_ENCRYPT(?, 'key'))");
psmt1.setString(1,title[0]);
psmt1.setString(2,title[1]);
psmt1.setString(3,min);
psmt1.setString(4,max);
psmt1.setString(5,disc);
psmt1.executeUpdate();
}
catch(Exception ex)
{
out.println("Error in connection : "+ex);
}
Below is my connection class
package databaseconnection;
import java.sql.*;
public class databasecon
{
static Connection con;
public static Connection getconnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cam","root","root");
}
catch(Exception e)
{
System.out.println("class error");
}
return con;
}
}
And finally error is
Error in connection : java.sql.SQLException: 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 'maxvalue,disc) values(AES_ENCRYPT('6', 'key'),AES_ENCRYPT('systolic bp', 'key'),' at line 1
As requested by my fellow developer i am posting my table sturuture
I don't know why this is the case, but you need to pass in a byte array as the second parameter to MySQL's AES_ENCRYPT :
psmt1 = con.prepareStatement("insert into medication(tid,titname,minvalue,maxvalue,disc) values(AES_ENCRYPT(?, 'key'),AES_ENCRYPT(?, 'key'),AES_ENCRYPT(?, 'key'),AES_ENCRYPT(?, 'key'),AES_ENCRYPT(?, 'key'))");
byte[] keyBytes = "key".getBytes();
psmt1.setString(1, title[0]);
psmt1.setBytes(2, keyBytes);
psmt1.setString(3, title[1]);
psmt1.setBytes(4, keyBytes);
psmt1.setString(5, min);
psmt1.setBytes(6, keyBytes);
psmt1.setString(7, max);
psmt1.setBytes(8, keyBytes);
psmt1.setString(9, disc);
psmt1.setBytes(10, keyBytes);
psmt1.executeUpdate();
I say that I don't have an explanation because the MySQL documentation implies that both parameters to AES_ENCRYPT
are strings. I would have made this mistake myself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.