用于插入新记录和更新现有记录的JDBC代码

时间:2016-05-06 07:33:11

标签: jdbc

如果记录找到更新记录,任何人都可以向我发送一条JDBC代码用于插入记录到数据库。

1 个答案:

答案 0 :(得分:1)

首先:创建连接

String dbURL = "jdbc:mysql://localhost:3306/sampledb";
String username = "root";
String password = "secret";

try {

    Connection conn = DriverManager.getConnection(dbURL, username, password);

    if (conn != null) {
        System.out.println("Connected");
    }
} catch (SQLException ex) {
    ex.printStackTrace();
}

第二:插入数据

String sql = "INSERT INTO Users (username, password, fullname, email) VALUES (?, ?, ?, ?)";

PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "bill");
statement.setString(2, "secretpass");
statement.setString(3, "Bill Gates");
statement.setString(4, "bill.gates@microsoft.com");

int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
    System.out.println("A new user was inserted successfully!");
}

第三:更新数据

String sql = "UPDATE Users SET password=?, fullname=?, email=? WHERE username=?";

PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "123456789");
statement.setString(2, "William Henry Bill Gates");
statement.setString(3, "bill.gates@microsoft.com");
statement.setString(4, "bill");

int rowsUpdated = statement.executeUpdate();
if (rowsUpdated > 0) {
    System.out.println("An existing user was updated successfully!");
}

最后:关闭连接

conn.close();

我建议您参考此链接 JDBC