package temp;
/**
*
* @author jadeluo
*/
import java.sql.connection;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.resultsetmetadata;
import java.sql.sqlexception;
import java.sql.statement;
import org.postgresql.ds.pgsimpledatasource;
public class postgresqldatasource {
/**
create table lfchat.auto_id_test ( id serial primary key , username
character(8) not null, password character(6) not null, email character(6) not null ) with ( oids=false );
alter table lfchat.auto_id_test owner to sdbadmin;
*
* @param args
* @throws sqlexception
*/
public static void main(string[] args) throws sqlexception {
pgsimpledatasource pgsimpledatasource = new pgsimpledatasource();
pgsimpledatasource.setservername("ip:11780");
// pgsimpledatasource.setservername("192.168.1.8");//default 5432
// pgsimpledatasource.setdatabasename("postgres");
// pgsimpledatasource.setdatabasename("foo");
pgsimpledatasource.setdatabasename("foo");
// pgsimpledatasource.setuser("lv");
// pgsimpledatasource.setpassword("lv");
pgsimpledatasource.setuser("sdbadmin");
pgsimpledatasource.setpassword("sa");
connection conn = pgsimpledatasource.getconnection();
statement state = conn.createstatement();
string sql = "insert into lfchat.auto_id_test (username,password,email) values (?,?,?);";
preparedstatement pstmt = (preparedstatement) conn.preparestatement(sql, statement.return_generated_keys);//传入参数:statement.return_generated_keys
pstmt.setstring(1, "username");
pstmt.setstring(2, "pwd");
pstmt.setstring(3, "email");
pstmt.executeupdate();//执行sql int autoinckey = -1;
resultset rs = pstmt.getgeneratedkeys(); //获取结果
if (rs.next()) {
int autoinckey = rs.getint(1);//取得id
system.out.println("autoinckey=>>>>>>>>>>" + autoinckey);
} else {
// throw an exception from here
}
}
static void showresultset(resultset resultset) throws sqlexception {
resultsetmetadata resultsetmetadata = resultset.getmetadata();
int num = resultsetmetadata.getcolumncount();
while (resultset.next()) {
for (int i = 1; i <= num; i++) {
system.out.print(resultsetmetadata.getcatalogname(i) + " "
+ resultset.getstring(i));
}
system.out.println();
}