[英]cannot insert java.sql.Date to the “Date” field in the database
I am getting a string value such as "2012-01-20" and converting it to sql.Date to insert it in the database. 我正在获取一个字符串值,例如“ 2012-01-20”,并将其转换为sql.Date,以将其插入数据库中。
code 码
java.util.Date DOB = new java.util.Date();
String datetext = txtDate.getText();
SimpleDateFormat sd = new SimpleDateFormat("yyyy-mm-dd");
DOB = sd.parse(datetext);
java.sql.Date sqlDate = new java.sql.Date(DOB.getTime());
String query = "ISERT INTO EMPLOYEE ('DOB')"
+ " VALUES ( ? ) ";
con = db.createConnection();
try{
ps = con.prepareStatement(query);
ps.setDate(1, sqlDate);
ps.executeQuery();
}catch(Exception ex){
System.err.print(ex);
}
When i run this code I am getting an exception ""[Microsoft][ODBC SQL Server Driver]Optional feature not implemented" 运行此代码时,出现异常“” [Microsoft] [ODBC SQL Server驱动程序]未实现可选功能”
what am i doing wrong here ? 我在这里做错了什么? pls help ! 请帮助!
Remove single quote - ('DOB') and INSERT
(misspell) 删除单引号-('DOB')和INSERT
(misspell)
String query = "INSERT INTO EMPLOYEE (DOB) VALUES (?)";
You may use java.sql.Date.valueOf("2012-01-20")
method to convert string to sql date. 您可以使用java.sql.Date.valueOf("2012-01-20")
方法将字符串转换为sql日期。
Use executeUpdate()
method instead of executeQuery(). 使用executeUpdate()
方法而不是executeQuery()。
String query = "INSERT INTO EMPLOYEE (DOB) VALUES (?)";
con = db.createConnection();
try{
ps = con.prepareStatement(query);
ps.setDate(1, java.sql.Date.valueOf("2012-01-20"));
//Or use
// ps.setTimestamp(1, new Timestamp(DOB.getTime()));
ps.executeUpdate();
}catch(Exception ex){
System.err.print(ex);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.