对Blob数据类型的操作
public class BlobTest1 {
@Test
public void test1() throws Exception {
Connection conn = JDBCUtils.getConnection();
String sql = "insert into customers(`name`,email,birth,photo)values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1,"王杰");
ps.setObject(2,"wangjie@gmail.com");
ps.setObject(3,"1980-01-01");
FileInputStream is = new FileInputStream(new File("王杰.jpg"));
ps.setBlob(4,is);
ps.execute();
is.close();
JDBCUtils.closeResource(conn,ps);
}
@Test
public void test2() throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
InputStream is = null;
FileOutputStream fos = null;
try {
conn = JDBCUtils.getConnection();
String sql = "select id,`name`,email,birth,photo from customers where id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1,19);
rs = ps.executeQuery();
if(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
Date birth = rs.getDate("birth");
Customer cust = new Customer(id,name,email,birth);
System.out.println(cust);
Blob photo = rs.getBlob("photo");
is = photo.getBinaryStream();
fos = new FileOutputStream("王杰2.jpg");
byte[] byteBuffer = new byte[1024];
int len;
while ((len = is.read(byteBuffer)) != -1){
fos.write(byteBuffer,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
fos.close();
JDBCUtils.closeResource(conn,ps,rs);
}
}
}
大批量插入数据
public class InsertTest {
@Test
public void test() throws Exception {
long start = System.currentTimeMillis();
Connection conn = JDBCUtils.getConnection();
String sql = "insert into goods (name) values (?)";
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0; i < 20000; i++) {
ps.setObject(1,"naem_" + i);
ps.execute();
}
JDBCUtils.closeResource(conn,ps);
long end = System.currentTimeMillis();
System.out.println(end - start);
}
@Test
public void test2() throws Exception {
long start = System.currentTimeMillis();
Connection conn = JDBCUtils.getConnection();
String sql = "insert into goods (name) values (?)";
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0; i < 200000; i++) {
ps.setObject(1,"naem_" + i);
ps.addBatch();
if(i % 1000 == 0){
ps.executeBatch();
ps.clearBatch();
}
}
JDBCUtils.closeResource(conn,ps);
long end = System.currentTimeMillis();
System.out.println(end - start);
}
@Test
public void test3() throws Exception {
long start = System.currentTimeMillis();
Connection conn = JDBCUtils.getConnection();
conn.setAutoCommit(false);
String sql = "insert into goods (name) values (?)";
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0; i < 200000; i++) {
ps.setObject(1,"naem_" + i);
ps.addBatch();
if(i % 1000 == 0){
ps.executeBatch();
ps.clearBatch();
}
}
conn.commit();
JDBCUtils.closeResource(conn,ps);
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}