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")
}
}
}
Asked
Active
Viewed 316 times
0
-
Workbench is a program, you cannot connect to it, but to a mysql server – nbk Jan 28 '20 at 16:14
1 Answers
0
Are you running this app in an emulator or in a real device?
check this line:
val url = "jdbc:mysql://localhost:3306/Boxing"
I guess your MySQL server is running in the same machine you are developing, when the app is running in an emulator you gonna have an IP like 10.0.X.X so you cannot see this localhost and when is running in a real devices IP maybe is something like 192.168.X.X, try to replace localhost for an IP (not 127.0.0.1) try with IP of your developing machine

Azhagthott
- 492
- 5
- 13
-
This is the exception am getting now: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. – Thabo Jan 29 '20 at 11:28
-
In that case I recommend you see this answer: https://stackoverflow.com/questions/2983248/com-mysql-jdbc-exceptions-jdbc4-communicationsexception-communications-link-fai – Azhagthott Jan 30 '20 at 09:58