当前位置:   article > 正文

Android studio连接MySQL数据库,在fragment中使用listview显示数据(Navicat操作数据库)(夜神模拟器运行)_andriod studio fragment访问数据库

andriod studio fragment访问数据库

本文连接MySQL数据库,使用到的为包mysql-connector-java-5.1.47-bin.jar。MySQL数据库版本为5.7.38.

在开始连接前请务必确保MySQL版本不是8.0及以上的版本!!否则会一直报错无法创建连接。

请不要嫌重装麻烦,我因为不舍得重装,搞了两三天还是重装了才成功。


环境配置:

一、资源包下载网址:MySQL :: 下载 MySQL Connector/J (存档版本)

二、MySQL8.0卸载:第一步:关闭当前MySQL服务,任务管理器——服务——打开服务,找到MySQL服务关闭

第二步:左下角电脑——设置——系统——存储——应用,卸载掉所有当前MySQL关键字的程序

三、MySQL5.7版本安装教程:http://t.csdn.cn/hW25g


开始连接:

一、准备工作

        1.选择下载好的jar文件(带bin和不带bin的对我们连接MySQL没有区别,我们连接数据库主要是使用到包里面封装好的Driver类,用于加载驱动)

         2.粘贴到目录下的libs中,点击左上角选择project,找到libs目录,粘贴

         3.右击jar包,点击Add as library,弹出来的窗口直接确定即可。

         ( 一开始我出现了右击却没有显示Add as library的情况,然后放那里不管,忙完回来再点击又显示出来了,如果有出现这个情况的,具体原因还未知)

        然后回到android编辑界面,在biuld.gradle中查看是否成功,注意有两个biuld.gradle,在第二个中查看

         4.在AndroidMainfest.xml添加连接网络权限(只是本机连接展示的话不用添加也行)。语句为:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

         至此准备工作结束,开始连接。


二、创建文件

       1.创建java类

       (1).创建数据库连接池DBUtils类。在java包下创建一个连接类DBUtils,用于调用里面的连接函数

 DBUtils代码:

                      (  具体解释在注释中已经写明了,如果想深入理解,请耐心观看。如果急需能用即可,直接粘贴即可。如果报错,请去掉try语句,再运行查看是哪一句出错)

  1. package com.example.an94;
  2. import android.util.Log;
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. public class DBUtils {
  11. private static final String TAG="DBUtils";// 用于日志打印
  12. private static Connection conn=null;// 定义连接变量conn
  13. //数据库连接函数
  14. public static Connection getConnection(String dbname) {//定义connection类函数,需要返回一个connection对象,即在上面定义的conn
  15. String ip = "192.168.56.1";//ip地址,win+R,输入cmd打开控制台,输入ipconfig /all查看本机ipv4地址,最上面那个
  16. int port = 3306;//MySQL安装时的默认端口号,无需更改
  17. String user = "root";//打开Navicat,点击用户,如果显示root@localhost,请修改为root@%或新加一个root@%,%表示任意,任意ip地址都可以连接
  18. String password = "6433868482";//密码
  19. String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbname + "?useUnicode=true&characterEncoding=UTF-8";
  20. // "?useUnicode=true&characterEncoding=UTF-8"添加中文信息时不会乱码
  21. // 注册JDBC驱动的固定语句
  22. try {
  23. Class.forName("com.mysql.jdbc.Driver");//这是一个目录,你可以找到这个目录点进去就懂了
  24. Log.d(TAG, "加载JDBC驱动成功");
  25. } catch (ClassNotFoundException e) {
  26. Log.d(TAG, "加载JDBC驱动失败");
  27. }
  28. // 创建与mysql的连接对象conn,当然你也可以直接把上面定义的那些变量url的值直接写进去,就不用上面写一堆定义
  29. try {
  30. conn = DriverManager.getConnection(url, user, password);
  31. Log.d(TAG, "数据库连接成功");
  32. } catch (SQLException e) {
  33. Log.d(TAG, "数据库连接失败");
  34. }
  35. return conn;//connection类,返回一个connection连接对象
  36. }
  37. //数据库查询函数
  38. //前面加载完JDBC驱动了,现在开始使用JDBC,
  39. //↓ List里只能放Map类型的对象,而这个Map类型的对象又只能放以String类型为键,以Object类型为值的键值对
  40. //就是说你定义了一个表list,然后表里得每一行数据都是HashMap,然后HashMap<标识符,你要保存的数据>
  41. public static List<HashMap<String,Object>> getinfo(String dbname) throws SQLException {
  42. // 定义List<HashMap<String,Object>>类型的数据并实例化
  43. List<HashMap<String,Object>> list=new ArrayList<HashMap<String, Object>>();
  44. // 调用连接函数,传入数据库名的形参,获得conn对象,因为getConnection的返回类型就是Connection及conn
  45. //1.调用连接,不然你连不上数据库
  46. Connection conn=getConnection(dbname);
  47. // 通过connection对象conn获取statement对象sta,createStatement():创建基本的statement对象
  48. //2.你要用statement去执行sql语句,但你得连上数据库才能执行,所以要用连接对象创建statement对象。
  49. Statement sta=conn.createStatement();
  50. // 定义sql语句
  51. String sql="select * from user ";
  52. // 调用Statement对象执行sql语句,返回结果为结果集,就是一个带指针的表格,通过操作指针来进行数据操作
  53. //3.使用statement的三种方法中的executeQuery()方法,返回的就是一个结果集ResultSet对象,所以你要用ResultSet变量接收
  54. ResultSet result=sta.executeQuery(sql);
  55. // 判断一下是否为空
  56. if (result==null){
  57. return null;
  58. }
  59. // 当这个结果集(就这个表)还有下一行时进入函数。这个表是有指针的,百度搜索ResultSet接口中的方法,
  60. while (result.next()) {
  61. // 每次循环都会新实例化一个HashMap对象,用于将遍历到的数据填进去
  62. HashMap<String,Object> map=new HashMap<>();
  63. // 往map中填数据,map的数据类型相当于键值对
  64. map.put("ID",result.getString("ID"));//ResultSet中的getString方法,获取指定字段的String类型值
  65. map.put("message",result.getString("message"));
  66. // 每次循环完就添加到list中
  67. list.add(map);
  68. }
  69. // 把list返回出去,否则拿不到这个list
  70. return list;
  71. }
  72. }

        (2).我定义的 fragment(下文中的fragment_already),这个fragment对应的java类already(类名自定义)。listview放在fragment_already中。

