JDBC資函仟奐芝村議徭奐麼囚
扮寂:2011-04-11 51cto鴬人 leizhimin
械械壓聞喘Hibernate、iBatis扮昨?輝峨秘匯訳方象議扮昨?糞悶Bean議圻**麼囚祥 験貧仟峙阻。
壓JDBC嶄?匆辛參宥狛延?議返隈栖恂欺宸泣。和中頁倖霞編議弌箭徨。
匯、桟廠
MySQL5.1
mysql-connector-java-5.1.10
jdk1.5
CREATE TABLE book(
code bigint(20) unsigned NOT NULL AUTO_INCREMENT,
kind varchar(45) NOT NULL,
name varchar(45) NOT NULL,
PRIMARY KEY(code, kind)
) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = latin1
屈、資函徭奐麼囚
import lavasoft.common.DBToolkit;
import java.sql.*;
/**
* JDBC資函仟奐芝村議麼囚
*
* @author leizhimin 2009-12-4 13:20:15
*/
public class InsertKeyTest {
public static void main(String[] args) {
insertWithStaticSQL();
insertWithParperedSQL();
}
/**
* 圓協吶SQL庁塀?資函仟奐芝村議麼囚
*/
public static void insertWithParperedSQL() {
Connection conn = null;
try {
conn = DBToolkit.getConnection();
String sql = "insert into testdb.user (name, pswd) values(?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.NO_GENERATED_KEYS);
pstmt.setString(1, "laozhang");
pstmt.setString(2, "111111");
pstmt.executeUpdate();
//殊沫喇噐峇佩緩 Statement 斤?遇幹秀議侭嗤徭強伏撹議囚
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
//岑凪叙嗤匯 双?絞資函及匯双
Long id = rs.getLong(1);
System.out.println("-----圓協吶SQL庁塀-----id = " + id);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection (conn);
}
}
/**
* 床蓑SQL庁塀?資函仟奐芝村議麼囚
*/
public static void insertWithStaticSQL() {
Connection conn = null;
try {
conn = DBToolkit.getConnection();
String sql = "insert into testdb.user (name, pswd) values(''ttttt'',''121'')";
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.NO_GENERATED_KEYS);
pstmt.executeUpdate();
//殊沫喇噐峇佩緩 Statement 斤?遇幹秀議侭嗤徭強伏撹議囚
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
//岑凪叙嗤匯 双?絞資函及匯双
Long id = rs.getLong(1);
System.out.println("-----床蓑SQL庁塀-----id = " + id);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection (conn);
}
}
}
峇佩潤惚?
-----床蓑SQL庁塀-----id = 8
-----圓協吶SQL庁塀-----id = 9
Process finished with exit code 0
竃侃?http://lavasoft.blog.51cto.com/62575/238643 |