package jdbc;

import java.sql.*;

public class JDBCInsert { public static void insert() { try { // 加载驱动 Class.forName('com.mysql.cj.jdbc.Driver'); } catch (ClassNotFoundException e) { e.printStackTrace(); }

    Connection conn = null;
    PreparedStatement statement = null;
    try{
        // 连接数据库
        conn = DriverManager.getConnection('jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC',
                'root','123456');

        // 插入数据
        String sql = 'INSERT INTO student (id, name, sex, age) VALUES (?, ?, ?, ?)';
        statement = conn.prepareStatement(sql);
        statement.setInt(1, 1);
        statement.setString(2, '张三');
        statement.setString(3, '男');
        statement.setInt(4, 19);
        statement.executeUpdate();

        statement.setInt(1, 2);
        statement.setString(2, '李四');
        statement.setString(3, '女');
        statement.setInt(4, 18);
        statement.executeUpdate();

        statement.setInt(1, 3);
        statement.setString(2, '王五');
        statement.setString(3, '男');
        statement.setInt(4, 20);
        statement.executeUpdate();

        // 查询数据并输出
        String query = 'SELECT * FROM student';
        ResultSet rs = statement.executeQuery(query);
        while(rs.next()){
            System.out.println(rs.getInt('id')+' '+rs.getString('name')
                    +' '+rs.getString('sex')+' '+rs.getInt('age'));
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
    finally {
        try {
            if (statement != null)
                statement.close();
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

}

Java JDBC 插入数据并查询示例 - 向 MySQL 数据库 student 表插入数据

原文地址: https://www.cveoy.top/t/topic/opuD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录