在我们写代码的时候,避免不了和数据库打交道,那么就经常会遇到JAVA类型和数据库类型的映射关系。
映射表如下:
下面就举个例子来讲(JAVA插入MySql的datetime类型的简单的例子):
看了映射表可知:我们可以以Timestamp类型的值插入到数据库中
数据库中表的设计为这样(有两个字段,id为整型是主键,create_on为datatime类型):
public static void main(String[] args) {
String username = "root";
String password = "root";
Connection conn;
PreparedStatement pStmt=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url ="jdbc:mysql://localhost:3306/rh?useUnicode=true&characterEncoding=UTF-8";
conn= DriverManager.getConnection(url,username,password);
System.out.println("connect to database successfully!");
String sql = "insert into rh_entity(id,create_on) values(?,?)";
pStmt = conn.prepareStatement(sql);
conn.setAutoCommit(false);
pStmt.setInt(1, 1);
Timestamp timestamp = new Timestamp(new Date().getTime());
pStmt.setTimestamp(2, timestamp);
pStmt.executeUpdate();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pStmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
运行结果:
这样就插入进去了,格式是年月日时分秒