如何在AsyncTask中快速重新连接到数据库?

时间:2019-06-23 12:31:01

标签: android kotlin android-asynctask

如果数据库连接丢失,则需要花费超过一分钟的时间才能重新连接。如何加快重新连接的速度?

class MssqlConnectorHelper (val view: View){

private var isConnected = false
lateinit var  mssqlConnector :MssqlConnector
var quitTask = false

inner class SyncData : AsyncTask<String, String, String>() {

    override fun onPreExecute() {
        mssqlConnector = MssqlConnector()
    }

    override fun doInBackground(vararg params: String?): String {
        var conn : Connection? = null

        while (!quitTask) {
            if (conn == null || !isConnected) {
                conn = mssqlConnector?.dbConn()
                isConnected = conn != null
            }

            if (conn != null && isConnected) {
                try {
                    val preparedStatement = conn.prepareStatement(params[0])
                    val cursor = preparedStatement.executeQuery()
                    if (cursor != null) {
                        while (cursor.next()) {
                            Log.i("SQL Result: ", cursor.getInt(1).toString() + " "
                                    + cursor.getInt(2).toString() + " "
                                    + cursor.getInt(3).toString() + " "
                                    + cursor.getInt(4).toString())
                        }
                    }
                }catch (e : Exception) {
                    isConnected = false
                    conn = null
                    Log.e("SQL Error", "Database Exception: "+e.message)
                }
            }else {
                Log.e("SQL Error", "Connection Error")
            }
            Thread.sleep(3000)
        }
        return "end background"
    }
}

fun getPickUpOrder() {
    SyncData().execute("SELECT * FROM pickUpOrder WHERE iStatus = 4")
}
}

我收到网络错误IOException:连接被拒绝,而ConnectException:连接被拒绝。之后,重新连接正常。

1 个答案:

答案 0 :(得分:0)

我自己找到了一个解决方案,这很简单,只需将超时添加到jtds URL:

SELECT * FROM history_by_month
WHERE month = '2014-05'
LIMIT 1;