第5章 JDBC的其他操作
1、JDBC 取得数据库自动生成的主键
获取自增长的键值:
(1)在创建PreparedStatement对象时
原来:
PreparedStatement pst = conn.preparedStatement(sql);
现在:
PreparedStatement pst = conn.prepareStatement(orderInsert,Statement.RETURN_GENERATED_KEYS);
(2)原来执行更新
原来:
int len = pst.executeUpdate();
现在:
int len = pst.executeUpdate();
ResultSet rs = pst.getGeneratedKeys();
if(rs.next()){
Object key = rs.getObject(第几列);//获取自增长的键值
}
package com.atguigu.other;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Scanner;
import org.junit.Test;
import com.atguigu.utils.JDBCUtils;
public class TestGetGenericKey { @Test public void add() throws Exception { Scanner input = new Scanner(System.in); System.out.println("请输入姓名:"); String name = input.nextLine();
System.out.println("请输入性别:"); String gender = input.nextLine();
|