如何使用 Java 将 DATE 插入 MySQL 列值?
为此,你可以使用 Java 的 PreparedStatement。让我们先创建一个表,其中一列为 ArrivalDate,类型为 DATE -
mysql> create table DemoTable( PassengerId int, PassengerName varchar(40), ArrivalDate date ); Query OK, 0 rows affected (0.82 sec)
插入日期的 JAVA 代码如下 -
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class InsertDateFromJava { public static void main(String[] args) { Connection con = null; PreparedStatement ps = null; try { java.util.Date javaDate = new java.util.Date(); java.sql.Date mySQLDate = new java.sql.Date(javaDate.getTime()); con = DriverManager.getConnection("jdbc :mysql ://127.0.0.1 :3306/web?useSSL=false", "root","123456"); String query = "insert into DemoTable(PassengerId,PassengerName,ArrivalDate) values(?,?,?) "; ps = con.prepareStatement(query); ps.setInt(1, 101); ps.setString(2, "Adam"); ps.setDate(3, mySQLDate); ps.executeUpdate(); System.out.println("Record is inserted with current Date......"); } catch (Exception e) { e.printStackTrace(); } } }
这将生成以下 Java 输出 -
Record is inserted with current Date......
以下是输出的截图 -
让我们再次检查表的记录 -
mysql> select * from DemoTable;
这将生成以下输出 -
+-------------+---------------+-------------+ | PassengerId | PassengerName | ArrivalDate | +-------------+---------------+-------------+ | 101 | Adam | 2019-09-07 | +-------------+---------------+-------------+ 1 row in set (0.00 sec)
截图如下 -
广告