随笔- 119  文章- 1  评论- 0  阅读- 437 

今天学习单表的增删改查中的增,这是在期末考试中一定要拿到的分数
首先通过 DriverManager.getConnection 方法根据配置信息建立与数据库的连接。
构建 INSERT 语句的 PreparedStatement 对象,其中 ? 是占位符,后续通过 setString、setInt 等方法按照顺序设置对应占位符的值,这样可以避免 SQL 注入风险。
调用 executeUpdate 方法执行插入操作,它返回受影响的行数,如果返回值大于 0,则表示插入成功。
最后关闭 PreparedStatement 和 Connection,释放相关资源,这是良好的编程习惯,避免出现资源浪费和潜在的连接数耗尽等问题。
我以student为例写了如下代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class InsertDataExample {
public static void main(String[] args) {
// 读取数据库连接配置
Properties properties = new Properties();
try {
properties.load(InsertDataExample.class.getClassLoader().getResourceAsStream("db.properties"));
String url = properties.getProperty("db.url");
String username = properties.getProperty("db.username");
String password = properties.getProperty("db.password");

        // 1. 建立数据库连接
        Connection connection = DriverManager.getConnection(url, username, password);

        // 2. 编写 SQL 语句,这里使用 PreparedStatement 更安全,能防止 SQL 注入
        String sql = "INSERT INTO students (name, age, gender) VALUES (?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, "张三");
        preparedStatement.setInt(2, 20);
        preparedStatement.setString(3, "男");

        // 3. 执行插入操作
        int rowsAffected = preparedStatement.executeUpdate();
        if (rowsAffected > 0) {
            System.out.println("数据插入成功");
        }

        // 4. 关闭资源,释放连接等,防止资源泄漏
        preparedStatement.close();
        connection.close();
    } catch (SQLException | java.io.IOException e) {
        e.printStackTrace();
    }
}

}

 posted on   敝屣  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示