目的:測試Android模擬器連接外部SQL server

環境:PostgresSQL 9.0 + JDBC 4

副程式:
public static void BasicJDBCDemo()
{
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
}catch (ClassNotFoundException cnfe) {
            System.err.println("Couldn't find driver class:");
            System.out.println("Couldn't find driver class:");
            cnfe.printStackTrace();
        }
try{
conn = DriverManager.getConnection("jdbc:postgresql://10.0.2.2:5432/users", 
"postgres", "tmdwbd");
}catch (SQLException se) {
    System.out.println("Couldn't connect: print out a stack trace and exit.");
     se.printStackTrace();
    System.exit(1);
  }
       
if(conn != null)
System.out.println("Successfully connected to Postgres Database");
  else
    System.out.println("We should never get here.");

   String query = "SELECT * FROM user123";
   try
   {
   Statement st = conn.createStatement();
   ResultSet rs = st.executeQuery(query);
   
   while (rs.next())
   {
   String name = rs.getString(1);
   System.out.println(name);
   }
   }catch (SQLException ex)
   {
   System.err.println(ex.getMessage());
   }
}

 

06-27 18:18 updated ip設定及連線問題

副程式中設定的ip 10.0.2.2是指模擬器上對外連至SQL server,如是在開發板上運作則須更動IP,並開放SQL對外連線權限pg_hba.conf。

文章標籤
全站熱搜
創作者介紹
創作者 風風風 的頭像
風風風

風風風的部落格

風風風 發表在 痞客邦 留言(0) 人氣(831)