package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Random;
public class Demo_main {
public static void main(String[] args){
PreparedStatement ps = null;
Connection c = null;
try {
//加载驱动类
Class.forName("com.mysql.jdbc.Driver");
//建立连接
c = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc的使用","root","root");
//关闭自动提交
c.setAutoCommit(false);//JDBC默认自动提交
//执行SQL语句
//随机插入时间为:当前时间-一个是随机数,如果想要给定范围内时间,则只需在随机数上做一些算法约束即可比如说1天的秒为24*60*60
//随机插入100个时间
int t;
for(int i = 0 ;i < 100;i++) {
t = new Random().nextInt(1000000000)+1000000000;//单位毫秒
ps = c.prepareStatement("insert into study(date,timestamp) values(?,?)");
//插入当前时间
//date
java.sql.Date d = new java.sql.Date(System.currentTimeMillis()-t);
//timestamp
Timestamp ts = new Timestamp(System.currentTimeMillis()-t);
ps.setObject(1, d);
ps.setTimestamp(2, ts);
ps.execute();
//手动提交
c.commit();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
try {
c.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}//回滚,回滚到该语句未执行前
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭
try {
if(ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(c != null) {
c.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
7.随机插入时间
最新推荐文章于 2024-08-28 08:52:25 发布