发表于: 2018-03-11 16:26:36
1 638
今日完成
1,回复师兄的提问:想想如何通过sql语句来插入时间戳,而不需要经过程序判断。
MySQL 获得当前时间戳函数:current_timestamp, current_timestamp()
insert into user_info values(null,'张三',21,current_timestamp());
这里create_at为varchar和timestamp类型都可以插入时间戳的。
方式二:通过在建表时指定默认值的方式添加时间戳,只能将其类型设为timestamp(时间戳),并且有timestamp这个选项的只能有一个。
create table user_time
(id int not null auto_increment primary key,
name varchar(50) not null,
create_at timestamp not null default CURRENT_TIMESTAMP on update current_timestamp);
然后我试过了加不加on update current_timestamp效果好像没什么差别。
Java中插入时间:Java中System.currentTimeMillis()产生一个当前的毫秒数,这个毫秒其实就是自1970年1月1日0时起的毫秒数。
1、MySQL中datetime类型转换为bigint类型
2、bigint类型转换为datetime类型
然后今天,将JDBC中statement语句换为preparedStatement语句。
Class.forName(driver);//加载驱动
conn= DriverManager.getConnection(url,username,password);//创建数据库连接
ps=conn.prepareStatement("insert into user_final values(?,?,?,?)");//向数据库发送要执行的SQL语句。Statement对象,用于执行不带参数的简单SQL语句
ps.setInt(1,2);
ps.setString(2,"张三");
ps.setLong(3,System.currentTimeMillis());
ps.setLong(4,System.currentTimeMillis());
int row1=ps.executeUpdate();//执行sql语句,返回整数,受影响的行数
if (row1!=-1){
ResultSet rs=ps.executeQuery("select * from user_final");
while (rs.next()){
int id=rs.getInt("id");
String name=rs.getString("name");
Long create_at=rs.getLong("create_at");
Long update_at=rs.getLong("update_at");
System.out.println("ID:"+id+",Name:"+name+",create_at:"+create_at+",update_at:"+update_at);
}
遇到的问题
1,将statement语句改为prepared Statement后,出现异常
异常错误:Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
解决:现在按照最新官方提示支持将com.mysql.jdbc.Driver 改为 com.mysql.cj.jdbc.Driver,驱动改为6.0.6。
2,异常错误:java.sql.SQLException: The server time zone value ' й ʱ ' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
解决:看网上是需要匹配时区?
之前的url:
String url="jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF8";
改为
Stringurl="jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8";
运行通过
明日计划
接着步骤17
收获
学会了如何使用MySQL本身来插入时间戳和用Java插入bigint类型的时间。
学习了preparedstatement语句的用法
评论