简体   繁体   English

JDBC中SQL查询中的InputStream错误

[英]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: 我尝试将InputStream存储在photo列中,如下所示:

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. 但是在我的数据库中插入了null值。 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. 即根据Jens的评论,使用PreparedStatement What is this buying you: 这是什么给你买的:

  1. You actually can set a BLOB type column 您实际上可以设置BLOB类型列
  2. You are safe from SQL injection (your first code with string concatenation is the cracker's paradise for taking over your application) 您可以安全地进行SQL注入(您的第一个带有字符串连接的代码是接管您应用程序的骗子的天堂)
  3. Potential performance improvements (not guaranteed - depends on how the driver handles your queries) 潜在的性能改进(不保证-取决于驱动程序如何处理查询)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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