Java 原生MySQL JDBC 插入后返回自增长ID,基于PreparedStatement executeUpdate

3 篇文章 0 订阅

返回ID的核心代码

关键在于PreparedStatement ps = DBConnection.getConn().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)的Statement.RETURN_GENERATED_KEYS
以及通过以下代码取id
ResultSet rs = ps.getGeneratedKeys();
if (rs.next())
return rs.getInt(1);

返回ID的完整代码

//万能修改方法,返回自动增长的ID
    public static int executeUpdateReturnId(String sql, Object... args){
        try(PreparedStatement ps = DBConnection.getConn().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            ps.executeUpdate();

            ResultSet rs = ps.getGeneratedKeys();
            if (rs.next())
                return rs.getInt(1);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

连接数据库代码

public class DBConnection {
    private static Connection conn;

    static {
        try {
            Properties properties = new Properties();
            
            String propertiesPath = "/Volumes/TOSHIBA EXT/Laner/JavaDT/classExerciseWeb1/webProject/web/WEB-INF/classes/com/laner/myPro.properties";

            //Web项目在Tomcat下查找properties文件
//            String propertiesPath = Objects.requireNonNull(DBConnection.class.getClassLoader().getResource("myPro.properties")).getPath().replace("%20"," ");
            //Java项目查找properties文件
            String propertiesPath = "src/com/laner/myPro.properties";
            properties.load(new FileInputStream(propertiesPath));

            String dbClassName = (String)properties.get("DBClassName");
            String dbUrl = (String)properties.get("DBURL");
            String dbUsername = (String)properties.get("DBUsername");
            String dbPassword = (String)properties.get("DBPassword");

            Class.forName(dbClassName);
            conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
        } catch (IOException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn() {
        return conn;
    }
}

myPro.properties

DBClassName = com.mysql.cj.jdbc.Driver
DBURL = jdbc:mysql://localhost:3306/jave2105ProjectOne
DBUsername = root
DBPassword = root

总结

更多数据库封装工具可以看这个链接
Java利用反射封装DBUtil,mysql万能增删改查工具类,附源码


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值