sqlserver中的image类型是以二进制形式存储的,之前在网上找了很多方法试着存入,都以失败告终,在解决这个问题后,将方法分享,记录下来
try { Connection conn = DriverManager.getConnection("数据库连接字符串","用户名","用户密码"); //jdbctemplate获取连接方法 //Connection conn = jdbcTemplate.getDataSource().getConnection(); String sql = "insert into [table](id,name,img) values(0,?,?)"; PreparedStatement ps = conn.prepareStatement("sql语句"); File file = new File("文件地址");//将要存入数据库的文件 InputStream is = new FileInputStream(file); ps.setString(1,file.getName()); ps.setBinaryStream(2,is,file.length());//替换sql中的"?",第一个参数代表要替换SQL中第几个参数 ps.execute();//执行SQL is.close(); conn.close();//关闭连接 } catch (Exception throwables) { throwables.printStackTrace(); }
数据库连接一定要关闭,不然重复调用接口时会出现连接超时的异常