2017-08-28 84 views
0

我想從數據庫中獲取一些值,但當單擊按鈕(void ButtonClick)時,我的應用程序崩潰。嘗試使用JDBC連接到數據庫時應用程序崩潰

這是我的代碼:

public void ButtonClick() throws Exception { 
    getConnection(); 
} 

public Connection getConnection() throws Exception { 
    try { 
     String username = "*******"; 
     String password = "*******"; 
     String url = "jdbc:mysql://http://**.***.***.***:3306/UserDB"; 
     Class.forName("com.mysql.jdbc.Driver").newInstance(); 

     Connection conn = (Connection) DriverManager.getConnection(url,username,password); 
     Statement statement = (Statement) conn.createStatement(); 
     String query = "SELECT * FROM TABLE 'UserDB'"; 
     ResultSet result = statement.executeQuery(query); 
     while (result.next()) { 
      String name = result.getString("Username"); 
      int id = result.getInt("ID"); 
      int points = result.getInt("Points"); 
      Toast.makeText(this, name + " " + id + " " + points, Toast.LENGTH_SHORT).show(); 
     } 
     return conn; 
    } catch (Exception e) { 
     Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show(); 
    } 
    return null; 
} 

(我不知道有什麼錯誤,因爲我的AVD不工作)

感謝您的幫助!

+2

什麼是錯誤? –

+2

請在此處添加代碼,而不是粘貼外部鏈接 –

+0

Alex Mamo,我不知道錯誤是什麼。我的AVD不工作。 –

回答

1

從Java 7開始,沒有必要使用forName()方法。您正在以這種方式創建一個新實例,同時您正嘗試使用DriverManager.getConnection()創建連接。

所以爲了解決這個問題,只需使用forName()方法刪除驅動程序的實例。

看到屏幕截圖,請注意,您無法從本機訪問Android的MySQL數據庫。其實你也許可以使用JDBC,但不推薦。請參閱post

希望它有幫助。

+1

我剛碰到這個問題。推薦的數據庫訪問方式顯然是位於應用程序和數據庫之間的RESTful服務。 – failedProgrammer

相關問題