首页 > 解决方案 > 无法连接到 SQL 数据库(Java、Android Studio)

问题描述

我已经导入了JDBC库,设置为可编译,并赋予App访问Internet的权限。当按下屏幕上的按钮时,它应该连接到数据库并为我提供要在列表中实现的值。

当我按下按钮时,我可以看到它给了我“连接到数据库”文本,但大约半秒后它显示最后一个 catch 块中定义的“异常”。

我在 onPostExecute 中注释掉了这三行代码,因为当我保留它们时,应用程序就会崩溃。

public void retrieveData(View view) {
    GetData retrieveData = new GetData();
    retrieveData.execute();


}

private class GetData extends AsyncTask<String,String,String> {
    String msg = "";

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

    static final String DB_URL = "jdbc:mysql://" + DbStrings.DATABASE_URL + "/" + DbStrings.DATABASE_NAME;

    @Override
    protected void onPreExecute() {
        progress.setText("Connecting to database");
    }

    @Override
    protected String doInBackground(String... strings) {

        Connection conn = null;
        Statement stmt = null;

        try {
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, DbStrings.USERNAME, DbStrings.PASSWORD);

            stmt = conn.createStatement();
            String sql = "SELECT * FROM video"; //
            ResultSet rs = stmt.executeQuery(sql);

            while(rs.next()) {
                String name = rs.getString("title");

                buildNames += name + " ### ";

            }

            msg = "Process complete.";

            rs.close();
            conn.close();
            stmt.close();


        } catch(SQLException connError) {
            msg = "An exception was thrown for JDBC.";
            connError.printStackTrace();
        } catch (ClassNotFoundException e) {
            msg = "A Class not found exception was thrown.";
            e.printStackTrace();
        } catch (java.sql.SQLException e) {
            msg = "Exception";
            e.printStackTrace();
        } finally {

            try{
                if(stmt != null) {
                    stmt.close();
                }
            } catch (java.sql.SQLException e) {
                e.printStackTrace();
            }
            try{
                if(conn != null) {
                    conn.close();
                }
            } catch (java.sql.SQLException e) {
                e.printStackTrace();
            }

        }


        return null;
    }

    @Override
    protected void onPostExecute(String msg) {

        progress.setText(this.msg);

        //names = buildNames.substring(0,buildNames.length()-5).split(" ### ");
        //itemAdapter = new ItemAdapter(thisContext, buildNames.substring(0,buildNames.length()-5).split(" ### ")); //crashes
        //namesList.setAdapter(itemAdapter);

    }


}

}

标签: javaandroidsqlandroid-studiojdbc

解决方案


检查堆栈跟踪后,我发现:

java.sql.SQLException: Unknown initial character set index '192' received from server.

所以我知道要搜索什么;我使用的是过时的 JDBC (3.x) 版本。导入版本 5.1.46 后,它现在可以工作了:)。


推荐阅读