我编译了这个,但是这个代码在resultSet.getDate()方法中出现了java.sql.SQLException和java.text.ParseException。
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Main {
public static void main(String[] args) throws SQLException {
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection
("jdbc:sqlite:C:/sqlite-tools/test.db");
Statement statement = connection.createStatement();
String sql = "CREATE TABLE t1 (" +
"no INTEGER PRIMARY KEY, " +
"date DATE, " +
"content TEXT)";
statement.executeUpdate(sql);
sql = "INSERT INTO t1 (date, content)" +
"VALUES(DATETIME('NOW', 'LOCALTIME'), 'test');";
statement.executeUpdate(sql);
ResultSet resultSet = statement.executeQuery("SELECT * FROM t1;");
while(resultSet.next()) {
// here occurs exception ↓ :(
Date date = resultSet.getDate("date");
// here occurs exception ↑ :(
String text = resultSet.getString("content");
System.out.println(date + " " + text);
}
statement.close();
connection.close();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
}
异常解释是这样的。
Exception in thread "main" java.sql.SQLException: Error parsing time stamp
at org.sqlite.jdbc3.JDBC3ResultSet.getDate(JDBC3ResultSet.java:327)
at org.sqlite.jdbc3.JDBC3ResultSet.getDate(JDBC3ResultSet.java:346)
at com.planb.main.Main.main(Main.java:35)
Caused by: java.text.ParseException: Unparseable date: "2016-12-20 17:08:07" does not match (\p{Nd}++)\Q-\E(\p{Nd}++)\Q-\E(\p{Nd}++)\Q \E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q.\E(\p{Nd}++)
at org.sqlite.date.FastDateParser.parse(FastDateParser.java:299)
at org.sqlite.date.FastDateFormat.parse(FastDateFormat.java:490)
at org.sqlite.jdbc3.JDBC3ResultSet.getDate(JDBC3ResultSet.java:324)
... 2 more
我找不到两个小时的解决方案。请帮帮我。 :(
答案 0 :(得分:0)
正如@Nurzhan建议的那样,您必须定义日期格式,然后使用它从String
将日期解析为resultSet
。一个例子:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(resultSet.next()) {
Date date = formatter.parse(resultSet.getString("date"));
String text = resultSet.getString("content");
System.out.println(date + " " + text);
}
输出将是:
12月20日星期二11:24:40 EET 2016测试