赞
踩
最近在做安卓课设时有连接数据库的需求,但程序一直报错,查了很多方法,最后总算成功。
在此记录并分享我的方法,希望能帮助到大家。
Android Stidio版本:3.5.2
MySQL版本:5.7
jar包版本:mysql-connerctor-java-5.1.48
(官网:MySQL :: Download MySQL Connector/J (Archived Versions))
在数据库中建好测试表:
数据库名:test
表名:users
这里需要注意数据库用户的权限,如果权限不够,后面在连接时可能报message from server: “Host is not allowed to connect to this MySQL server“错误。
打开数据库
输入密码后依次输入:
use mysql;
update user set host = '%' where user = 'root';(root就是你的数据库用户名)
select host, user from user;
FLUSH PRIVILEGES;
成功后如图
概览如图:
点击Android切换Project视图
依次点击app、src、main
右键main创建文件夹libs
将下好的jar包复制或者拖入libs中
右键jar包点击Add As Library...(这里因为我导入过了,所以用其他jar包演示了一下)
再切回Android视图,找到Grade Scripts文件下的build.gradle(app)
查看是否有如下代码
如果曾导入过其他版本jar包,记得删除对应语句,只留你需要的版本!否则报错
在java文件夹下创建
- package com.example.mysql;
-
- import android.util.Log;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.util.HashMap;
-
- //数据库工具类:连接数据库用、获取数据库数据用
- public class DBUtils {
- private static String driver = "com.mysql.jdbc.Driver";// MySql驱动
- private static String user = "root";// 用户名
- private static String password = "sise";// 密码
-
- private static Connection getConn(String dbname){
- Connection connection = null;
- try{
- Class.forName(driver);// 动态加载类
- String ip = "172.17.9.108"; // 写成本机地址,不能写成localhost
- // 尝试建立到给定数据库URL的连接
- connection = DriverManager.getConnection("jdbc:mysql://" + ip
- + ":3306/" + dbname, user, password);
- }catch (Exception e){
- Log.i("DBUtils","Exception");
- e.printStackTrace();
- }
- return connection;
- }
-
- public static HashMap<String, Object> getAllInfo(){
- HashMap<String, Object> map = new HashMap<>();
- // 根据数据库名称,建立连接
- Connection connection = getConn("test");
- try {
- String sql = "select * from users;";
- if (connection != null){// connection不为null表示与数据库建立了连接
- PreparedStatement ps = connection.prepareStatement(sql);
- if (ps != null){
- // 执行sql查询语句并返回结果集
- ResultSet rs = ps.executeQuery();
- if (rs != null){
-
- while (rs.next()){
- // String rsm = rs.getMetaData().getColumnName(1);
- // Log.i("DBUtils","记录rsm :" + rsm);
- // 通过字段检索
- String id = rs.getString("nums");
- String name = rs.getString("name");
- String passw = rs.getString("passw");
- int age = rs.getInt("age");
- String adress = rs.getString("adress");
- Log.i("DBUtils","记录全 :" + id + name + passw + age + adress);
- map.put(id,","+name+","+passw+","+age+","+adress);
- }
- connection.close();
- ps.close();
- return map;
- }else {
- Log.i("DBUtils","结果为空");
- return null; }
- }else {
- Log.i("DBUtils","sql");
- return null; }
- }else {
- Log.i("DBUtils","连接失败");
- return null; }
- }catch (Exception e){
- e.printStackTrace();
- Log.e("DBUtils","异常:" + e.getMessage());
- return null;
- }
-
- }
- public static HashMap<String, Object> getInfoByName(String names){
- HashMap<String, Object> map = new HashMap<>();
- // 根据数据库名称,建立连接
- Connection connection = getConn("test");
- try {
- // mysql简单的查询语句。这里是根据users表的name字段来查询某条记录
- String sql = "select * from users where name = ? ;";
- if (connection != null){ // connection不为null表示与数据库建立了连接
- PreparedStatement ps = connection.prepareStatement(sql);
- if (ps != null){
- // 设置上面的sql语句中的?的值为name
- // ps.setString(1, names);
- ps.setNString(1,names);
- // 执行sql查询语句并返回结果集
- ResultSet rs = ps.executeQuery();
- // rs.beforeFirst();
- if (rs != null && rs.next()){
- Log.i("DBUtils","记录 count :" + rs.getMetaData().getColumnCount());
- rs.previous();
- while (rs.next()){
- // 通过字段检索
- String id = rs.getString("nums");
- String name = rs.getString("name");
- String passw = rs.getString("passw");
- int age = rs.getInt("age");
- String adress = rs.getString("adress");
- Log.i("DBUtils","记录全 :" + id + name + passw + age + adress);
- map.put(id,","+name+","+passw+","+age+","+adress);
- }
- connection.close();
- ps.close();
- return map;
- }else {
- Log.i("DBUtils","结果为空");
- return null; }
- }else {
- Log.i("DBUtils","sql");
- return null; }
- }else {
- Log.i("DBUtils","连接失败");
- return null; }
- }catch (Exception e){
- e.printStackTrace();
- Log.e("DBUtils","异常:" + e.getMessage());
- return null;
- }
-
- }
- }

查看注释要求,用户密码就是数据库的用户密码
主机地址填本机的地址,可在命令行中用查询。
- package com.example.mysql;
- import androidx.appcompat.app.AppCompatActivity;
-
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import java.util.HashMap;
-
- public class MainActivity extends AppCompatActivity {
-
- private TextView tv_data;
- private Button btn_get_data; //声明组件
- private Button btn_get_all; //声明组件
-
- private final Handler handler = new Handler(new Handler.Callback() {
- @Override
- public boolean 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;
- }
- return true;
- }
- });
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- // 控件的初始化
- btn_get_data = findViewById(R.id.btn_get_data);
- btn_get_all = findViewById(R.id.btn_get_all);
- 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 = DBUtils.getInfoByName("张三");
- 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();
-
- }
- });
-
- // 按钮点击事件
- btn_get_all.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 创建一个线程来连接数据库并获取数据库中对应表的数据
- new Thread(new Runnable() {
- @Override
- public void run() {
- // 调用数据库工具类DBUtils的getInfoByName方法获取数据库表中数据
- HashMap<String, Object> map = DBUtils.getAllInfo();
- 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();
-
- }
- });
- }
- }

- <?xml version="1.0" encoding="utf-8"?>
- <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=".MainActivity"
- 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"/>
-
- <Button
- android:id="@+id/btn_get_all"
- 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:layout_width="match_parent"
- android:layout_height="wrap_content"/>
-
-
-
-
- </LinearLayout>

在其中加入
<uses-permission android:name="android.permission.INTERNET"/>
获取网络权限
至此,所有配置完成,运行。
成功!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。