获取数据库自动生成的主键的值
1.getGeneratedKeys()
这里我只测试过可以获取 MySQL和SQL Server数据库的自增主键值
设置主键:
mysql: create table student(id int auto_increment primary key not null, name varchar(15));
sqlserver: create table student(id int identity(1,1) primary key not null, name varchar(15));
oracle: 要通过触发器来设置主键自增.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement;
import org.junit.Test;
public class test { @Test public void testGetKeyValue() { Connection conn = null; PreparedStatement ps = null; String sql = "INSERT INTO Student VALUES(?,?,?)"; ResultSet rs = null; try { conn = JDBCTools.getConnection(); ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, "Jhon"); ps.setString(2, "jhon@qq.com"); ps.setDate(3, new Date(new java.util.Date().getTime())); ps.executeUpdate(); rs = ps.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)); } } catch (Exception e) { e.printStackTrace(); }finally { JDBCTools.release(rs, ps, conn); } } }
|
2.元数据获取数据库相关信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement;
import org.junit.Test;
public class test { @Test public void testJDBC() { Connection conn = null; DatabaseMetaData db = null; ResultSet rs = null; try { conn = JDBCTools.getConnection(); db = conn.getMetaData(); System.out.println(db.getDatabaseProductVersion()); System.out.println(db.getUserName()); rs = db.getCatalogs(); while(rs.next()) { System.out.println(rs.getString(1)); } } catch (Exception e) { e.printStackTrace(); }finally { JDBCTools.release(rs, null, conn); } } }
|