I briefly summarized the methods I currently know.
- Package
Test;
- Import
Java. SQL. connection;
- Import
Java. SQL. drivermanager;
- Import
Java. SQL. resultset;
- Import
Java. SQL. statement;
- /**
- * Three Methods to automatically generate a primary key are available.
- *
- * @ Author Zhao Xueqing www.java2000.net
- *
- */
- Public
Class
Testgetpk {
- Public
Static
Void
Main (string [] ARGs) throws
Exception {
- Class. forname ("com. GBASE. JDBC. Driver"
);
- String url = "JDBC: GBASE: // localhost/mytest"
;
- Connection con = drivermanager. getconnection (URL, "root"
, 111111"
);
- System. Out. println (getpk1 (CON ));
- System. Out. println (getpk2 (CON ));
- System. Out. println (getpk3 (CON ));
- }
- /**
- * Use getgeneratedkeys provided by JDBC 3.0. Recommended
- *
- * @ Param con
- * @ Return
- * @ Throws exception
- */
- Public
Static
Long
Getpk1 (connection con) throws
Exception {
- Statement stmt = con. createstatement ();
- Stmt.exe cuteupdate ("insert into t_type (name) values ('Can I get the auto increment field? ')"
,
- Statement. return_generated_keys );
- Int
Autoinckeyfromapi =-1
;
- Resultset rs = stmt. getgeneratedkeys ();
- If
(Rs. Next ()){
- Autoinckeyfromapi = Rs. getint (1
);
- }
- Return
Autoinckeyfromapi;
- }
- /**
- * Use your own special SQL.
- *
- * @ Param con
- * @ Return
- * @ Throws exception
- */
- Public
Static
Long
Getpk2 (connection con) throws
Exception {
- Statement stmt = con. createstatement ();
- Stmt.exe cuteupdate ("insert into t_type (name) values ('Can I get the auto increment field? ')"
,
- Statement. return_generated_keys );
- Int
Autoinckeyfromfunc =-1
;
- Resultset rs = stmt.exe cutequery (
"Select last_insert_id ()"
);
- If
(Rs. Next ()){
- Autoinckeyfromfunc = Rs. getint (1
);
- }
- Return
Autoinckeyfromfunc;
- }
- /**
- * Use updatable result sets.
- *
- * @ Param con
- * @ Return
- * @ Throws exception
- */
- Public
Static
Long
Getpk3 (connection con) throws
Exception {
- Statement stmt = con. createstatement (Java. SQL. resultset. type_forward_only,
- Java. SQL. resultset. concur_updatable );
- Resultset rs = stmt.exe cutequery ("select * From t_type"
);
- Rs. movetoinsertrow ();
- Rs. updatestring ("name"
, "Auto increment here? "
);
- Rs. insertrow ();
- Rs. Last ();
- Int
Autoinckeyfromrs = Rs. getint ("ID"
);
- Return
Autoinckeyfromrs;
- }
- }