Android连接Mysql数据库教程以及增删改查

安装Mysql的驱动(Android需要mysql的驱动才能与mysql连接)

Android Studio 版本 3.2 mysql驱动版本 5.0.7 (本人mysql 5.7.26 )这两个版本最好都是5.xx,不然会出现连接不了的错误(版本要一致)
关于版本不一致会出现的错误可见:
解决Android连接Mysql数据库出现的DexArchiveBuilderException异常

打开mysql驱动下载页这里我链接的是5.0.7,你可以选择其他的版本
如图点击jar下载:
在这里插入图片描述

第二步,导入jar包

将我们下载好的mysql-connector-java.jar包放入我们建好的项目中的lib文件夹中,如图:
在这里插入图片描述
右键这个jar包,选择添加为库:
在这里插入图片描述
如果出现下图这几个东西,表明导入成功了:
在这里插入图片描述
好了准备工作已经完成了。

第三步,建议数据库与表

这里我用的是HeidiSQL操作mysql的,安装好heidiSQL之后,新建数据库test如下:
在这里插入图片描述
然后新建表test_one以及字段id,name:
在这里插入图片描述
添加如下数据记录:
在这里插入图片描述

第四步,建立连接

第一步,新建数据库连接帮助类

新建一个DBOpenHelper.java

package com.example.mysqlconnectiontest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBOpenHelper {
   private static String diver = "com.mysql.jdbc.Driver";
   //加入utf-8是为了后面往表中输入中文,表中不会出现乱码的情况
   private static String url = "jdbc:mysql://192.168.1.121:3306/test?characterEncoding=utf-8";
   private static String user = "root";//用户名
   private static String password = "123456";//密码
    /*
    * 连接数据库
    * */
   public static Connection getConn(){
       Connection conn = null;
       try {
           Class.forName(diver);
           conn = (Connection) DriverManager.getConnection(url,user,password);//获取连接
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       } catch (SQLException e) {
           e.printStackTrace();
       }
       return conn;
   }
}

第二步,修改activity_main.xml文件

<?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">
<Button
    android:id="@+id/bt_send"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="查询数据表"/>
    <TextView
        android:id="@+id/tv_response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

</LinearLayout>

第三步,修改MainActivity.java

package com.example.mysqlconnectiontest;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MainActivity extends AppCompatActivity {
    private Button button;
    private TextView textView;
    private static final int TEST_USER_SELECT = 1;
    int i =0;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String user;
            switch (msg.what){
                case TEST_USER_SELECT:
                    Test test = (Test) msg.obj;
                    user = test.getUser();
                    System.out.println("***********");
                    System.out.println("***********");
                    System.out.println("user:"+user);
                    textView.setText(user);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.bt_send);
        textView = (TextView) findViewById(R.id.tv_response);
    }

    @Override
    protected void onStart() {
        super.onStart();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //执行查询操作
                //通多点击buttoni自增长查询对应id的name
                if (i<=3){//因为数据库我就添加了三个数据条数,所以进行判断使其可以循环查询
                    i++;
                }
                else{
                    i=1;
                }
                //连接数据库进行操作需要在主线程操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection conn = null;
                        conn =(Connection) DBOpenHelper.getConn();
                        String sql = "select name from test_one where id='"+i+"'";
                        Statement st;
                        try {
                            st = (Statement) conn.createStatement();
                            ResultSet rs = st.executeQuery(sql);
                            while (rs.next()){
                               //因为查出来的数据试剂盒的形式,所以我们新建一个javabean存储
                                Test test = new Test();
                                test.setUser(rs.getString(1));
                                Message msg = new Message();
                                msg.what =TEST_USER_SELECT;
                                msg.obj = test;
                                handler.sendMessage(msg);
                            }
                            st.close();
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }
}    

第五步 添加网络权限

修改AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mysqlconnectiontest">
    //添加网络权限
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

运行结果如下:
在这里插入图片描述

第六步,数据库删除操作

第一步,修改activity_main.xml文件(添加一个删除按钮)

<?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">
<Button
    android:id="@+id/bt_send"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="查询数据表"/>
    <TextView
        android:id="@+id/tv_response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold" />
    <Button
        android:id="@+id/bt_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除数据"/>

</LinearLayout>

第二步,修改MainActivity.java

