Android Java ODBC Connection

扶醉桌前 提交于 2019-12-24 10:25:48

问题


i am here with another problem about android... I am trying to connect to my mysql database with that code:

  public void testDB() {
    TextView tv = (TextView)this.findViewById(R.id.textView1);
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, user, pass);
        /* System.out.println("Database connection success"); */

        String result = "Database connection success\n";
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from users");
        ResultSetMetaData rsmd = rs.getMetaData();

        while(rs.next()) {
            result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
            result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
            result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n";
        }
        tv.setText(result);
    }
    catch(Exception e) {
        e.printStackTrace();
        tv.setText(e.toString());
    }   

}

In the AVD i get this error:

10-23 16:49:08.103: W/System.err(12939): java.sql.SQLException: Unable to connect to any hosts due to exception: android.os.NetworkOnMainThreadException

I think there's something wrong in the libs, is that true? But i tryied this on bluestack emulator, with android gingerbread i think and the connection work good... Does someone know how can i do?


回答1:


You're getting a NetworkOnMainThreadException. With Honeycomb and forward, you can't do any networking tasks on your main thread, which means you need to move your code off into a separate thread. I'd suggest an AsyncTask.




回答2:


The exception is very informative: you are doing network operations in the main thread which is not allowed. This article is a guide to background operations.




回答3:


This is because you're doing a network operation in the main thread, consider using an AsyncTask for network operations.

Example of AsyncTask implementation: http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/

Do your network operation in doInBackground.




回答4:


 java.sql.SQLException: Unable to connect to any hosts due to exception: android.os.NetworkOnMainThreadException

All network calls should be on separate threads instead on main thread. You need to use AsynchTask to make network calls.

Here is android tutorial on how to write asynchtask for this purpose.



来源:https://stackoverflow.com/questions/13033287/android-java-odbc-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!