繁体   English   中英

如何使用SQL在数据库中插入当前日期和时间?

[英]How to insert current date and time in a database using SQL?

我使用了以下代码,但SQL中的DateTime字段表示为:

2005-04-08 00:00:00

我也想要时间。 我应该改变什么?

这是我的代码如下:

// Get the system date and time.
java.util.Date utilDate = new Date();
// Convert it to java.sql.Date
java.sql.Date date = new java.sql.Date(utilDate.getTime());
...
...
...
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setDate(1, date);

尝试使用setTimestamp而不是setDate ,因为时间戳是数据时间的首选格式。

你可以设置Timestamp import java.sql.Timestamp;

stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));

代替

stmt.setDate(1, date);

o / p将是:2014-05-16 08:34:52.977

将您的DB --column设置为Timestamp。

尝试这个:

Connection con;
Statement stmt;
con = DriverManager.getConnection(url, username, password);
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO MYTABLE(time) " +
"VALUES ('" + new java.sql.Date(System.CurrentTimeMillis())"');");

现在使用sql函数()。

INSERT INTO table date_field VALUES(NOW());

我不打算在Java中检索当前时间,只需让数据库完成工作:

String sql = "insert into some_table (some_column, timestamp_column) values (?, current_timestamp)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setInt(1, 42);
stmt.executeUpdate();

尝试使用setDate(utilDate)而不是尝试设置SQL日期。 在SQL中,日期和时间是不同的数据类型。

我做了如下:

con = new BDConesion(); //Conexion with de DB
Connection cn = con.conexion()
PreparedStatement st = null;
st = cn.prepareStatement("INSERT INTO TABLE (Id,Fecha,contendido) VALUES(?,?,?)");
st.setString(1,String.valueOf(key)); //convert the int to string
st.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
st.setString(3,Cont);//Cont it is a varible string
st.executeUpdate();

我希望你服务

实际上,数据库中的日期是一个像“yyyy-mm-dd”这样的字符串。

为什么不尝试:

String date = "2010-07-28";

stmt.executeUpdate("INSERT INTO MYTABLE(time) " + s);

这只是你想要的日期。

如果您想立即插入,请使用如下命令:

INSERT INTO mytable(now());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM