JAVA中将String类型的字符串写入数据库的datatime方法如下
birth1 = txtyear.getText()+"-"+txtmoth.getText()+"-"+txtday.getText();//获取文本域里的值
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");//设置日期格式
java.util.Date birth =null;
try
{
birth = sdf.parse(birth1); //返回的是java.util.Date的值
} catch (ParseException ex)
{
}
下面是写入数据库时的SQL语句的写法,一般情况都用PreparedStatement接口,
Sql a = new Sql();//Sql是一个写好的连接数据库的类
Connection con = a.getConnection();
PreparedStatement pstmt=null;
String sql = "INSERT table()values();
pstmt = con.prepareStatement(sql);
pstmt.setDate(1, new java.sql.Date (birth.getTime()));//千万要记住写入数据库时,必须这么写
pstmt.executeUpdate();
------------------------------------------------------------------------------------------------------------------------
public class StringToDate {
public static void main(String[] args) {
String aa = "2008-01-02";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//如果要带上时分秒可设成yyyy-MM-dd hh:mm:ss
try {
java.util.Date d = df.parse(aa); //将字符串转换成日期类型的
java.sql.Date e = new java.sql.Date(d.getTime());//转换成sql类型的日期格式以方便存储到数据库中
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection con = (DriverManager.getConnection"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs;","sa","sa");
String sql = "insert into userInfo values(?,?)";
PreparedStatement st = con.prepareStatement(sql);
st.setInt(1,1);
st.setDate(2,e);
st.executeUpdate();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容