今天在实验室整了半天,看Mysql的文档,写了一个测试代码,但是好像插不进去数据啊,不知道问题出在什么地方!很是郁闷!
数据库Mysql5.0
CREATE TABLE `test` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(64) NOT NULL,
`img` blob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
测试代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ImgTest {
private Connection conn = null;
private Statement stat = null;
public ImgTest() throws Exception {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
}
public void connect(String url, String username, String password) {
String connect= url + "?" + "user=" + username +
"&" + "password=" + password;
try{
conn= DriverManager.getConnection(connect);
stat = conn.createStatement();
}catch(SQLException e){
System.err.println(e.getLocalizedMessage());
}
}
public void disconnect(){
try{
stat.close();
conn.close();
}catch(SQLException e){
System.err.println(e.getLocalizedMessage());
}
}
public void insert(String name) throws Exception {
PreparedStatement pstmt = conn.prepareStatement(
"insert into test values ( ? , ?, ?)" );
FileInputStream in = new FileInputStream(name);
try{
//System.out.println("0");
pstmt.setObject(1, null);
//System.out.println("1");
pstmt.setObject(2, name);
//System.out.println("2");
pstmt.setBinaryStream(3,in,in.available());
System.out.println("3");
int re = pstmt.executeUpdate();
System.out.println(re);
System.out.println("Successful!");
}catch(SQLException e){
}
}
public ResultSet query() throws Exception {
return stat.executeQuery("select * from test");
}
public static void main(String args[]) throws Exception {
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "441300";
ImgTest test = null;
try{
test = new ImgTest();
}catch(Exception e){
}
test.connect(url,username,password);
test.insert("Sunset.jpg");
ResultSet result = test.query();
/*
InputStream in = null;
FileOutputStream out =null;
String name;
byte[] b;
int id;
try {
while(result.next()) {
id = result.getInt("id");
name = result.getString("name").replace("." , "1.");
in = result.getBinaryStream("img");
b = new byte[in.available()];
in.read( b );
out = new FileOutputStream(new File(name));
out.write( b );
String row = id + " " + name;
System.out.println(row);
}
in.close();
out.close();
result.close();
test.disconnect();
} catch(SQLException e) {}
*/
}
}
后面的代码有注释,可以在测试的时候去掉!