温馨提示×

jdbc怎么实现添加功能

小亿
82
2023-12-21 10:41:26
栏目: 编程语言

要实现添加功能,你可以按照以下步骤进行操作:
1. 创建一个连接到数据库的`Connection`对象,可以使用`DriverManager.getConnection()`方法来获取连接。连接字符串包含数据库的URL、用户名和密码。
2. 创建一个`PreparedStatement`对象,用于预编译SQL语句。SQL语句中使用`?`作为占位符,稍后会将真实的值替换进去。
3. 使用`PreparedStatement`对象的`setXxx()`方法为占位符设置真实的值,其中`setXxx()`的参数类型要与数据库中对应列的数据类型相匹配。
4. 调用`PreparedStatement`对象的`executeUpdate()`方法来执行SQL语句。该方法返回一个整数,表示受影响的行数。
5. 根据需要,可以使用`Connection`对象的`commit()`方法提交事务。
6. 最后,关闭`PreparedStatement`对象和连接对象,释放资源。
以下是一个示例代码,演示如何向数据库的`user`表中添加一条记录:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class AddExample {

    public static void main(String[] args) {

        // 连接数据库

        try (Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/mydb”, 

        “username”, “password”)) {

            // 创建预编译的SQL语句

            String sql = “INSERT INTO user (name, age) VALUES (?, ?)”;

            PreparedStatement stmt = conn.prepareStatement(sql);

            // 设置占位符的值

            stmt.setString(1, “张三”);

            stmt.setInt(2, 20);

            // 执行SQL语句

            int rows = stmt.executeUpdate();

            System.out.println(“添加了 " + rows + " 行数据”);

        } catch (SQLException e) {

            e.printStackTrace();

        }

    } }

请注意,上述代码中的数据库URL、用户名和密码需要根据实际情况进行修改。另外,PreparedStatement对象也可以使用conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)方法来获取自动生成的主键。

0