1.引入jar包。复制jar包到libs目录下,再右键jar包Add as library.
1.mysql-connector-java-5.1.30-bin.jar下载
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ConnectActivity"
android:orientation="vertical">
<Button
android:id="@+id/btn_get_data"
android:layout_margin="2dp"
android:textSize="16sp"
android:text="获取数据测试"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_data"
android:padding="10dp"
android:textSize="16sp"
android:gravity="center"
android:text="imxiaoqi"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
LinearLayout>
3.ConnUtil工具类
package com.example.login.ToastUtil;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
public class ConnUtil {
private static String driver = "com.mysql.jdbc.Driver";// MySql驱动
// private static String url = "jdbc:mysql://localhost:3306/map_designer_test_db";
private static String user = "root";// 用户名
private static String password = "root";// 密码
private static Connection getConn(String dbName){
Connection connection = null;
try{
Class.forName(driver);// 动态加载类
String ip = "192.168.0.101";// 写成本机地址,不能写成localhost,同时手机和电脑连接的网络必须是同一个
// 尝试建立到给定数据库URL的连接
connection = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/" + dbName,
user, password);
}catch (Exception e){
e.printStackTrace();
}
return connection;
}
public static HashMap<String, Object> getInfoByName(String name){
HashMap<String, Object> map = new HashMap<>();
// 根据数据库名称,建立连接
Connection connection = getConn("stubase");
try {
// mysql简单的查询语句。这里是根据MD_CHARGER表的NAME字段来查询某条记录
String sql = "select * from test_one where name = ?";
// String sql = "select * from MD_CHARGER";
if (connection != null){
// connection不为null表示与数据库建立了连接
PreparedStatement ps = connection.prepareStatement(sql);
if (ps != null){
// 设置上面的sql语句中的?的值为name
ps.setString(1, name);
// 执行sql查询语句并返回结果集
ResultSet rs = ps.executeQuery();
if (rs != null){
int count = rs.getMetaData().getColumnCount();
Log.e("DBUtils","列总数:" + count);
while (rs.next()){
// 注意:下标是从1开始的
for (int i = 1;i <= count;i++){
String field = rs.getMetaData().getColumnName(i);
map.put(field, rs.getString(field));
}
}
connection.close();
ps.close();
return map;
}else {
return null;
}
}else {
return null;
}
}else {
return null;
}
}catch (Exception e){
e.printStackTrace();
Log.e("DBUtils","异常:" + e.getMessage());
return null;
}
}
}
3.Activity.java中的代码。
package com.example.login;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
import android.widget.EditText;
import android.view.View;
import android.util.Log;
import android.widget.Toast;
import java.util.HashMap;
import com.example.login.ToastUtil.ConnUtil;
public class ConnectActivity extends AppCompatActivity {
private Button btn_get_data;
private TextView tv_data;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0x11:
String s = (String) msg.obj;
tv_data.setText(s);
break;
case 0x12:
String ss = (String) msg.obj;
tv_data.setText(ss);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
// 控件的初始化
btn_get_data = findViewById(R.id.btn_get_data);
tv_data = findViewById(R.id.tv_data);
setListener();
}
/**
* 设置监听
*/
private void setListener() {
// 按钮点击事件
btn_get_data.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 创建一个线程来连接数据库并获取数据库中对应表的数据
new Thread(new Runnable() {
@Override
public void run() {
// 调用数据库工具类DBUtils的getInfoByName方法获取数据库表中数据
HashMap<String, Object> map = ConnUtil.getInfoByName("tom");
Message message = handler.obtainMessage();
if(map != null){
String s = "";
for (String key : map.keySet()){
s += key + ":" + map.get(key) + "\n";
}
message.what = 0x12;
message.obj = s;
}else {
message.what = 0x11;
message.obj = "查询结果为空";
}
// 发消息通知主线程更新UI
handler.sendMessage(message);
}
}).start();
}
});
}
}
4.数据库
自己随便建一个~~
点击连接测试按钮成功运行!