各位大侠,我写了个程序,其中有部分涉及到了把系统当前时间录入到数据库中,我使用了PreparedStatement对象的setTimestamp(int Index, Timestamp ts, Calendar c)方法,但是执行了sql语句后发现时间没录进去值显示为null,下面是我写的这部分的代码,跪求高手指点下
PreparedStatement pstmt = DB.prepareStmt(conn, "insert into manager values (null, ?, ?, ?, ?, ?)");
try {
pstmt.setString(1, name);
pstmt.setString(2, gender);
pstmt.setString(3, item);
pstmt.setInt(4, money);
Calendar c = Calendar.getInstance();
Timestamp ts = null;
pstmt.setTimestamp(5, ts, c);
pstmt.executeUpdate();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ta.setText("数据记录成功");
DB.close(pstmt, conn);
------解决思路----------------------
Calendar是用来指定时区的
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class TestSql {
public static void main(String[] args) {
try {
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://192.168.233.11:5432/test","test","test");
PreparedStatement pstmt = conn.prepareStatement("insert into test.table_a(name, time_str) values(?,?)");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateTime = sdf.parse("2012-10-29 11:00:00");
Timestamp ts = new Timestamp(dateTime.getTime());
// Test1
pstmt.setString(1, "test1");
pstmt.setTimestamp(2, ts);
pstmt.executeUpdate();
// Test2 wich Calendar
TimeZone tz = TimeZone.getTimeZone("gmt");
Calendar calendar = Calendar.getInstance(tz);
pstmt.setString(1, "test2");
pstmt.setTimestamp(2, ts, calendar);
pstmt.executeUpdate();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
数据库结果如下:
name
------解决思路----------------------
time_str
-------+--------------------------------------
test1
------解决思路----------------------
2012-10-29 11:00:00.000000 +08:00:00
test2
------解决思路----------------------
2012-10-29 03:00:00.000000 +00:00:00