Java MySQL INSERT(使用PreparedStatement)

时间:2014-11-08 17:15:11

标签: java mysql

我向你们提出一个小问题。

我尝试将用户添加到数据库。

用户具有以下字段:id,name,surname等。

方法

public static String insertUsertoDatabase(Connection con, User userToAdd)

做这样的事情

 // the mysql insert statement
        String query = " insert into User (id,log,pass)"
                + " values (?, ?, ?)";

        // create the mysql insert preparedstatement
        PreparedStatement preparedStmt = con.prepareStatement(query);
        preparedStmt.setInt(1, 1);
        preparedStmt.setString(2, "h");
        preparedStmt.setString(3, "l");

setUser方法

    public String setUser(User userToBase) {
    return insertUsertoDatabase(con, userToBase);
}

和main.java

User us1 = new User("9", "h", "l");
db.setUser(us1); //insert to database User u1

如何将User构造函数中的值放入preparedStmt?

我有一个像这样的构造函数:

public class User(id, login, pass) {
      this.id = id;
      etc.

}

但我想知道如何从构造函数

发送数据
User us1 = new User("9", "h", "l");

到我的方法

public static String insertUsertoDatabase(Connection con, User userToAdd)



    preparedStmt.setInt(1, 9);           <-------------    from User constructor
    preparedStmt.setString(2, "h");
    preparedStmt.setString(3, "l");

1 个答案:

答案 0 :(得分:0)

你可能需要这样的东西:

// TODO: use meaningful names
private String pim;
private String pam;
private String poom;

public User(String pim, String pam, String poom) {
    this.pim = pim;
    this.pam = pam;
    this.poom = poom;
}

public String getPim() {
    return this.pim;
}

// ...

然后:

User usr1 = new User("9", "h", "l");
usr1.getPim() // = "9"
// ...

阅读constructors