CREATE TABLE userblob
(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
photo LONGBLOB
);
Java程序代码如下:
import java.sql.Connection ;
import java.sql.DriverManager ;
import java.sql.SQLException ;
import java.sql.PreparedStatement ;
import java.io.File ;
import java.io.FileInputStream ;
import java.io.InputStream ;
public class BlobDemo01{
// 定义MySQL的数据库驱动程序
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
// 定义MySQL数据库的连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/testDatabase" ;
// MySQL数据库的连接用户名
public static final String DBUSER = "root" ;
// MySQL数据库的连接密码
public static final String DBPASS = "mysqladmin" ;
public static void main(String args[]) throws Exception{ // 所有异常抛出
Connection conn = null ; // 数据库连接
PreparedStatement pstmt = null ;
String name = "Sheldon" ;
String sql = "INSERT INTO userblob(name,photo) VALUES (?,?) " ;
Class.forName(DBDRIVER) ; // 加载驱动程序
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
pstmt = conn.prepareStatement(sql) ;
File f = new File("d:" + File.separator + "Sheldon.gif") ; // 图片文件
InputStream input = null ;
input = new FileInputStream(f) ;
pstmt.setString(1,name) ; // 设置第一个“?”的内容
pstmt.setBinaryStream(2,input,(int)f.length()) ; // 设置输入流
pstmt.executeUpdate() ; // 更新数据库
pstmt.close() ;
conn.close() ; // 数据库关闭
}
};
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an er
ror in your SQL syntax; check the manual that corresponds to your MySQL server version for the right
syntax to use near '\0\0\0\0?€?0\0?€?0\0\0\0\00221?\0\0\0\0\0\0è?‘\0\0\0\0\0\0é??\0\0\
' 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:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2427)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2345)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2330)
at BlobDemo01.main(BlobDemo01.java:30)