JAVA中三种获得⾃动⽣成主键的⽅法
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* 三种获得⾃动⽣成主键的⽅法。
*
*/
public class TestGetPK
{
public static void main(String[] args) throws Exception
{
Class.forName("com.gba.jdbc.Driver" );
String url = "jdbc:gba://localhost/mytest" ;
Connection con = Connection(url, "root" , "111111" );
System.out.println(getPK1(con));
System.out.println(getPK2(con));
System.out.println(getPK3(con));
}
/**
* 使⽤JDBC 3.0提供的 getGeneratedKeys。推荐使⽤
*
* @param con
* @return
* @throws Exception
三年级数学竖式*/
public static long getPK1(Connection con) throws Exception
{
Statement stmt = ateStatement();
Statement.RETURN_GENERATED_KEYS);
int autoIncKeyFromApi = -1 ;
ResultSet rs = GeneratedKeys();
if (rs.next())
何曾吹落北风中{
autoIncKeyFromApi = rs.getInt(1);
}
return autoIncKeyFromApi;
}
/**
* 使⽤数据库⾃⼰的特殊SQL.
*
* @param con
* @return
* @throws Exception
布和*/
public static long getPK2(Connection con) throws Exception
炸饺子皮{
Statement stmt = ateStatement();
Statement.RETURN_GENERATED_KEYS);
钢琴重量
int autoIncKeyFromFunc = -1 ;
ResultSet rs = uteQuery( "SELECT LAST_INSERT_ID()");
图片非主流if (rs.next())
{
autoIncKeyFromFunc = rs.getInt(1);
}
}
return autoIncKeyFromFunc;
}
/**
* 使⽤可更新的结果集。
* @param con
* @return
莲子心的功效与作用
* @throws Exception
*/
public static long getPK3(Connection con) throws Exception
{
Statement stmt = ateStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_UPDATABLE);
ResultSet rs = uteQuery("SELECT * FROM t_Type");
rs.updateString("name", "AUTO INCREMENT here?");
rs.inrtRow();
rs.last();
int autoIncKeyFromRS = rs.getInt("id" );网页截图快捷键
return autoIncKeyFromRS;
}
}