在Android中使用JDBC连接远程MySQL

时间:2012-04-02 02:09:29

标签: android mysql jdbc

我的源代码如下:

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 Connection Error”。

我的环境如下:

Mac OS X 10.7.2, Eclipse Java EE Indigo, MySQL的连接的Java-5.1.18-bin.jar, 模拟器4.0.3,API 15

1 个答案:

答案 0 :(得分:1)

这不是一个真正的答案,但我记得当我第一次开始在Android编程时,我被告知不要直接连接到远程数据库,而是要经常通过一个接口(即JSP,PHP,.NET等)。 ..)。我不确定这个的确切原因(可能是安全性)但只是想我会投入2美分