Android使用JDBC连接MySQL总结

一、MySQL数据库的安装和使用

使用的是Navicat for MySQL 数据库,软件和激活工具下载网盘链接,提取码:jnvb
具体激活步骤可参考其他博客。

二、数据库相关环境:

数据库版本:8.0.23
mysql-connector-java-8.0.23.jar

三、开发步骤

1. 导入jar包

AS工程,以project形式打开,在app目录下,找到libs文件夹,将mysql的jar包复制粘贴到libs目录,
在这里插入图片描述
右击jar包,选择Add As Library… 等待一会即可完成导入jar包。
在这里插入图片描述

2. 权限

在AndroidMainfest文件中添加权限,用于连接网络。

    <uses-permission android:name="android.permission.INTERNET"/>
3. 注意事项
由于使用的是8.0版本MySQL,所以加载类名和连接的url和之前版本不一样,需要进行修改。进行连接的时候需要开启线程方可进行连接。
  //动态加载类
  Class.forName("com.mysql.cj.jdbc.Driver");
  //设置连接地址以及数据库名称
  String url = "jdbc:mysql://xxx.xxx.xxx.x:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT";

四、代码

1. 布局代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#3399ff"
        android:gravity="center"
        android:padding="15dp"
        android:text="登录"
        android:textColor="#fff"
        android:textSize="18dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="12dp">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="账号:" />

            <EditText
                android:id="@+id/et_username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="密码:" />

            <EditText
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword" />

        </LinearLayout>


        <Button
            android:id="@+id/btn_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="登录" />

        <Button
            android:id="@+id/btn_register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="注册" />

    </LinearLayout>

</RelativeLayout>
2. MainActivity
package com.example.mysqlrocord;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_username;
    private EditText et_password;
    private Button btn_login;
    private Button btn_register;

    private String username, password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView() {
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_register = (Button) findViewById(R.id.btn_register);

        btn_login.setOnClickListener(this);
        btn_register.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                submit();
                break;
            case R.id.btn_register:
//                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
        }
    }
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.d("999","已经开启线程");
            try {
                Log.d("999","即将加载类");
                //动态加载类
                Class.forName("com.mysql.cj.jdbc.Driver");
                Log.d("999","即将执行url");
                //设置连接地址以及数据库名称
                String url = "jdbc:mysql://192.168.137.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT";
                Log.d("999","即将连接数据库");
                //连接数据库
                Connection conn = DriverManager.getConnection(url, "root", "123456");
                Log.d("999","即将创建SQL语句");
                //创建Statement对象(可执行SQL语句的对象)
                Statement stmt = conn.createStatement();
                Log.d("999","返回数据");
                //执行sql语句 返回一个ResultSet对象(返回数据集合)
                String sql = "SELECT userName,password FROM user WHERE uername='" + username + "' AND password='" + password + "' LIMIT 1";
                ResultSet rs = stmt.executeQuery(sql);
                //遍历rs 输出数据
                while (rs.next()) {
                    String id = rs.getString(1);
                    String name = rs.getString(2);
                    String gender = rs.getString(3);
                    System.out.println("ID:" + id + " username:" + name + " UserPass:" + gender);
                }
                if (rs.next()) {
                    //登录成功,跳转到主页
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    //登录失败
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void submit() {
        username = et_username.getText().toString().trim();
        password = et_password.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "账号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        else if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        else
        //新建一个线程 因为 Android 主程序中不允许直接使用网络
            new Thread(runnable).start();
    }

}
3. 跳转界面自己实现即可
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值