wuruize888 2017-06-01 00:49 采纳率: 66.7%
浏览 927
已采纳

java web,关于封装入库的问题?

思路上有点不清楚,经常看到数据库表里的字段通过class封装后在通过prepareStatement装入数据库。
哪位师傅能帮我写个完整的代码,我学习一下。

比如
class student{
String name;
int age;
String aihao;
底下怎么写?怎么在数据库操作中应用这个类。谢谢
}

  • 写回答

2条回答 默认 最新

  • 冷咖啡15 2017-06-01 10:42
    关注

    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);

    }

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?