问题遇到的现象和发生背景
安卓课程,在连接mysql数据库这一章,我的android studio连接本机mysql和同学的mysql都不行,一直“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.”
我的数据库版本为5.7
jar包也采用的5的版本
用代码块功能插入代码,请勿粘贴截图
模块配置文件如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
连接数据库代码
package com.example.test;
import android.util.Log;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connection {
private static final String TAG = "mysql11111";
java.sql.Connection conn=null;
public static void mymysql(){
final Thread thread =new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(100); // 每隔0.1秒尝试连接
} catch (InterruptedException e) {
Log.e(TAG, e.toString());
}
// 1.加载JDBC驱动
try {
Class.forName("com.mysql.jdbc.Driver");
Log.v(TAG, "加载JDBC驱动成功");
} catch (ClassNotFoundException e) {
Log.e(TAG, "加载JDBC驱动失败");
return;
}
// 2.设置好IP/端口/数据库名/用户名/密码等必要的连接信息
String ip = "192.168.43.52";
int port = 3306;
String dbName = "xsxx";
String url = "jdbc:mysql://" + ip + ":" + port
+ "/" + dbName+"?useUnicode=true&characterEncoding=utf-8&useSSL=false";
// 构建连接mysql的字符串
String user = "huhui";
String password = "123456";
// 3.连接JDBC
try {
java.sql.Connection conn = DriverManager.getConnection(url, user, password);
Log.d(TAG, "数据库连接成功");
conn.close();
return;
}
catch (SQLException e) {
Log.e(TAG, e.getMessage());
}
}
}
});
thread.start();
}
}
MainAcitivity代码
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Connection.mymysql();
}
}
运行结果及报错内容
报错为
“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.”
我的解答思路和尝试过的方法
已经参考了很多篇文章,也改了防火墙,换了另外一个模拟器都不行
我想要达到的结果
不要再报这个错了,我改这个已经改了快3天了,一点进展都没有。