前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JDBC 获取插入记录的主键值(9)

JDBC 获取插入记录的主键值(9)

作者头像
桑鱼
发布2020-03-17 17:11:13
9680
发布2020-03-17 17:11:13
举报
代码语言:javascript
复制
import java.sql.*;

public class JDBCTest03 {
    public static void testGetKeyValue() throws ClassNotFoundException, SQLException, SQLException {
        String sql = "INSERT INTO examstudent(type,id_card, exam_card, student_name,location,grade)"
                + "VALUES(?,?,?,?,?,?)";
        String driverClass = "com.mysql.jdbc.Driver";
        String jdbcUrl = "jdbc:mysql://localhost:3306/myemployees?useUnicode=true&useSSL=false";
        String user = "root";
        String password = "abcd123456";
        Class.forName(driverClass);
        Connection connection = DriverManager.getConnection(jdbcUrl,user,password);
        // 返回主键核心代码,preparedStatement()重载方法
        PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setInt(1,5);
        preparedStatement.setString(2,"1234567890");
        preparedStatement.setString(3,"12345");
        preparedStatement.setString(4,"ee");
        preparedStatement.setString(5,"SH");
        preparedStatement.setInt(6,10);
        preparedStatement.executeUpdate();
        // 通过getGeneratedKeys()获取包含了新恒诚的主键的ResultSet对象
        // 在ResultSet中只有1列 GENERATED_KEY,用于存放新生成的主键值
        ResultSet rs = preparedStatement.getGeneratedKeys();
        if(rs.next()){
            System.out.println(rs.getObject(1));
        }
        ResultSetMetaData rsmd = rs.getMetaData();
        for(int i = 0; i < rsmd.getColumnCount();i++){
            System.out.println(rsmd.getColumnName(i + 1));
        }
        rs.close();
        preparedStatement.close();
        connection.close();
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        testGetKeyValue();
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档