一、BLOB類型介紹
在MySQL中,BLOB是一個二進制的大型對象,可以存儲大量數據的容器,它能容納不同大小的數據。
在MySQL中有四種BLOB類型。
實際使用中根據需要存入的數據大小定義不同的BLOB類型。需要注意的是,如果存儲的文件過大,數據庫的性能會下降。
二、Java數據類型與MySQL類型對照表
對於blob,一般用於對圖片的數據庫存儲,原理是把圖片打成二進制,然后進行的一種存儲方式,在java中對應byte[]數組。
對於boolen類型,在mysql數據庫中,個人認為用int類型代替較好,對bit操作不是很方便,尤其是在具有web頁面開發的項目中,表示0/1,對應java類型的Integer較好。
三、添加Blob到數據庫
Person.java
public class Person{ private int id; private String name; private String city; private int age; private float salary; private byte[] head; public Person(){ super(); } public Person(int id,String name,String city,int age,float salary,byte[] head){ super(); this.id = id; this.name = name; this.city = city; this.age = age; this.salary = salary; this.head = head; } //...get、set方法 }
@Test public void testAddPerson() throws Exception{ FileInputStream fis = new FileInputStream("1.jpg"); byte[] bs = inputStream2Byte(fis); addPerson(new Person(0,"HeHe2","BJ",23,1300,bs)); } /* * 插入數據 */ public static void addPerson(Person p) throws Exception{ String sql = "insert into person(id,name,city,age,salary,head) values(?,?,?,?,?,?)"; JdbcTools.update(sql,p.getId(),p.getName(),p.getCity(),p.getAge(),p.getSalary(),p.getHead()); } /* * 輸入流轉換為字節數組 * @param inStream * @return * @throws Exception */ public static byte[] inputStream2Byte(InputStream inStream) throws Exception{ ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while((len = inStream.read(buffer)) != -1){ outSteam.write(buffer,0,len); } outSteam.close(); inStream.close(); return outSteam.toByteArray(); }
JdbcTools.update()方法
/* * 通用的增刪改方法 * 執行SQL語句,使用PreparedStatemnt * @param sql 帶占位符的sql語句 * @param args 填寫SQL占位符的可變參數 */ public static void update(String sql,Object...args){ Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try{ con = JdbcTools.getConnection(); ps = con.prepareStatement(sql); for(int i = 0;i < args.length;i++){ ps.setObject(i + 1,args[i]); } ps.execute(); }catch (Exception e) { e.printStackTrace(); } finally{ JdbcTools.releaseResource(con,ps,rs); } }
結果:
在最后BLOb中右鍵另存為圖片即可看到。