jdbc 获取 自增主键值

来源:互联网 发布:mt4数据导出系统 编辑:程序博客网 时间:2024/05/20 05:45

建表语句:

CREATE TABLE `test` (  `id` bigint(20) NOT NULL AUTO_INCREMENT,  `username` varchar(255) DEFAULT NULL,  `password` varchar(255) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

测试类:

package com.test;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JDBCUtils1 {    public static void main(String[] args) throws Exception {        System.out.println(getGeneratedKey("test", "123"));    }    public static Connection conn;    public static String user = "root";    public static  String password = "111111";    public static  String url = "jdbc:mysql://localhost/shiro";    /**     * 获取自增的 ID     * @return     * @throws Exception      */    public static int getGeneratedKey(String username, String password) throws Exception {        Connection conn = getMysqlConn();        String sql = "insert into test (username,password) values (?,?)";        PreparedStatement pstat = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);        pstat.setString(1, username);        pstat.setString(2, password);        pstat.executeUpdate();        ResultSet rs = pstat.getGeneratedKeys();        rs.next();        int key = rs.getInt(1);        return key;    }    /**     * @return 获取 Mysql 连接     * @throws Exception     */    public static Connection getMysqlConn() throws Exception {        if(conn == null) {            Class.forName("org.gjt.mm.mysql.Driver");            conn = DriverManager.getConnection(url, user, password);        }        return conn;    }}
0 0
原创粉丝点击