already代码:

  1. package com.example.an94;
  2. import android.annotation.SuppressLint;
  3. import android.os.Bundle;
  4. import androidx.annotation.NonNull;
  5. import androidx.fragment.app.Fragment;
  6. import android.os.Handler;
  7. import android.os.Message;
  8. import android.util.Log;
  9. import android.view.LayoutInflater;
  10. import android.view.View;
  11. import android.view.ViewGroup;
  12. import android.widget.Button;
  13. import android.widget.ListView;
  14. import android.widget.SimpleAdapter;
  15. import java.sql.SQLException;
  16. import java.util.ArrayList;
  17. import java.util.HashMap;
  18. import java.util.List;
  19. import static com.example.an94.DBUtils.getConnection;
  20. import static com.example.an94.DBUtils.getinfo;
  21. public class already extends Fragment {
  22. private static final String TAG="DBUtils";
  23. @Override
  24. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  25. Bundle savedInstanceState) {
  26. final View view = inflater.inflate(R.layout.fragment_already,null);//找到你的fragment
  27. //找到你的fragment中的控件,之所以要view.findViewById(),因为是在fragment里找,而你是通过的view找到fragment
  28. Button query=view.findViewById(R.id.query);
  29. //*************查找按钮功能****************************************************************************
  30. query.setOnClickListener(new View.OnClickListener() {
  31. @Override
  32. public void onClick(View v) {
  33. // 在点击事件里写内容
  34. //-----------------------------------------
  35. // Handler部分
  36. //Android studio中,需要新开一个子线程处理数据库,主线程只有一个不能同时执行
  37. // 由子线程传出的数据在这里处理
  38. @SuppressLint("HandlerLeak")
  39. // 先new一个Handler对象
  40. final Handler handler =new Handler(){
  41. @Override
  42. public void handleMessage(@NonNull Message msg) {
  43. super.handleMessage(msg);
  44. // 获取listview组件,因为我们要在这个部分更新UI组件
  45. final ListView listView=view.findViewById(R.id.list_already);
  46. // if的判断条件是区分msg是哪一条,即msg的ID,是下面连接数据库时我们自己定义的
  47. if(msg.what==1){
  48. // 获取发送过来的msg.obj对象,因为我传的是List<HashMap<String, Object>>类型的obj,所以这边同样用List<HashMap<String, Object>> list去接收,要强转
  49. List<HashMap<String,Object>> list= (List<HashMap<String, Object>>) msg.obj;
  50. // 定义SimpleAdapter,参数分别为当前上下文,刚拿到的数据集合list,子项布局文件,数据集合中的字段信息,要添加到的子布局文件中的控件ID
  51. SimpleAdapter simpleAdapter=new SimpleAdapter(getContext(),list,R.layout.already_list_item,new String[]{"ID","message"},new int[]{R.id.序号,R.id.介绍});
  52. // 为listview设置适配器
  53. listView.setAdapter(simpleAdapter);
  54. }
  55. }
  56. };
  57. // Handler部分
  58. //----------------------------------------------------------------------
  59. //--------------------------------------------------------------
  60. // 连接数据库并进行相应操作的线程
  61. // 第二、第三部分
  62. // new 一个线程,接下来是数据库操作部分,要在子线程中执行
  63. Thread thread=new Thread(new Runnable() {
  64. // 定义一个子线程中的全局变量List<HashMap<String,Object>> list1,用于接收从DBUtils中返回的list
  65. List<HashMap<String,Object>> list1=new ArrayList<HashMap<String, Object>>();
  66. @Override
  67. public void run() {
  68. // 与数据库建立连接
  69. getConnection("android");
  70. try {
  71. // 以下这些要用try/catch包含
  72. // 调用数据库工具类的getinfo函数,用list1接收返回的list数据
  73. list1=getinfo("android");
  74. // 打印日志,测试用
  75. Log.d(TAG, list1.toString());
  76. } catch (SQLException e) {
  77. e.printStackTrace();
  78. }
  79. // 将从数据库拿到的list1对象传给message再由handler传出,再在handler中处理,可进行更新UI
  80. // 新建一个message对象,尽量不要直接new,而是用这种方法,因为有内存的问题存在
  81. Message message=Message.obtain();
  82. // 设置message的辨认码,这里设为1
  83. message.what=1;
  84. // 把刚才接收到的list1赋给message.obj对象
  85. message.obj=list1;
  86. // 通过handler将携带数据的message传出去,传到handler中
  87. handler.sendMessage(message);
  88. }
  89. });
  90. // 上面线程定义完了,现在启动线程
  91. thread.start();
  92. // 第二、第三部分
  93. //------------------------------------------------
  94. }
  95. });
  96. return view;
  97. }
  98. }

        (3)最后是 MainActivity.Java

  1. package com.example.an94;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import androidx.fragment.app.FragmentManager;
  4. import androidx.fragment.app.FragmentTransaction;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.FrameLayout;
  8. import android.widget.TextView;
  9. public class MainActivity extends AppCompatActivity implements View.OnClickListener{
  10. private TextView txt_dibufour;
  11. private already fg4;
  12. private FragmentManager fManager; //声明FragmentManager类变量
  13. @Override
  14. protected void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. // requestWindowFeature(Window.FEATURE_NO_TITLE);//将系统自带的标题栏隐藏掉
  17. //这一句一定要在加载activity之前调用
  18. setContentView(R.layout.activity_main);
  19. fManager = getSupportFragmentManager(); //实例化fragmentManager变量
  20. bindViews();
  21. }
  22. private void bindViews() {
  23. txt_dibufour=(TextView) findViewById((R.id.txt_dibu4));
  24. txt_dibufour.setOnClickListener(this);
  25. }
  26. private void setSelected(){//重置所有文本选中状态
  27. txt_dibufour.setSelected(false);
  28. }
  29. private void hideAllFragment(FragmentTransaction fragmentTransaction){
  30. if(fg4 != null)fragmentTransaction.hide(fg4);
  31. }
  32. @Override
  33. public void onClick(View v){
  34. FragmentTransaction fTransaction = fManager.beginTransaction();//通过begin开启事务
  35. hideAllFragment(fTransaction);
  36. switch (v.getId()){
  37. case R.id.txt_dibu4:
  38. setSelected();
  39. txt_dibufour.setSelected(true);
  40. if(fg4==null){
  41. fg4=new already();
  42. fTransaction.add(R.id.zj_content,fg4);
  43. }else{
  44. fTransaction.show(fg4);
  45. }
  46. break;
  47. }
  48. fTransaction.commit();//提交事务
  49. }
  50. }


         2.创建布局文件

        (1)MainActivity.xml

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. tools:context=".MainActivity">
  6. <RelativeLayout
  7. android:id="@+id/dingbu_bar"
  8. android:layout_width="match_parent"
  9. android:layout_height="48dp">
  10. <TextView
  11. android:id="@+id/txt_topbar"
  12. android:layout_width="match_parent"
  13. android:layout_height="match_parent"
  14. android:layout_centerInParent="true"
  15. android:gravity="center"
  16. android:textSize="18sp"
  17. android:textColor="#000"
  18. android:text="信息界面"
  19. />
  20. <View
  21. android:layout_width="match_parent"
  22. android:layout_height="2px"
  23. android:background="#C0C0C0"
  24. android:layout_alignParentBottom="true"
  25. />
  26. </RelativeLayout>
  27. <LinearLayout
  28. android:id="@+id/dibu_bar"
  29. android:layout_width="match_parent"
  30. android:layout_height="56dp"
  31. android:layout_alignParentBottom="true"
  32. android:orientation="horizontal"
  33. android:background="#C0C0C0"
  34. >
  35. <TextView
  36. android:id="@+id/txt_dibu4"
  37. android:layout_width="0dp"
  38. android:layout_height="match_parent"
  39. android:layout_weight="1"
  40. android:background="#FFF"
  41. android:drawablePadding="3dp"
  42. android:gravity="center"
  43. android:padding="0dp"
  44. android:text="显示记录"
  45. android:textColor="@android:color/holo_green_light"
  46. android:textSize="16sp"
  47. />
  48. </LinearLayout>
  49. <View
  50. android:id="@+id/tab_bar"
  51. android:layout_width="match_parent"
  52. android:layout_height="2px"
  53. android:background="@android:color/white"
  54. android:layout_above="@id/dibu_bar"
  55. />
  56. <FrameLayout
  57. android:id="@+id/zj_content"
  58. android:layout_width="match_parent"
  59. android:layout_height="match_parent"
  60. android:layout_below="@id/dingbu_bar"
  61. android:layout_above="@id/tab_bar"
  62. >
  63. </FrameLayout>
  64. </RelativeLayout>

        (2)fragment_already.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. tools:context=".already">
  7. <LinearLayout
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. >
  11. <!-- TODO: Update blank fragment layout -->
  12. <ListView
  13. android:id="@+id/list_already"
  14. android:layout_width="match_parent"
  15. android:layout_height="match_parent"
  16. />
  17. </LinearLayout>
  18. <LinearLayout
  19. android:layout_width="match_parent"
  20. android:layout_height="56dp"
  21. android:layout_alignParentBottom="true"
  22. android:background="#C0C0C0"
  23. android:orientation="horizontal"
  24. android:gravity="center"
  25. android:layout_marginBottom="0dp"
  26. >
  27. <Button
  28. android:id="@+id/query"
  29. android:layout_width="wrap_content"
  30. android:layout_height="wrap_content"
  31. android:text="显示记录"
  32. android:textSize="20sp"
  33. />
  34. </LinearLayout>
  35. </RelativeLayout>

        (3)already_list_item .xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical" android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <LinearLayout
  6. android:layout_width="match_parent"
  7. android:layout_height="wrap_content"
  8. android:orientation="horizontal">
  9. <TextView
  10. android:id="@+id/序号"
  11. android:layout_width="64dp"
  12. android:layout_height="wrap_content"
  13. android:textSize="20sp"
  14. />
  15. <TextView
  16. android:id="@+id/介绍"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:textSize="20sp"
  20. />
  21. </LinearLayout>
  22. </LinearLayout>

 


        由于我前面写的部分是已经做出来的效果,所以前面的图片里会出现很多无关文件,因此我又重做了一遍,将代码原原本本的粘贴一个都不改,运行效果如下。

 

        在粘贴代码时,修改数据库链接池DBUtils中的使用JDBC链接数据库部分即可。

都看到这里了,不妨点个赞再走吧~

欢迎收藏讨论~

already类代码部分参考文章: http://t.csdn.cn/eRFGw

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/279772
推荐阅读
相关标签
  

闽ICP备14008679号