时间:2021-07-01 10:21:17 帮助过:23人阅读
四种不同大小的二进制类型,单位为字节
TinyBlob 255B
Blob 65k
MediumBlob 16M
LongBlob 4G
package jdbc_preparement; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class text_preparestartment { public static void main(String[] args) { // TODO Auto-generated method stub Connection con=simplecon.getConnection(); String sql="insert into t_user values(null,?,?,null);"; String sql1="insert into t_hobby values(?,?)"; try { PreparedStatement ps=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); ps.setString(1, "mike"); //插入一组数据 ps.setString(2, "4399"); ps.execute(); ResultSet re=ps.getGeneratedKeys(); //获得主键 re.next(); int n=re.getInt(1); System.out.println("自然增长的序号为"+n); simplecon.close(re); simplecon.close(ps); PreparedStatement ps1=con.prepareStatement(sql1); ps1.setInt(1, n); Blob pic=con.createBlob(); //创建一个二进制类型 OutputStream out=pic.setBinaryStream(1); //返回一个流,流向这个二进制存放处,并设置位置为初始位置1 //读入一个二进制文件 byte[] b; String picname="d:/tupian.jpg"; b=simple_read.readpic(picname); //自定义的读入图片的类 out.write(b);//将图片的二进制写到Blob中 out.flush(); out.close(); ps1.setBlob(2,pic);//将blob写到数据库中 ps1.execute(); simplecon.close(ps1); simplecon.close(con); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
//连接数据库 class simplecon { static Connection con; static Connection getConnection() { try{ con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","数据库名","数据库密码"); }catch(SQLException e){ e.printStackTrace(); } return con; } static void close(AutoCloseable a) { try { a.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
//从文件中读取图片 class simple_read { static byte[] readpic(String a) { byte[] b=null; try { FileInputStream in=new FileInputStream(a); b=new byte[in.available()]; in.read(b); in.close(); System.out.println("ok!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return b; } }
用JDBC处理二进制类文件
标签:oca return [] next insert ps1 create nbsp bsp