五.獲得MYSQL數據庫自動生成的主鍵


測試腳本如下:

1  create table test1
2 (
3      id int primary key auto_increment,
4      name varchar(20)
5 );

 

測試代碼:

package me.tanlei.demo;

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

import me.tanlei.jdbc.jdbcUtils;

public class Test {
   public static void main(String[] args) {
    Connection connection=null;
    PreparedStatement pStatement=null;
    ResultSet resultSet=null;
    
    try {
        connection=jdbcUtils.getConnection();
       String sql="insert into test1(name) values(?)";
       pStatement=connection.prepareStatement(sql);
       pStatement.setString(1, "aaa");
       pStatement.executeUpdate();
       //獲取數據庫自動生成的主鍵 resultSet=pStatement.getGeneratedKeys();  if(resultSet.next()) {
           System.out.println(resultSet.getInt(1));
       }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        jdbcUtils.release(connection, pStatement, resultSet);
    }
    
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM