简体   繁体   中英

InputStream in SQL query error in JDBC

I've the below table:

CREATE TABLE `contact` (
  `idcontact` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(245) NOT NULL,
  `last_name` varchar(245) NOT NULL,
  `photo` mediumblob NOT NULL,
  PRIMARY KEY (`idcontact`),
  UNIQUE KEY `idcontact_UNIQUE` (`idcontact`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

I tried storing an InputStream in photo column as below:

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "root", "root");
Statement st = con.createStatement();
String sql = "insert into contact(first_name,last_name,photo) values('"+firstName+"','"+lastName+"','"+inputStream+"')";
if(st.executeUpdate(sql) !=0){
    System.out.println("Success");
} else {
    System.out.println("Fail");
}

But null value inserted in my database. How is this caused and how can I solve it?

Replace this part of the code:

        Statement st = con.createStatement();
        String sql = "insert into contact(first_name,last_name,photo) values('"+firstName+"','"+lastName+"','"+inputStream+"')";
        if(st.executeUpdate(sql) !=0){

with:

        PreparedStatement st = con.prepareStatement("insert into contact(first_name,last_name,photo) values(?, ?, ?)");
        st.setString(1, firstName);
        st.setString(2, lastName);
        st.setBlob(3, inputStream);
        if( st.executeUpdate() != 0 ) {

Ie using PreparedStatement , as per the comment from Jens. What is this buying you:

  1. You actually can set a BLOB type column
  2. You are safe from SQL injection (your first code with string concatenation is the cracker's paradise for taking over your application)
  3. Potential performance improvements (not guaranteed - depends on how the driver handles your queries)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM