版本描述
- Android Studio:3.5.2
- MySQL:5.5.58 MySQL Community Server (GPL)
- jar包:mysql-connector-java-5.1.22
参考链接
Android Studio 通过JDBC驱动获取Mysql数据库数据
步骤
- 导入jar包
Project→app→libs,复制jar包,粘贴至libs下,右击选择Add As Library
; - 复制代码并粘贴;
- 修改成自己IP地址及数据库信息,成功!
JdbcUtil.java
package com.example.mysqlconnect.utils;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JdbcUtil {
/*
* jdbc:mysql://我的ip地址/我要访问的数据库","用户名","密码
* ip地址获取:在命令行输入ipconfig后查看
* 用户名:MySQL中的用户,比如root,一定要先授予权限
*/
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://自己电脑ip地址:3306/数据库名";
private static final String USER = "root";
private static final String PASSWORD = "123456";
public static boolean connMysql() {
Connection conn = null;
PreparedStatement st = null;
try {
Class.forName(DRIVER).newInstance();
} catch (Exception e) {
e.printStackTrace();
return false;
}
try {
conn = DriverManager.getConnection(URL, USER, PASSWORD);
Log.i("Mysql", "Connect successfully!");
//MySQL查询语句
String sql = "select * from 数据库表名";
st = conn.prepareStatement(sql);
ResultSet rs = st.executeQuery();
while (rs.next()) { //读取表中的每一列
Log.i("自己随便定义吧", rs.getString("表内某字段名")); //读取某某列并输出显示
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
MainActivity.java
package com.example.mysqlconnect;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.mysqlconnect.utils.JdbcUtil;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//访问MySQL需开新线程
new Thread(new Runnable() {
@Override
public void run() {
JdbcUtil.connMysql();
}
}).start();
}
}
备注
我也尝试过网上其他参考代码,比如:
均未连接成功,后找到上面的版本,一试竟然可以。接下来自己新建工程,手敲代码一遍,结果竟又失败……甚是费解……
来源:CSDN
作者:jhj101510
链接:https://blog.csdn.net/weixin_41108819/article/details/104170577