03-JDBC连接MySQL数据库【插入数据】

JDBC连接mysql–学习目录:

地址:http://blog.csdn.net/baidu_37107022/article/details/72600018

1.实现插入步骤

这里写图片描述

前三个步骤:注册、获得连接,创建statement对象方法,见上一节:

02-JDBC实战–JDBC查询数据库MySQLhttp://blog.csdn.net/baidu_37107022/article/details/72597975

2.使用jdbc向数据库中插入数据

这里使用的是queryDemo数据库,表格为demo1student,表中数据如下:

这里写图片描述

1)插入单个数据

SQL语法:insert into 表名 values (值1,值2,值3,…)

代码演示

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import org.junit.Test;

public class Test7 {
    //插入insert单个数据
        @Test
        public void insert1(){
            Connection connection=null;
            PreparedStatement ps=null;

            try {
                //1.register
                Class.forName("com.mysql.jdbc.Driver");

                //2.getConnection
                String url="jdbc:mysql://localhost:3306/queryDemo";
                Properties info=new Properties();
                info.put("user", "root");
                info.put("password", "123");
                connection=DriverManager.getConnection(url, info);

                //3.create Statement
                String sql="insert into demo1student (name,age,score) values(?,?,?)";
                ps=connection.prepareStatement(sql);
                ps.setString(1, "Mary");
                ps.setInt(2, 22);
                ps.setInt(3, 99);

                //4.excuteUpdate
                int resultSet=ps.executeUpdate();
                if(resultSet>0){
                    //如果插入成功,则打印success
                    System.out.println("Sucess");
                }else{
                    //如果插入失败,则打印Failure
                    System.out.println("Failure");
                }

            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                //5.关闭资源
                if(connection!=null){
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(ps!=null){
                    try {
                        ps.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
}

表格数据变化:
1.运行前:
这里写图片描述

2.运行后:
特别说明:id是主键,并且设置了自动增长。因为之前删除了id=9的数据,所以这里从10开始,自动增长的规则见:MySQL【连接地址】
这里写图片描述


2)使用addbatch()–插入多个数据

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.junit.Test;

public class Test8 {
    @Test
    public void insert5(){
        Connection connection=null;
        PreparedStatement ps=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");

            String url="jdbc:mysql://localhost:3306/queryDemo";
            String user="root";
            String password="123";
            connection=DriverManager.getConnection(url, user, password);

            String sql="insert into demo1student (name,age,score) values(?,?,?),(?,?,?)";
            ps=connection.prepareStatement(sql);
            ps.setString(1, "Jane");
            ps.setInt(2, 25);
            ps.setInt(3, 100);
            ps.setString(4, "李磊");
            ps.setInt(5, 28);
            ps.setInt(6, 99);

            //4.excuteUpdate
            ps.addBatch();
            int[] resultSet=ps.executeBatch();

            if(resultSet.length >0){
                //如果插入成功,则打印success
                System.out.println("Sucess");
            }else{
                //如果插入失败,则打印Failure
                System.out.println("Failure");
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            //5.关闭资源
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

表格数据变化:

1.运行前
这里写图片描述

2.运行后:
这里写图片描述


3)使用for循环–插入多个数据

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import org.junit.Test;

public class Test9 {
        //使用for循环--插入insert多个数据
        @Test
        public void insert2(){

            Connection connection=null;
            PreparedStatement ps=null;

            try {
                Class.forName("com.mysql.jdbc.Driver");

                String url="jdbc:mysql://localhost:3306/queryDemo";
                Properties info=new Properties();
                info.put("user", "root");
                info.put("password", "123");
                connection=DriverManager.getConnection(url, info);

                String sql="insert into demo1student (name,age,score) values(?,?,?)";
                ps=connection.prepareStatement(sql);
                int num=0;
                for(int i=0;i<5;i++){
                    //这里我只是随机赋值,可以将你想要添加的数据放在集合中,使用for插入数据
                    //name赋值
                    ps.setString(1, "汪洋"+i);
                    //age赋值
                    ps.setInt(2, 20+(int)Math.random()*5);
                    //score赋值
                    ps.setInt(3, 77+(int)Math.random()*20);
                    num=ps.executeUpdate();
                }


                if(num>0){
                    //如果插入成功,则打印success
                    System.out.println("Sucess");
                }else{
                    //如果插入失败,则打印Failure
                    System.out.println("Failure");
                }

            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                //5.关闭资源
                if(connection!=null){
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(ps!=null){
                    try {
                        ps.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        }
}

运行结果:

1.运行前
这里写图片描述

2.运行后
这里写图片描述

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 JDBC(Java Database Connectivity)来连接数据库插入数据MySQL 数据库。以下是一个简单的示例代码: ```java import java.sql.*; public class InsertDataExample { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/your_database_name"; static final String USER = "your_username"; static final String PASS = "your_password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开连接 System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); // 执行查询 System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql = "INSERT INTO your_table_name " + "VALUES (value1, value2, value3)"; stmt.executeUpdate(sql); // 完成后关闭 stmt.close(); conn.close(); } catch (SQLException se) { // 处理 JDBC 错误 se.printStackTrace(); } catch (Exception e) { // 处理 Class.forName 错误 e.printStackTrace(); } finally { // 关闭资源 try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } // 什么都不做 try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } System.out.println("Goodbye!"); } } ``` 在上面的示例中,你需要将 `your_database_name` 替换为你的数据库名称,`your_username` 和 `your_password` 替换为你的 MySQL 用户名和密码,`your_table_name` 替换为你要插入数据的表名称,以及 `value1`、`value2` 和 `value3` 替换为你要插入的实际值。 注意,上述代码只是一个示例,实际使用时需要根据你的实际需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值