AKbiubiu 2011-08-08
一、插入图片
importjava.io.FileInputStream;
importjava.io.InputStream;
importjava.sql.Connection;
importjava.sql.PreparedStatement;
importjava.sql.SQLException;
publicclassTestAdd{
/**
*
*测试向mysql添加大字段
*/
publicvoidtestAdd(){
//1.createsql;
Stringsql="insertintouserinfo(username,password,image)values(?,?,?)";
//2.getconnection
Connectionconn=null;
PreparedStatementpsmt=null;
InputStreamis=null;
try{
conn=JdbcHelper.getConnection();
//3.preparesql
psmt=conn.prepareStatement(sql);
//4.setparams
psmt.setString(1,"javaee");
psmt.setString(2,"123456");
//(1)getthestream
is=newFileInputStream("F:/androidgo/院内信息资源整合系统建立.bmp");
psmt.setBinaryStream(3,is,is.available());
//5.updatedb
psmt.executeUpdate();
System.out.println("ok!");
}catch(Exceptione){
e.printStackTrace();
}finally{
//6.closedb
try{
if(psmt!=null)
psmt.close();
if(conn!=null)
conn.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
publicstaticvoidmain(String[]args){
TestAddtest=newTestAdd();
test.testAdd();
}
}二、获取图片importjava.io.FileInputStream;
importjava.io.InputStream;
importjava.sql.Connection;
importjava.sql.PreparedStatement;
importjava.sql.SQLException;
publicclassTestAdd{
/**
*
*测试向mysql添加大字段
*/
publicvoidtestAdd(){
//1.createsql;
Stringsql="insertintouserinfo(username,password,image)values(?,?,?)";
//2.getconnection
Connectionconn=null;
PreparedStatementpsmt=null;
InputStreamis=null;
try{
conn=JdbcHelper.getConnection();
//3.preparesql
psmt=conn.prepareStatement(sql);
//4.setparams
psmt.setString(1,"javaee");
psmt.setString(2,"123456");
//(1)getthestream
is=newFileInputStream("F:/androidgo/院内信息资源整合系统建立.bmp");
psmt.setBinaryStream(3,is,is.available());
//5.updatedb
psmt.executeUpdate();
System.out.println("ok!");
}catch(Exceptione){
e.printStackTrace();
}finally{
//6.closedb
try{
if(psmt!=null)
psmt.close();
if(conn!=null)
conn.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
publicstaticvoidmain(String[]args){
TestAddtest=newTestAdd();
test.testAdd();
}
}
三、助手类
importjava.sql.Connection;
importjava.sql.DriverManager;
/**
*
*@authorAdministrator
*=====================返回数据库的连接信息==========================
*/
publicclassJdbcHelper{
privatestaticConnectionconn;
privateJdbcHelper(){
}
//gettheconnectiontodb
publicstaticsynchronizedConnectiongetConnection()throwsException{
if(conn==null)
initConnection();
elseif(conn.isClosed())
initConnection();
returnconn;
}
//
privatestaticvoidinitConnection()throwsException{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://192.168.1.101:3306/android",
"root","123456");
}
}
四、数据库文件CREATETABLE`userinfo`(`id`int(10)unsignedNOTNULLauto_increment,`username`varchar(45)defaultNULL,`password`varchar(45)defaultNULL,`image`longblob,PRIMARYKEY(`id`))ENGINE=InnoDBDEFAULTCHARSET=utf8;
本篇文章来自Java中文网:http://www.javaweb.cc/topics/jdbc/181603.shtml