package Blob;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//Blob主要用于处理大二进制文件,最大4G
//使用Blob类可以简化写出操作
public class BlobDemo01 {
//定义mysql的数据库加载驱动
public static final String dbDriver="org.gjt.mm.mysql.Driver";
//定义mysql数据库的连接地址
public static final String dbUrl="jdbc:mysql://localhost:3306/mydb"; //连接到指定数据库
//定义连接数据库的用户名
public static final String dbUser="root"; //连接到指定数据库
//定义连接数据库的密码
public static final String dbPass="admin"; //连接到指定数据库
public static void main(String[] args) throws Exception{
Class.forName(dbDriver); //加载驱动程序
Connection conn=null;
conn=DriverManager.getConnection(dbUrl, dbUser, dbPass); //获得连接
String name="myPhoto";
PreparedStatement pstat=null;
String sql="Insert into userblob (name,photo) values(?,?)";
pstat=conn.prepareStatement(sql);// 实例化PreapredStatement对象
pstat.setString(1, name);
/*FileInputStream fis=new FileInputStream("E:/eclipse/javawork/JDBC_lixinghua/src/Blob/12.jpg");
pstat.setAsciiStream(2, fis);*/
InputStream is=null;
File f=new File("E:/eclipse/javawork/JDBC_lixinghua/src/Blob/12.jpg");
is=new FileInputStream(f);
pstat.setBinaryStream(2,is, (int)(f.length())); //File类有获取字节长度方法
pstat.executeUpdate();
pstat.close();
conn.close();
}
}
mysql中创建表的语句:create table userBlob(
id int auto_increment primary key,
name varchar(30) not null,
photo longBlob
);
运行后提示:
Exception in thread "main" 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 '?\\??A¤^i????[?M\'y?.8.à=T?\0<Y?_????u????F??i,??yq?d9ùQy??\0?ZN
ù}<K?' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)