You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中使用mysql-connector-j连接MySQL失败问题求助

解决Android中MySQL JDBC连接失败问题

问题根源分析

从错误栈可定位两个核心问题:

  1. NetworkOnMainThreadException:Android禁止在主线程执行网络/耗时操作,你的数据库连接与查询代码直接在SecondActivity.onCreate中调用,运行在主线程触发此异常。
  2. 数据库URL错误:getConnection方法中手动拼接的URL缺少目标数据库名freedb_dispenser_data,且未使用已定义的正确DB_URL。

修复步骤

1. 将数据库操作移至子线程

Kotlin中推荐用协程处理异步操作,避免主线程阻塞:

修改DispenserDatabaseHelper类:

import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
import java.sql.Statement
import java.util.Properties

class DispenserDatabaseHelper(context: Context?) {

    private val DB_URL = "jdbc:mysql://sql.freedb.tech:3306/freedb_dispenser_data"
    private var conn: Connection? = null
    private val username = "freedb_tobeitsolutions"
    private val password = "ayJ?DpgEMp57WBV"

    // 协程在IO线程执行查询
    suspend fun executeMySQLQuery() = withContext(Dispatchers.IO) {
        var stmt: Statement? = null
        var resultset: ResultSet? = null
        try {
            getConnection()
            conn?.let { connection ->
                stmt = connection.createStatement()
                resultset = stmt?.executeQuery("SHOW DATABASES;")
                while (resultset?.next() == true) {
                    println(resultset?.getString("Database"))
                }
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        } finally {
            // 释放资源
            resultset?.close()
            stmt?.close()
            conn?.close()
            conn = null
        }
    }

    private fun getConnection() {
        val connectionProps = Properties().apply {
            put("user", username)
            put("password", password)
            // MySQL 8.0+ 兼容配置
            put("useSSL", "false")
            put("serverTimezone", "UTC")
        }
        conn = DriverManager.getConnection(DB_URL, connectionProps)
    }
}

在Activity中调用协程:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        val dbHelper = DispenserDatabaseHelper(this)
        // 主线程启动协程,IO线程执行数据库操作
        CoroutineScope(Dispatchers.Main).launch {
            dbHelper.executeMySQLQuery()
        }
    }
}

2. 修复数据库URL

直接使用已定义的DB_URL,避免手动拼接错误,同时添加MySQL 8.0版本兼容参数,避免额外兼容性问题。

3. 必要配置与注意事项

  • 确保AndroidManifest.xml添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
  • Android平台不推荐直接用JDBC连接远程MySQL:此方式存在账号密码暴露风险、性能差,更合理的方案是搭建后端API,APP通过HTTP请求与API交互,由API操作数据库。

内容的提问来源于stack exchange,提问作者Jaspalsinh Gohil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:24:56