我得到一个字符串值,如"2012-01-20",并将其转换为sql.Date将其插入数据库中.
码
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);
}
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,我收到异常""[Microsoft] [ODBC SQL Server驱动程序]可选功能未实现"
我在这做错了什么?请帮忙!
删除单引号 - ('DOB')和INSERT(拼写错误)
String query = "INSERT INTO EMPLOYEE (DOB) VALUES (?)";
Run Code Online (Sandbox Code Playgroud)
您可以使用java.sql.Date.valueOf("2012-01-20")方法将字符串转换为SQL日期.
使用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);
}
Run Code Online (Sandbox Code Playgroud)