2012年8月26日 星期日

jdbc 無法連接資料庫




public static final String MYSQL_URL = "jdbc:mysql://sql09.freemysql.net:3306/";
public static final String MYSQL_DBNAME = "xxxx";
public static final String MYSQL_USERNAME = "xxxxx";
public static final String MYSQL_PASSWORD = "xxxxxx";

public ArrayList bookList() throws Exception
{

ArrayList results = new ArrayList();

try
{
String script = "SELECT id, number, URL FROM position";
Log.d("Mystic","script = " + script);

// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");

// Setup the connection with the DB
connect = (Connection) DriverManager.getConnection(MYSQL_URL
+ MYSQL_DBNAME,MYSQL_USERNAME,MYSQL_PASSWORD);

Log.d("Mystic","connection is success");

}
catch(Exception e)
{
Log.e("Mystic","Exception");
e.printStackTrace();
throw e;
}
finally
{
Log.d("Mystic","Finally");
connect.close();
}
return results;
}





一直無法連線成功,印出例外訊息:android.os.networkonmainthreadexception

幾經波折,後來發現是下述問題!


http://flipper.pixnet.net/blog/post/36169513-android-3.0-%E7%99%BC%E7%94%9F-android.os.networkonmainthreadexception