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;
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语句
ps = c.prepareStatement("insert into study(date,timestamp) values(?,?)");
//插入当前时间
//date
java.sql.Date d = new java.sql.Date(System.currentTimeMillis());
//timestamp
Timestamp ts = new Timestamp(System.currentTimeMillis());//时间可以用另一种自己设定,不过不常用
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();
}
}
}
}