package com.example.mysqlconnectiontest;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button button,button_delete;
    private TextView textView;
    private static final int TEST_USER_SELECT = 1;
    int i =0,d=0;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String user;
            switch (msg.what){
                case TEST_USER_SELECT:
                    Test test = (Test) msg.obj;
                    user = test.getUser();
                    System.out.println("***********");
                    System.out.println("***********");
                    System.out.println("user:"+user);
                    textView.setText(user);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.bt_send);
        textView = (TextView) findViewById(R.id.tv_response);
        button_delete = (Button) findViewById(R.id.bt_delete);
    }

    @Override
    protected void onStart() {
        super.onStart();
        button.setOnClickListener(this);
        button_delete.setOnClickListener(this);

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_send:
                //执行查询操作
                //通多点击buttoni自增长查询对应id的name
                if (i<=3){
                    i++;
                }
                else{
                    i=1;
                }
                //连接数据库进行操作需要在主线程操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection conn = null;
                        conn =(Connection) DBOpenHelper.getConn();
                        String sql = "select name from test_one where id='"+i+"'";
                        Statement st;
                        try {
                            st = (Statement) conn.createStatement();
                            ResultSet rs = st.executeQuery(sql);
                            while (rs.next()){
                                //因为查出来的数据是集合的形式,所以我们新建一个javabean存储
                                Test test = new Test();
                                test.setUser(rs.getString(1));
                                Message msg = new Message();
                                msg.what =TEST_USER_SELECT;
                                msg.obj = test;
                                handler.sendMessage(msg);
                            }
                            st.close();
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            case R.id.bt_delete:
                //new一个线程执行删除数据库数据
                d++;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection conn = null;
                        int u = 0;
                        conn =(Connection) DBOpenHelper.getConn();
                        String sql = "delete from test_one where id='"+d+"'";
                        PreparedStatement pst;
                        try {
                                pst = (PreparedStatement) conn.prepareStatement(sql);
                                u = pst.executeUpdate();
                            pst.close();
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
                default:
        }
    }
}

运行效果如下:
在这里插入图片描述
表中数据全部被删掉(所以删除东西前最好加个弹出框,是否确定删除,来保证数据不会被乱删)
在这里插入图片描述

第七步,插入数据

第一步,修改activity_main.xml文件(添加一个添加按钮和输入框)

<?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">
<Button
    android:id="@+id/bt_send"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="查询数据表"/>
    <TextView
        android:id="@+id/tv_response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold" />
    <Button
        android:id="@+id/bt_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除数据"/>
    <EditText
        android:id="@+id/ed_insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入要插入的数据"
        android:maxLines="2"/>
    <Button
        android:id="@+id/bt_insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="插入数据"/>

</LinearLayout>

第二步,修改MainActivity.java

