Java(32)_ JDBC向数据库中插入数据

 

复制代码
package MYSQK;
import java.sql.*;

/**
 * PreparedStatement 对象可以对sql语句进行预编译,预编译的信息会存在存储该对象中,当相同的sql语句再次执行时,程序
 *   会使用PrepareStatement对象中,而不需再次编译去查询数据库,大大提高了数据的访问效率
 */

public class Insert {
    public  static  void main(String[] args) throws SQLException{
        Connection conn=null;
        PreparedStatement pst =null;

        try {
            // 1 加载驱动类
            Class.forName("com.mysql.jdbc.Driver");
            // 2 通过DriverManager获取connection对象
             String url="jdbc:mysql://192.168.64.128:3306/jdbc?" +
                      "user=root&password=815qza&useUnicode=true&characterEncoding=UTF8";
             conn = DriverManager.getConnection(url);
             if (!conn.isClosed()){
                 System.out.println("Succeeded connecting to the Database!");
             }else{
                 System.out.println("Sorry,failed  connecting to the Database");
             }
             // 3 获取pre对象
              String sql = "INSERT  INTO  USERS(name,PASSWORD,email,birthday) VALUES (?,?,?,?)";
               pst = conn.prepareStatement(sql);
             //为sql参数赋值
               pst.setString(1,"bowen5");
               pst.setString(2,"815qza");
               pst.setString(3,"bowen815@126.com");
               pst.setString(4,"1990-11-01");
             //4  使用prepare对象执行sql语句
               int count = pst.executeUpdate();
               System.out.println("影响数据库的条数为:"+count);
             //5 操作result结果集
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            // 6 关闭连接
             pst.close();
             conn.close();
        }
    }
}
复制代码

 

 

posted @   sunnybowen  阅读(4885)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示