JDBC环境下
如果使用的是PreparedStatement接口:
String sql = "insert into 表名(date类型的列) values(?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setDate(1, date对象);
stmt.executeUpdate();
如果使用的是Statement接口:
java.text.SimpleDateFormat fmt1 = new java.text.SimpleDateFormat("yyyy-MM-dd"); // mssql、mysql格式
java.text.SimpleDateFormat fmt2 = new java.text.SimpleDateFormat("dd-MM月-yyyy"); // oracle格式
String sql = String.format("insert into 表名(date类型的列) values('%s')", fmt1.format(date对象));
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
mysql的数据读到java:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDate {
public static void main(String args[]){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=123");
Statement stmt = conn.createStatement();//jdbc:mysql://localhost/graduatestudent?user=root&password=123
ResultSet rs = stmt.executeQuery("select pdate from date");
while(rs.next()){
Date d = rs.getDate("pdate");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年mm月dd日");
System.out.println(sdf.format(d));
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}