问题描述
如何在没有时间的情况下将日期插入MySQL数据库表?
我试过这些代码,但是我得到以下异常:
How do I insert date, without time, to MySQL database table?I tried these codes but I get the following exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Mar 05 00:00:00 GMT-08:00 2014,1,1)' at line 1
注意:在MySQL表中,此列的数据类型我选择了日期数据类型
NOTE: In MySQL table, data type of this column I chose date datatype
String Date = "\\d\\d\\d\\d\\D[0-1][0-9]\\D[0-3][0-9]";
while (DateMatcher.find()) {
String date = DateMatcher.group().trim();
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = formatter.parse(date);
db.insert_date(myDate,2,1);
}
我只对日期部分有问题
查询插入日期:
I've problem only with date partQuery for inserting Date :
// insert DATE
public void insert_date(Date date_str, int sentence_id ,int document_id ){
// Statements allow to issue SQL queries to the database
try {
statement = connect.createStatement();
System.out.println( "insert into Date(date_Str,Sen_id,doc_id) " +
" values(" + date_str + "," + sentence_id + "," + document_id + ")"
);
statement.executeUpdate(
"insert into test.Date(date,Sen_id,doc_id)" +
" values(" + date_str + "," + sentence_id + "," + document_id + ")"
);
}
catch(Exception e ){System.out.println(e);};
// Result set get the result of the SQL query
}
推荐答案
首先,要将 java.util.Date
保存到Java数据库中,您必须转换它。关于JDBC SQL Date
的幸运之处在于它是Java的子类 Date
。
First of all, to persist a java.util.Date
into a database in Java, you will have to convert it to java.sql.Date
. The fortunate thing about JDBC SQL Date
is that it's a subclass of Java Date
.
因此,要创建,你必须这样做:
Therefore, to create a java.sql.Date
from java.util.Date
, you will have to do this:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = formatter.parse(date);
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
db.insert_date(sqlDate);
确保 db.insert_date
仅接受。
Make sure that db.insert_date
accepts only java.sql.Date
.
您必须在哪里拨打 PreparedStatement.setDate()
function。
Where you will have to call your PreparedStatement.setDate()
function.
参见相关问题。
这篇关于如何在Java中将Date插入MySQL数据库表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!