import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
public class HelloWorld {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello world!");
// 1. 注册驱动
try {
// Register MySQL driver
Class.forName("com.mysql.jdbc.Driver");
Connection MySQLconn = null;
PreparedStatement MySQLpstmt = null;
PreparedStatement MySQLquery = null;
ResultSet MySQLrs = null;
try {
MySQLconn = java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost:3309/test", "root", "mysql");
// 插入DATETIME类型数据
MySQLpstmt = MySQLconn
.prepareStatement("insert into t_test(created_date) values(?)");
java.sql.Timestamp vTimestamp = new java.sql.Timestamp(
new java.util.Date().getTime());
MySQLpstmt.setTimestamp(1, vTimestamp);
MySQLpstmt.execute();
// 查询DATETIME类型数据
MySQLquery = MySQLconn.prepareStatement("select created_date from t_test order by created_date desc");
MySQLrs = MySQLquery.executeQuery();
while (MySQLrs.next())
{
System.out.println(MySQLrs.getTimestamp(1));
}
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
// Close result set
if (MySQLrs != null) {
try {
MySQLrs.close();
} catch (SQLException sqlEx) {
} // ignore
MySQLrs = null;
}
// Close statement
if (MySQLpstmt != null) {
try {
MySQLpstmt.close();
} catch (SQLException sqlEx) {
} // ignore
MySQLpstmt = null;
}
// Close connection
if (MySQLconn != null) {
try {
MySQLconn.close();
} catch (SQLException sqlEx) {
} // ignore
MySQLconn = null;
}
}
} catch (ClassNotFoundException e) { // TODO Auto-generated catch block
e.printStackTrace();
}// Mysql 的驱动
}
}
|