1、时间类型
数据库类型与java中类型的对应关系:
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
领域对象(domain)中的所有属性不能出现java.sql包下的东西!即不能使用java.sql.Date;
ResultSet#getDate()返回的是java.sql.Date()
PreparedStatement#setDate(int, Date),其中第二个参数也是java.sql.Date
时间类型的转换:
java.util.Date java.sql.Date、Time、Timestamp
把util的Date转换成毫秒值
使用毫秒值创建sql的Date、Time、Timestamp
java.sql.Date、Time、Timestamp java.util.Date
这一步不需要处理了:因为java.sql.Date是java.util.Date;
java.util.Date date = new java.util.Date();
long l = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(l);
2、mysql存储大数据:
mysql默认存储大小为4M 需要重新设置最大值:
在my.ini中添加如下配置!
max_allowed_packet=10485760 (10M)
public class Demo4 {
@Test
public void fun1 () throws Exception{
Connection con = JdbcUtils.getConnection();
String sql = "INSERT INTO tab_bin VALUE(?,?,?)" ;
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1 , 1 );
pstmt.setString(2 , "思疆调.mp3" );
byte [] bytes = IOUtils.toByteArray(new FileInputStream("C:/Users/11316/Music/思疆调.mp3" ));
Blob blob = new SerialBlob(bytes);
pstmt.setBlob(3 , blob);
pstmt.executeUpdate();
}
@Test
public void fun2 () throws Exception{
Connection con = JdbcUtils.getConnection();
String sql = "select * from tab_bin" ;
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
Blob blob = rs.getBlob("data" );
InputStream ips= blob.getBinaryStream();
OutputStream ops = new FileOutputStream("E:/sjd.mp3" );
IOUtils.copy(ips, ops);
}
}
}
3、批处理
mysql默认批处理关闭,需要在连接时设置url参数
打开批处理:
jdbc: mysql: //localhost:3306/mydb 1?rewriteBatchedStatements=true
public class Demo5 {
@Test
public void fun5 () throws Exception{
Connection con = JdbcUtils.getConnection();
String sql = "INSERT INTO stu VALUES(?,?,?,?)" ;
PreparedStatement pstmt = con.prepareStatement(sql);
for (int i = 0 ; i < 10000 ; i++){
pstmt.setInt(1 ,i+1 );
pstmt.setString(2 ,"stu_" +i);
pstmt.setInt(3 ,i);
pstmt.setString(4 ,i%2 ==0 ?"男" :"女" );
pstmt.addBatch();
}
long start = System.currentTimeMillis();
pstmt.executeBatch();
long end = System.currentTimeMillis();
System.out .println(end-start);
}
}
4、JdbcUtils 简化得到连接
public class JdbcUtils {
private static Properties props = null ;
static {
try {
InputStream in = JdbcUtils.class.getClassLoader()
.getResourceAsStream("dbconfig.properties" );
props = new Properties();
props.load(in );
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
Class.forName(props.getProperty("driverClassName" ));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection () throws SQLException {
return DriverManager.getConnection(props.getProperty("url" ),
props.getProperty("username" ),
props.getProperty("password" ));
}
}