- 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();
- }
- }
- }