本文连接MySQL数据库使用包mysql-connector-java-5.1.47-bin.jar。MySQL5.数据库版本.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句子,然后操作查看哪个句子错了)
package com.example.an94; import android.util.Log; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class DBUtils { private static final String TAG="DBUtils";// 用于日志打印 private static Connection conn=null;// 定义连接变量conn ///数据库连接函数 public static Connection getConnection(String dbname) {//定义connection类函数,需要返回一个connection对象,即上面定义的对象conn String ip = "192.168.56.1";//ip地址,win R,输入cmd打开控制台,输入ipconfig /all查看本机ipv4地址,最上面那个 int port = 3306;//MySQL默认端口号安装时无需更改 String user = "root";//打开Navicat,如果显示,单击用户root@localhost,请修改为root@%或新加一个root@%,%表示任意,任意ip地址可以连接 String password = "6433868482";//密码 String url = "jdbc:mysql://" ip ":" port "/" dbname "?useUnicode=true&characterEncoding=UTF-8"; // "?useUnicode=true&characterEncoding=UTF-8"添加中文信息时,不会乱码 // 注册JDBC驱动固定语句 try { Class.forName("com.mysql.jdbc.Driver");//这是一个目录,你可以找到这个目录点进去理解 Log.d(TAG, "加载JDBC驱动成功"); } catch (ClassNotFoundException e) { Log.d(TAG, "加载JDBC驱动失败"); } // 创建与mysql的连接对象conn,当然,您也可以直接定义上述变量url直接写入,你不必在上面写一堆定义 try { conn = DriverManager.getConnection(url, user, password); Log.d(TAG, "数据库连接成功"); } catch (SQLException e) { Log.d(TAG, "数据库连接失败"); } return conn;//connection类,返回一个connection连接对象 } ///数据库查询函数 //前面加载JDBC驱动现在开始使用JDBC, //↓ List里只能放Map而这个类型的对象Map只能放置类型对象String类型为键,以Object类型值键值对 //也就是说,你定义了一个表list,然后表中的每一行数据都是HashMap,然后HashMap<标识符,您想要保存的数据> public static List<HashMap<String,Object>> getinfo(String dbname) throws SQLException { // 定义List<HashMap<String,Object>>并实例化类型数据 List<HashMap<String,Object>> list=new ArrayList<HashMap<String, Object>>(); // 调用连接函数,形参传入数据库名,获得conn对象,因为getConnection返回类型是Connection及conn //1.调用连接,否则,连不上数据库 Connection conn=getConnection(dbname); // 通过connection对象conn获取statement对象sta,createStatement():创建基础statement对象 //2.你要用statement去执行sql但是你必须连接到数据库才能执行,所以你必须使用连接对象来创建statement对象。 Statement sta=conn.createStatement(); // 定义sql语句 String sql="select * from user "; // 调用Statement对象执行sql返回结果为结果集,它是一个带指针的表格,通过操作指针进行数据操作 //3.使用statement在三种方法中executeQuery()方法,返回是结果集ResultSet对象,所以你要用ResultSet变量接收 ResultSet result=sta.executeQuery(sql); // 判断是否为空 if (result==null){ return null; } // 在此结果集(仅此表)和下一行中进入函数。这个表有指针,百度搜索ResultSet接口中的方法, while (result.next()) { // 每个循环都会有新的实例HashMap对象用于填写遍历数据 HashMap<String,Object> map=new Hashap<>();
// 往map中填数据,map的数据类型相当于键值对
map.put("ID",result.getString("ID"));//ResultSet中的getString方法,获取指定字段的String类型值
map.put("message",result.getString("message"));
// 每次循环完就添加到list中
list.add(map);
}
// 把list返回出去,否则拿不到这个list
return list;
}
}
(2).我定义的 fragment(下文中的fragment_already),这个fragment对应的java类already(类名自定义)。listview放在fragment_already中。
already代码:
package com.example.an94;
import android.annotation.SuppressLint;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.example.an94.DBUtils.getConnection;
import static com.example.an94.DBUtils.getinfo;
public class already extends Fragment {
private static final String TAG="DBUtils";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_already,null);//找到你的fragment
//找到你的fragment中的控件,之所以要view.findViewById(),因为是在fragment里找,而你是通过的view找到fragment
Button query=view.findViewById(R.id.query);
//*************查找按钮功能****************************************************************************
query.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在点击事件里写内容
//-----------------------------------------
// Handler部分
//Android studio中,需要新开一个子线程处理数据库,主线程只有一个不能同时执行
// 由子线程传出的数据在这里处理
@SuppressLint("HandlerLeak")
// 先new一个Handler对象
final Handler handler =new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
// 获取listview组件,因为我们要在这个部分更新UI组件
final ListView listView=view.findViewById(R.id.list_already);
// if的判断条件是区分msg是哪一条,即msg的ID,是下面连接数据库时我们自己定义的
if(msg.what==1){
// 获取发送过来的msg.obj对象,因为我传的是List<HashMap<String, Object>>类型的obj,所以这边同样用List<HashMap<String, Object>> list去接收,要强转
List<HashMap<String,Object>> list= (List<HashMap<String, Object>>) msg.obj;
// 定义SimpleAdapter,参数分别为当前上下文,刚拿到的数据集合list,子项布局文件,数据集合中的字段信息,要添加到的子布局文件中的控件ID
SimpleAdapter simpleAdapter=new SimpleAdapter(getContext(),list,R.layout.already_list_item,new String[]{"ID","message"},new int[]{R.id.序号,R.id.介绍});
// 为listview设置适配器
listView.setAdapter(simpleAdapter);
}
}
};
// Handler部分
//----------------------------------------------------------------------
//--------------------------------------------------------------
// 连接数据库并进行相应操作的线程
// 第二、第三部分
// new 一个线程,接下来是数据库操作部分,要在子线程中执行
Thread thread=new Thread(new Runnable() {
// 定义一个子线程中的全局变量List<HashMap<String,Object>> list1,用于接收从DBUtils中返回的list
List<HashMap<String,Object>> list1=new ArrayList<HashMap<String, Object>>();
@Override
public void run() {
// 与数据库建立连接
getConnection("android");
try {
// 以下这些要用try/catch包含
// 调用数据库工具类的getinfo函数,用list1接收返回的list数据
list1=getinfo("android");
// 打印日志,测试用
Log.d(TAG, list1.toString());
} catch (SQLException e) {
e.printStackTrace();
}
// 将从数据库拿到的list1对象传给message再由handler传出,再在handler中处理,可进行更新UI
// 新建一个message对象,尽量不要直接new,而是用这种方法,因为有内存的问题存在
Message message=Message.obtain();
// 设置message的辨认码,这里设为1
message.what=1;
// 把刚才接收到的list1赋给message.obj对象
message.obj=list1;
// 通过handler将携带数据的message传出去,传到handler中
handler.sendMessage(message);
}
});
// 上面线程定义完了,现在启动线程
thread.start();
// 第二、第三部分
//------------------------------------------------
}
});
return view;
}
}
(3)最后是 MainActivity.Java
package com.example.an94;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView txt_dibufour;
private already fg4;
private FragmentManager fManager; //声明FragmentManager类变量
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);//将系统自带的标题栏隐藏掉
//这一句一定要在加载activity之前调用
setContentView(R.layout.activity_main);
fManager = getSupportFragmentManager(); //实例化fragmentManager变量
bindViews();
}
private void bindViews() {
txt_dibufour=(TextView) findViewById((R.id.txt_dibu4));
txt_dibufour.setOnClickListener(this);
}
private void setSelected(){//重置所有文本选中状态
txt_dibufour.setSelected(false);
}
private void hideAllFragment(FragmentTransaction fragmentTransaction){
if(fg4 != null)fragmentTransaction.hide(fg4);
}
@Override
public void onClick(View v){
FragmentTransaction fTransaction = fManager.beginTransaction();//通过begin开启事务
hideAllFragment(fTransaction);
switch (v.getId()){
case R.id.txt_dibu4:
setSelected();
txt_dibufour.setSelected(true);
if(fg4==null){
fg4=new already();
fTransaction.add(R.id.zj_content,fg4);
}else{
fTransaction.show(fg4);
}
break;
}
fTransaction.commit();//提交事务
}
}
2.创建布局文件
(1)MainActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="@+id/dingbu_bar"
android:layout_width="match_parent"
android:layout_height="48dp">
<TextView
android:id="@+id/txt_topbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:textSize="18sp"
android:textColor="#000"
android:text="信息界面"
/>
<View
android:layout_width="match_parent"
android:layout_height="2px"
android:background="#C0C0C0"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
<LinearLayout
android:id="@+id/dibu_bar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:background="#C0C0C0"
>
<TextView
android:id="@+id/txt_dibu4"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#FFF"
android:drawablePadding="3dp"
android:gravity="center"
android:padding="0dp"
android:text="显示记录"
android:textColor="@android:color/holo_green_light"
android:textSize="16sp"
/>
</LinearLayout>
<View
android:id="@+id/tab_bar"
android:layout_width="match_parent"
android:layout_height="2px"
android:background="@android:color/white"
android:layout_above="@id/dibu_bar"
/>
<FrameLayout
android:id="@+id/zj_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/dingbu_bar"
android:layout_above="@id/tab_bar"
>
</FrameLayout>
</RelativeLayout>
(2)fragment_already.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".already">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="@+id/list_already"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentBottom="true"
android:background="#C0C0C0"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginBottom="0dp"
>
<Button
android:id="@+id/query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示记录"
android:textSize="20sp"
/>
</LinearLayout>
</RelativeLayout>
(3)already_list_item .xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/序号"
android:layout_width="64dp"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
<TextView
android:id="@+id/介绍"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
</LinearLayout>
</LinearLayout>
由于我前面写的部分是已经做出来的效果,所以前面的图片里会出现很多无关文件,因此我又重做了一遍,将代码原原本本的粘贴一个都不改,运行效果如下。
在粘贴代码时,修改数据库链接池DBUtils中的使用JDBC链接数据库部分即可。
都看到这里了,不妨点个赞再走吧~
欢迎收藏讨论~
already类代码部分参考文章: http://t.csdn.cn/eRFGw