Look at the definition of the database table first
The Date field is the Sql.date type. I want to insert the specified date and the current date into it.
First, insert the current date
Idea: First get the current system, the time to convert the current system time to a SQL type, and then insert the database. The code is as follows
Public Static voidInsert_now ()throwsclassnotfoundexception, sqlexception{java.util.Date utildate=NewDate ();//gets the Java.util.Date object---that is, the current timeJava.sql.Date sqldate =NewJava.sql.Date (Utildate.gettime ());//convert java.util.Date type to java.sal.Date typeConnection conn = Jdbcutils.getconn ();//Get database connectionString sql = "INSERT into TestDate (?)"; PreparedStatement PS=conn.preparestatement (SQL); Ps.setdate (1, sqldate);//SQL type data into the databaseps.executeupdate (); Conn.close ();}
After the database refreshes, the following:
Second, insert data for the specified date
Insert the string "2012-12-21" into the database. Idea: Use the java.sql.Date.valueOf (String str) method to convert a string to a Date of type SQL and insert it into the database
Public Static voidString_insert_sql ()throwsclassnotfoundexception, sqlexception{String str= "2012-12-21"; Java.sql.Date sqldate= Java.sql.Date.valueOf (str);//converts a string into SQL. Date TypeConnection conn = Jdbcutils.getconn ();//connecting to a databaseString sql = "INSERT into TestDate (?)"; PreparedStatement PS=conn.preparestatement (SQL); Ps.setdate (1, sqldate);//SQL type of amount data inserted into the databaseps.executeupdate (); Conn.close ();}
After the database refreshes, the following:
Iii. reading date-type data from the database
Public Static voidSql_to_string ()throwsclassnotfoundexception, sqlexception{date Date=NULL; Connection Conn= Jdbcutils.getconn ();//Get database connectionString sql = "SELECT * from testdate WHERE id = 4"; PreparedStatement PS=conn.preparestatement (SQL); ResultSet RS=Ps.executequery (); if(Rs.next ()) {Date= Rs.getdate (2); } conn.close (); SYSTEM.OUT.PRINTLN (date); //date can be converted to date.tostring ()}
Attach a piece to see the blog http://blog.csdn.net/foamflower/article/details/2171537
Inserting date-type data into MySQL