import java.sql.*;
public class JDBCTest03 {
public static void testGetKeyValue() throws ClassNotFoundException, SQLException, SQLException {
String sql = "INSERT INTO examstudent(type,id_card, exam_card, student_name,location,grade)"
+ "VALUES(?,?,?,?,?,?)";
String driverClass = "com.mysql.jdbc.Driver";
String jdbcUrl = "jdbc:mysql://localhost:3306/myemployees?useUnicode=true&useSSL=false";
String user = "root";
String password = "abcd123456";
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(jdbcUrl,user,password);
// 返回主键核心代码,preparedStatement()重载方法
PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setInt(1,5);
preparedStatement.setString(2,"1234567890");
preparedStatement.setString(3,"12345");
preparedStatement.setString(4,"ee");
preparedStatement.setString(5,"SH");
preparedStatement.setInt(6,10);
preparedStatement.executeUpdate();
// 通过getGeneratedKeys()获取包含了新恒诚的主键的ResultSet对象
// 在ResultSet中只有1列 GENERATED_KEY,用于存放新生成的主键值
ResultSet rs = preparedStatement.getGeneratedKeys();
if(rs.next()){
System.out.println(rs.getObject(1));
}
ResultSetMetaData rsmd = rs.getMetaData();
for(int i = 0; i < rsmd.getColumnCount();i++){
System.out.println(rsmd.getColumnName(i + 1));
}
rs.close();
preparedStatement.close();
connection.close();
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
testGetKeyValue();
}
}
复制