package com.example.mysqlconnectiontest;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button button,button_delete,button_insert;
    private TextView textView;
    private static final int TEST_USER_SELECT = 1;
    int i =0,d=0;
    private EditText editText;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String user;
            switch (msg.what){
                case TEST_USER_SELECT:
                    Test test = (Test) msg.obj;
                    user = test.getUser();
                    System.out.println("***********");
                    System.out.println("***********");
                    System.out.println("user:"+user);
                    textView.setText(user);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.bt_send);
        textView = (TextView) findViewById(R.id.tv_response);
        button_delete = (Button) findViewById(R.id.bt_delete);
        button_insert = (Button) findViewById(R.id.bt_insert);
        editText = (EditText) findViewById(R.id.ed_insert);
    }

    @Override
    protected void onStart() {
        super.onStart();
        button.setOnClickListener(this);
        button_delete.setOnClickListener(this);
        button_insert.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_send:
                //执行查询操作
                //通多点击buttoni自增长查询对应id的name
                i++;
                //连接数据库进行操作需要在主线程操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection conn = null;
                        conn =(Connection) DBOpenHelper.getConn();
                        String sql = "select name from test_one where id='"+i+"'";
                        Statement st;
                        try {
                            st = (Statement) conn.createStatement();
                            ResultSet rs = st.executeQuery(sql);
                            while (rs.next()){
                                //因为查出来的数据试剂盒的形式,所以我们新建一个javabean存储
                                Test test = new Test();
                                test.setUser(rs.getString(1));
                                Message msg = new Message();
                                msg.what =TEST_USER_SELECT;
                                msg.obj = test;
                                handler.sendMessage(msg);
                            }
                            st.close();
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            case R.id.bt_delete:
                //new一个线程执行删除数据库数据
                d++;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection conn = null;
                        int u = 0;
                        conn =(Connection) DBOpenHelper.getConn();
                        String sql = "delete from test_one where id='"+d+"'";
                        PreparedStatement pst;
                        try {
                                pst = (PreparedStatement) conn.prepareStatement(sql);
                                u = pst.executeUpdate();
                            pst.close();
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            case R.id.bt_insert:
                //执行插入操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection conn = null;
                        int u = 0;
                        conn =(Connection) DBOpenHelper.getConn();
                        String sql = "insert into test_one (name) values(?)";
                        PreparedStatement pst;
                        try {
                            pst = (PreparedStatement) conn.prepareStatement(sql);
                            //将输入的edit框的值获取并插入到数据库中
                            pst.setString(1,editText.getText().toString());
                            u = pst.executeUpdate();
                            pst.close();
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
                default:
        }
    }
}

运行结果如下:
在这里插入图片描述
数据库表记录:
在这里插入图片描述

第八步,更新数据

第一步,修改activity_main.xml文件(添加一个更新按钮和输入框)

<?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">
<Button
    android:id="@+id/bt_send"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="查询数据表"/>
    <TextView
        android:id="@+id/tv_response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold" />
    <Button
        android:id="@+id/bt_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除数据"/>
    <EditText
        android:id="@+id/ed_insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入要插入的数据"
        android:maxLines="2"/>
    <Button
        android:id="@+id/bt_insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="插入数据"/>
    <EditText
        android:id="@+id/ed_update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入更新的内容"
        android:maxLines="2"/>
<Button
    android:id="@+id/bt_update"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="更新数据"/>
</LinearLayout>

第二步,修改MainActivity.java

package com.example.mysqlconnectiontest;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button button,button_delete,button_insert,button_update;
    private TextView textView;
    private static final int TEST_USER_SELECT = 1;
    int i =0,d=0,z=0;
    private EditText editText,editText_update;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String user;
            switch (msg.what){
                case TEST_USER_SELECT:
                    Test test = (Test) msg.obj;
                    user = test.getUser();
                    System.out.println("***********");
                    System.out.println("***********");
                    System.out.println("user:"+user);
                    textView.setText(user);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.bt_send);
        textView = (TextView) findViewById(R.id.tv_response);
        button_delete = (Button) findViewById(R.id.bt_delete);
        button_insert = (Button) findViewById(R.id.bt_insert);
        button_update = (Button) findViewById(R.id.bt_update);
        editText_update = (EditText) findViewById(R.id.ed_update);
    }

    @Override
    protected void onStart() {
        super.onStart();
        button.setOnClickListener(this);
        button_delete.setOnClickListener(this);
        button_insert.setOnClickListener(this);
        button_update.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_send:
                //执行查询操作
                //通多点击buttoni自增长查询对应id的name
                if (i<=3){
                    i++;
                }else {
                    i=1;
                }
                //连接数据库进行操作需要在主线程操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection conn = null;
                        conn =(Connection) DBOpenHelper.getConn();
                        String sql = "select name from test_one where id='"+i+"'";
                        Statement st;
                        try {
                            st = (Statement) conn.createStatement();
                            ResultSet rs = st.executeQuery(sql);
                            while (rs.next()){
                                //因为查出来的数据试剂盒的形式,所以我们新建一个javabean存储
                                Test test = new Test();
                                test.setUser(rs.getString(1));
                                Message msg = new Message();
                                msg.what =TEST_USER_SELECT;
                                msg.obj = test;
                                handler.sendMessage(msg);
                            }
                            st.close();
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            case R.id.bt_delete:
                //new一个线程执行删除数据库数据
                d++;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection conn = null;
                        int u = 0;
                        conn =(Connection) DBOpenHelper.getConn();
                        String sql = "delete from test_one where id='"+d+"'";
                        PreparedStatement pst;
                        try {
                                pst = (PreparedStatement) conn.prepareStatement(sql);
                                u = pst.executeUpdate();
                            pst.close();
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            case R.id.bt_insert:
                //执行插入操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection conn = null;
                        int u = 0;
                        conn =(Connection) DBOpenHelper.getConn();
                        String sql = "insert into test_one (name) values(?)";
                        PreparedStatement pst;
                        try {
                            pst = (PreparedStatement) conn.prepareStatement(sql);
                            //将输入的edit框的值获取并插入到数据库中
                            pst.setString(1,editText.getText().toString());
                            u = pst.executeUpdate();
                            pst.close();
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            case R.id.bt_update:
                //new一个线程执行删除数据库数据
                z++;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection conn = null;
                        int u = 0;
                        conn =(Connection) DBOpenHelper.getConn();
                        String sql = "update test_one set name='"+editText_update.getText().toString()+"' where id='"+z+"'";
                        PreparedStatement pst;
                        try {
                            pst = (PreparedStatement) conn.prepareStatement(sql);
                            u = pst.executeUpdate();
                            pst.close();
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
                default:
        }
    }
}

运行结果如下:
在这里插入图片描述
在这里插入图片描述
关于Android连接mysql数据库以及增删改查就讲到这里了,欢迎讨论!
项目GitHub地址:https://github.com/Tobey-r1/RepositoryTest 。

补充

有人私信我问了我那个Test的问题,我简单补充上去吧:

public class Test {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • 114
    点赞
  • 612
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 75
    评论
好的,我了解了。针对你的问题,我可以给你一些基本的步骤和思路,帮助你实现 Android Studio 连接 MySQL 数据库并实现增删改查功能。 1. 配置 MySQL 数据库 首先,你需要在本地或者远程服务器上搭建一个 MySQL 数据库,并创建一张表用于存储数据。这一步需要你具备一定的数据库管理知识,如果你不熟悉,请参考相关的教程或者请专业人士帮忙。 2. 导入 MySQL 驱动 将 MySQL 驱动包(JDBC)导入到 Android Studio 项目中。你可以在 Maven 中心库中找到对应版本的 MySQL 驱动,或者手动下载 jar 包导入到项目中。在项目的 build.gradle 文件中添加以下代码: ``` dependencies { // ... implementation 'mysql:mysql-connector-java:8.0.23' } ``` 3. 编写数据库连接代码 在你的 Android Studio 项目中创建一个数据库连接类,用于连接 MySQL 数据库并执行 SQL 语句。代码示例: ```java import java.sql.*; public class MySQLConnection { // 数据库连接信息 private static final String DRIVER = "com.mysql.cj.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/mydatabase"; private static final String USERNAME = "root"; private static final String PASSWORD = "password"; // 获取数据库连接 public static Connection getConnection() { Connection connection = null; try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return connection; } // 关闭数据库连接 public static void closeConnection(Connection connection, Statement statement, ResultSet resultSet) { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } ``` 4. 实现增删改查功能 在你的 Android Studio 项目中编写增删改查的代码,使用上面创建的数据库连接类来执行 SQL 语句。代码示例: ```java import java.sql.*; public class MySQLUtils { // 插入数据 public static void insert(String name, String email) { Connection connection = null; PreparedStatement statement = null; try { connection = MySQLConnection.getConnection(); String sql = "INSERT INTO user(name, email) VALUES (?, ?)"; statement = connection.prepareStatement(sql); statement.setString(1, name); statement.setString(2, email); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { MySQLConnection.closeConnection(connection, statement, null); } } // 删除数据 public static void delete(int id) { Connection connection = null; PreparedStatement statement = null; try { connection = MySQLConnection.getConnection(); String sql = "DELETE FROM user WHERE id=?"; statement = connection.prepareStatement(sql); statement.setInt(1, id); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { MySQLConnection.closeConnection(connection, statement, null); } } // 更新数据 public static void update(int id, String name, String email) { Connection connection = null; PreparedStatement statement = null; try { connection = MySQLConnection.getConnection(); String sql = "UPDATE user SET name=?, email=? WHERE id=?"; statement = connection.prepareStatement(sql); statement.setString(1, name); statement.setString(2, email); statement.setInt(3, id); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { MySQLConnection.closeConnection(connection, statement, null); } } // 查询数据 public static void query() { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = MySQLConnection.getConnection(); String sql = "SELECT * FROM user"; statement = connection.createStatement(); resultSet = statement.executeQuery(sql); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String email = resultSet.getString("email"); System.out.println("id: " + id + ", name: " + name + ", email: " + email); } } catch (SQLException e) { e.printStackTrace(); } finally { MySQLConnection.closeConnection(connection, statement, resultSet); } } } ``` 这样,你就可以在 Android Studio 中连接 MySQL 数据库并实现增删改查功能了。当然,这只是一个简单的示例,实际情况可能会更加复杂,需要你根据具体的需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 75
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雪の星空朝酱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值