1
我的源代码:在Android中使用JDBC连接远程MySQL如下
private static final String url = "jdbc:mysql://localhost/db_name";
private static final String user = "xxxx";
private static final String pswd = "xxxx";
private static final String sql = "SELECT * FROM table_name";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout linLayMain = new LinearLayout (this);
TextView txtViewMainTitle = new TextView (this);
TextView txtViewAdminName = new TextView (this);
TextView txtViewAdminPswd = new TextView (this);
txtViewMainTitle.setText ("Main Title : NONE");
txtViewAdminName.setText ("Admin Name : NONE");
txtViewAdminPswd.setText ("Admin Password : NONE");
try
{
Class.forName ("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection) DriverManager.getConnection (url, user, pswd);
txtViewMainTitle.setText ("Main Title : JDBC Connection Sccess");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery (sql);
while (rs.next())
{
txtViewAdminName.setText ("Admin Name : " + rs.getInt (1));
txtViewAdminPswd.setText ("Admin Pswd :" + rs.getString (2));
}
}
catch (Exception e)
{
Log.i ("Test GoSport", "Jdbc Error : " + e.getMessage());
e.printStackTrace();
}
linLayMain.addView (txtViewMainTitle);
linLayMain.addView (txtViewAdminName);
linLayMain.addView (txtViewAdminPswd);
txtViewMainTitle.setLayoutParams (new LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
txtViewAdminName.setLayoutParams (new LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
txtViewAdminPswd.setLayoutParams (new LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setContentView (linLayMain);
}
但是,它现在之前从未成功。当我在DDMS中看到Log.i时,它总是显示“JDBC连接错误”。
我的环境如下:
的Mac OS X 10.7.2, 的Eclipse的Java EE靛蓝, mysql的连接的Java-5.1.18-bin.jar, 模拟器4.0.3,API 15
我会引用我自己的回答。 http://stackoverflow.com/questions/9858099/using-jdbc-in-android – 2012-04-02 02:28:05