JDBC之獲取插入語句返回的主鍵
阿新 • • 發佈:2019-01-30
該獲取主鍵並不是絕對的,也和具體的資料庫實現的驅動有關。
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
/**
* 測試JDBC中的幾個其他API
*/
public class OtherApi {
/**
* 測試create方法
* @throws SQLException
*/
@Test
public void testCreate() throws SQLException {
System.out.println(create());
}
/**
* 測試從資料庫讀取資料
* @throws SQLException
* @throws InterruptedException
*/
@Test
public void testRead() throws SQLException, InterruptedException {
read();
}
/**
* 讀取資料庫中的資料
* @throws SQLException
* @throws InterruptedException
*/
static void read() throws SQLException, InterruptedException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//建立連線
conn = JdbcUtils.getConnection();
//建立語句
st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//執行語句
rs = st.executeQuery("select id, name, money, birthday from user where id < 5");
//處理結果
while(rs.next()) {
int id = rs.getInt("id");
System.out.println("show" + id + "...");
Thread.sleep(10000);
System.out.println(id +"\t" + rs.getObject("name") + "\t"
+ rs.getObject("birthday") + "\t"
+ rs.getObject("money"));
}
} finally {
JdbcUtils.free(rs, st, conn);
}
}
/**
* 向資料庫中插入語句
* @return
* @throws SQLException
*/
static int create() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//建立連線
conn = JdbcUtils.getConnection();
//建立語句
String sql = "insert into user(name,birthday, money) values ('name2 gk', '1987-01-01', 400) ";
//通過傳入第二個引數,就會產生主鍵返回給我們
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
//返回的結果集中包含主鍵,注意:主鍵還可以是UUID,
//複合主鍵等,所以這裡不是直接返回一個整型
rs = ps.getGeneratedKeys();
int id = 0;
if(rs.next()) {
id = rs.getInt(1);
}
return id;
} finally{
JdbcUtils.free(rs, ps, conn);
}
}
}