jdbc 6.0

1.获取数据库自动生成的键值

 1 package com.rong.jielong;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 import java.sql.Statement;
 9 
10 public class Test11 {
11 
12     /**
13      * 获取数据库自动生成的键值
14      * 
15      * @author 容杰龙
16      */
17     public static void main(String[] args) {
18         try {
19             Class.forName("com.mysql.jdbc.Driver");
20             String url = "jdbc:mysql://localhost:3306/rjl";
21             String user = "rjl";
22             String password = "123";
23             Connection conn = DriverManager.getConnection(url, user, password);
24             // MySQL自动生成的键值可先用null填补位置
25             String sql = "insert into user values(null,?,?,?)";
26 
27             // 创建一个默认 PreparedStatement 对象,该对象能获取自动生成的键,适合insert语句搜索
28             PreparedStatement ps = conn.prepareStatement(sql,
29                     Statement.RETURN_GENERATED_KEYS);
30 
31             ps.setString(1, "hhh");
32             ps.setInt(2, 22);
33             ps.setString(3, "www");
34             int count = ps.executeUpdate();
35             if (count > 0) {
36                 // 获取自动生成的键值-----结果集
37                 ResultSet rs = ps.getGeneratedKeys();
38                 while (rs.next()) {
39                     int autoKey = rs.getInt(1);
40                     System.out.println(autoKey);
41                 }
42             } else {
43                 System.out.println("获取失败!");
44             }
45         } catch (ClassNotFoundException e) {
46             e.printStackTrace();
47         } catch (SQLException e) {
48             e.printStackTrace();
49         }
50 
51     }
52 
53 }

 

posted @ 2017-11-05 15:24  57容杰龙  阅读(260)  评论(0编辑  收藏  举报