java - 无法连接到 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);
}
}
}
解决方案
检查堆栈跟踪后,我发现:
java.sql.SQLException: Unknown initial character set index '192' received from server.
所以我知道要搜索什么;我使用的是过时的 JDBC (3.x) 版本。导入版本 5.1.46 后,它现在可以工作了:)。
推荐阅读
- java - 覆盖依赖 JAR 中属性文件的键的值
- r - R:我可以将权重参数传递给 LightGBM 中的 params = list()
- java - 尝试在同一行上逐行打印多个二维数组
- java - Android 编码将 Json 值填充到 Spinner 获取所有选定的值到 TextView 或 Edit
- azure-service-fabric - 在 Actor 激活之前调用 Reliable Actor 时出现随机序列化异常
- spring - 我在运行以交互模式打开 docker 容器并执行一些命令的 bash 脚本时遇到问题
- javascript - 当我在 Nodejs+Express 中使用护照进行用户身份验证时发生了奇怪的事情
- java - 如何从 Java 中 owl 类的“等效于”部分中定义的类表达式中检索对象属性?
- javascript - 为什么我不能在更新其值时重新使用 SessionStorage?
- kubernetes - 如何检查 kubernate 集群中节点上的空间问题