jdbc获取自增列值
向数据库插入一条数据时,有时可能想直接获取到该列值插入到数据库后由数据库自动产生的值(如
identity ),获取到该值的方法如下:
这是一个连接MSSQL的类
package com.maomao.db;
imp
imp
imp
imp
imp
public class DB {
public Connection getCon() {
String url = "jdbc:jtds:sqlserver://127.0.0.1:1433/northwind;user=sa;password=sa";
new net.sourceforge.jtds.jdbc.Driver();
try {
return DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Statement getStmt(Connection con) {
try {
return con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public PreparedStatement getPstmt(Connection con, String sql,int returnkey) {
try {
PreparedStatement pstmt =con.prepareStatement(sql,returnkey);
return pstmt;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
注意:如果想能获取到子增列的值的话在得到 Statement子类对象(PreparedStatement 对象)的时候一定要采用Connection对象的prepareStatement(String sql, int autoGeneratedKeys) 方法;
下面是一个测试类:
package com.maomao.db.test;
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
int key=-1;
DB db = new DB();
Connection con = db.getCon();
String sql = "insert into Categories values(?,?,?)";
PreparedStatement pstmt = db.getPstmt(con, sql,
Statement.RETURN_GENERATED_KEYS);
Image img = Toolkit.getDefaultToolkit().getImage(
Test.class.getResource("http://www.cnblogs.com/http://www.cnblogs.com/img/IP.gif"));
InputStream fis = Test.class
.getResourceAsStream("http://www.cnblogs.com/http://www.cnblogs.com/img/IP.gif");
byte[] b = new byte[1024];
try {
fis.read(b);
} catch (IOException e) {
e.printStackTrace();
}
try {
pstmt.setString(1, "瓜瓜");
pstmt.setBytes(3, b);
pstmt.setString(2, "就是瓜瓜");
pstmt.executeUpdate();
ResultSet rskey = pstmt.getGeneratedKeys();
if(rskey.next())
key = rskey.getInt(1);
else{
System.out.println("o, my god!");
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(key+"------------");
}
}
好啦,采用这样的方式就能获取到自增列的值啦。

浙公网安备 33010602011771号