[Android Studio] Connect to MySQL database

1. Use environment

  • Android Studio
  • MySql8
  • JDBC depends on mysql-connector-java-5.1.49.jar

Project screenshots

 

2. Simple Android page writing

Since we connect to the database, we need to add, delete, modify and check the database, so we need to write a simple page

<?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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="安卓访问MySql数据库"
        android:textSize="20sp"
        android:textColor="#9C27B0"
        android:textStyle="bold"
        />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/but_query_count"
        android:text="查询用户数量"
        android:textSize="20sp"
        android:textColor="#CDC3CF"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/tv_user_count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="用户数量为:"
        android:textSize="20sp"
        android:textColor="#9C27B0"
        android:textStyle="bold"
        />
</LinearLayout>

3. Write a class to connect to the database

We need to write a class to connect to the database, which can be connected through Url, Driver, User, Password

package com.example.chi;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;

public class DBUtils {

    private static Connection conn=null;
    private static final String TAG = "DBUtils";
    public static int getConnection(){
        String url="jdbc:mysql://192.168.137.43:3306/zxcfruiter?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";
        /*电脑的IP地址*/
        /*数据库名字*/
        String user="root1";/*数据库用户名*/
        String password="123456789";/*进入数据库的密码*/

        int count = 0;

        try{
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,password);
            String sql = "select count(*) as sl from user";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()){
                count = rs.getInt("sl");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return count;
    }
}

4. Write the main program

package com.example.chi;

import androidx.annotation.NonNull;
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;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button btu_query_count;
    private TextView tv_user_count;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg){
            if(msg.what == 0){
                int count = (Integer)msg.obj;
                tv_user_count.setText("用户数据库中的用户数量为:"+count);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DBUtils.getConnection();
        initView();
    }
    
    private void initView(){
        btu_query_count = findViewById(R.id.but_query_count);
        tv_user_count = findViewById(R.id.tv_user_count);
        btu_query_count.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.but_query_count:  //查询数量。执行查询
                doQueryCount();
                break;
        }
    }


    //执行查询数量的方法
    private void doQueryCount(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = DBUtils.getConnection();
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = count;
                //向主线程发送数据
                handler.sendMessage(msg);

            }
        }).start();
    }

}

The operating environment can be directly queried

Query result demo

 Here we do not explicitly extract a certain class as the class for connecting to the database, and a certain class is the class for writing SQL statements. If necessary, you can modify it later through this project and just extract it.

If an error is reported, it may be that the version of the JAR package does not match the version of the MySQL database.

Notice

  • Note that the password and account number of the database are correct
  • Pay attention to whether the permissions of the database account have permissions
  • Pay attention to the setting of the IP address, because we use the mobile phone to run the program, which belongs to remote access, so we cannot use 127.0.0.1 or localhost, and need to use a specific IP address.

Guess you like

Origin blog.csdn.net/zhou_ge1/article/details/124426282