package com.example.test
import android.os.Bundlemportandroid.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import java.sql.DriverManager
import com.mysql.jdbc.Driver
import java.sql.PreparedStatement
import java.sql.Connection
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle ? ) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnDB.setOnClickListener {
DBConn.DBString()
}
setSupportActionBar(toolbar)
fab.setOnClickListener {
view - >
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null)
.show()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when(item.itemId) {
R.id.action_settings - > true
else - > super.onOptionsItemSelected(item)
}
}
fun DBCon() {
try {
val url = "jdbc:mysql://localhost:3306/Boxing"
var conn: Connection = DriverManager.getConnection(url, "root", "Guru9")
//conn.close();
if (conn != null) {
println("Connected successfully to Database")
}
} catch (e: Exception) {
println(" Not connected to Database")
}
}
}
最佳答案
您是在模拟器中还是在真实设备中运行此应用程序?
检查这一行:
val url = "jdbc:mysql://localhost:3306/Boxing"
我猜你的 MySQL 服务器运行在你正在开发的同一台机器上,当应用程序在模拟器中运行时,你将拥有一个像 10.0.X.X 这样的 IP,所以你看不到这个本地主机,也看不到它何时在真实设备 IP 中运行也许类似于 192.168.X.X,尝试将 localhost 替换为 IP(不是 127.0.0.1),尝试使用开发计算机的 IP
关于java - Android Studio MainActivity 类无法连接到本地 Mysql Workbench,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59952286/