当数据正确时,该方法有效,但是当我更改数据库中的密码时,此方法无限期地工作。 我想如果密码或用户不正确,应用程序停止并显示信息通知"或用户密码错误"。
要显示我计划使用AlertDialog的信息,我知道如何操作,只是我不知道如何将其与我的方法myMethod()
联系起来有什么想法吗?
public void myMethod()
{
Connection conn = null;
Statement stmt = null;
try {
StrictMode.ThreadPolicy ab = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(ab);
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url2, user2, pass2);
stmt = conn.createStatement();
String sql = "SELECT abc FROM this";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Double ba3 = rs.getDouble("abc");
list.add(ba3, rs.getDouble("abc"));
}
} catch (SQLException se)
{
se.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
} finally {
try {
if (stmt != null)
conn.close();
} catch (SQLException se)
{
}
try {
if (conn != null)
conn.close();
} catch (SQLException se)
{
se.printStackTrace();
}
}
}
EDIT1:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
});
答案 0 :(得分:1)
关于这段代码有很多令我担忧的事情。首先,如果您需要连接到远程数据库,则无法通过直接连接for a number of reasons。
安全性 - 如果用户具有直接访问权限,他们可以从您的数据库中获取任何内容。此外,他们将在您的数据库中有一个密码。因此,如果您使用的SQL服务器存在缺陷,那么他们可以利用它。此外,如果您的权限设置错误,可能会擦除您的数据库。
速度 - 如果用户经常使用大型查询,那么它可能会使您的系统快速而不必要地陷入困境。如果您通过网络界面,可以限制它。
辅助功能 - 几乎所有内容都支持Web查询。它需要特殊客户端直接访问SQL数据库。
除了移动数据的脆弱性之外,意味着可能难以保持套接字打开。我会考虑创建一个REST API来充当中间人。
其次:
StrictMode.ThreadPolicy ab = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(ab);
这里你基本上告诉Android忽略UI线程上的任何网络调用(或允许在UI线程上发生任何类型的密集工作)。同样,这是一个非常糟糕的主意,因为任何阻塞调用(例如数据库连接)都会导致UI出现大幅减速问题。根据您的需要,我建议您查看此问题 - How to get data to/from a socket in a thread?
但是,如果你必须以这种方式实现它,我会像这样构造它:
public void callerOnBackgroundThread() {
try {
myMethod();
} catch (Exception se) {
e.printStackTrace();
if (e instanceof ClassNotFoundException) {
// Error is related to your jdbc driver
} else if (e instanceof SQLException) {
// Error is related to your SQL connection
} else {
// Error is something else
}
}
}
private void myMethod() throws SQLException {
Connection conn = null;
Statement stmt = null;
SQLException exception = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url2, user2, pass2);
stmt = conn.createStatement();
String sql = "SELECT abc FROM this";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Double ba3 = rs.getDouble("abc");
list.add(ba3, rs.getDouble("abc"));
}
} catch (Exception e) {
exception = e;
} finally {
try {
if (stmt != null) conn.close();
} catch (SQLException se) {
exception = se;
}
}
if (exception != null) throw exception;
}
由于上述原因,在后台线程上调用callerOnBackgroundThread()
。
关于在显示对话框时使用instanceof
对异常进行排序,我的意思是这样的:
if (e instanceof ClassNotFoundException) {
// Error is related to your jdbc driver
} else if (e instanceof SQLException) {
// Error is related to your SQL connection
} else {
// Error is something else
}
因此,您可以根据错误类型适当使用AlertDialog。