package mysql;
import java.sql.*;
import java.text.SimpleDateFormat;
public class Test {
public static void main(String[] args) throws Exception{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "nazi1987");
String name="fff";
int age=27;
String birthday="2001-07-23";
String password="789";
String sex="'female'";//此处赋值过大,估计是数据库中该字段的长度为2,太小了。
String sql="insert into user(name,password,age,sex,birthday)values(?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,name);
ps.setString(2,password);
ps.setInt(3,age);
ps.setString(4,sex);
java.util.Date temp=new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
java.sql.Date bir=new java.sql.Date(temp.getTime());
ps.setDate(5,bir);
ps.executeUpdate();
Statement st=con.createStatement();
String sql1="select * from user";
ResultSet rs=st.executeQuery(sql1);
while(rs.next()){
int id=rs.getInt(1);
String name1=rs.getString(2);
String pass=rs.getString(3);
int age1=rs.getInt(4);
String sex1=rs.getString(5);
java.util.Date d=rs.getDate(6);//估计此处也会有异常,因为从数据库中取的时间格式是:java.sql.Date 所有需要转换成java.util.Date 即java.util.Date d= new java.util.Date(rs.getDate(6).getTime());
System.out.println(id+":"+name1+":"+pass+":"+age1+":"+sex1+":"+d);
}
con.close();
}
}
|