思路上有点不清楚,经常看到数据库表里的字段通过class封装后在通过prepareStatement装入数据库。
哪位师傅能帮我写个完整的代码,我学习一下。
比如
class student{
String name;
int age;
String aihao;
底下怎么写?怎么在数据库操作中应用这个类。谢谢
}
思路上有点不清楚,经常看到数据库表里的字段通过class封装后在通过prepareStatement装入数据库。
哪位师傅能帮我写个完整的代码,我学习一下。
比如
class student{
String name;
int age;
String aihao;
底下怎么写?怎么在数据库操作中应用这个类。谢谢
}
public void insertStudent(Student stu) {
Connection con = null;
PreparedStatement pst = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "komal"; //数据库名
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + dbName, user, pass);
String sql = "insert into student (name,age,aihao)values(?,?,?) ";
pst = con.prepareStatement(sql);
pst.setString(1, stu.getName());
pst.setInt(2, stu.getAge());
pst.setString(1, stu.getAihao());
pst.executeUpdate();
pst.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}