Android studio连接MySQL并完成简单的登录注册功能

打印 上一主题 下一主题

主题 497|帖子 497|积分 1491

近期需要完成一个Android项目,那先从与数据库交互最简单的登陆注册开始吧,现记录过程如下:
此篇文章的小demo主要涉及数据库的连接,以及相应信息的查找与插入。
我已将源码上传至GitHub:https://github.com/changyan-maker/LoginApp
首先展示一下完成效果。
数据库设计:

数据库内容:

登录结果展示:







此处默认您已经安装好Android studio 与MySQL软件。
首先需要创建一个空项目,关于空的项目如何创建,请参考我本篇文章:
https://blog.csdn.net/changyana/article/details/122948513
接下来需要连接MySQL,首先需要开启网络权限。需要添加一句话,具体位置如图:(将项目切换成Android模式比较好找)

之后是导入Mysql-connection的jar包
关于这个jar包需要我们去官网下载:https://downloads.mysql.com/archives/c-j/

关于版本的选择个人建议选择老一点的,比较稳定。选择ZIP格式进行下载。

下载完成后在里边找到mysql-connector-java-5.1.47-bin.jar并复制到粘贴板。

然后将Android studio的项目页面切换到Project模式,找到如下文件的位置进行粘贴。


粘贴完成后需要把刚才导入的jar包右击Add as Library


然后切换回Android视图,操作如下,新建一个package




然后粘贴代码如下:

本篇文章从图片可以看到我的项目名称为HelloWorld,这个项目只是我用来做测试的。但是代码是我完善后放在另一个项目为party中的,所有的位置都是一样的,只是项目名称不一样,这个不用担心。你只需要把我的代码里的包名改成你项目的名称就好了。
注意数据库的连接:要连接的数据库,还有用户名和密码都要和自己的Mysql对应。
  1. package com.example.party.utils;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. /**
  5. * function: 数据库工具类,连接数据库用
  6. */
  7. public class JDBCUtils {
  8.     private static final String TAG = "mysql-party-JDBCUtils";
  9.     private static String driver = "com.mysql.jdbc.Driver";// MySql驱动
  10.     private static String dbName = "party";// 数据库名称
  11.     private static String user = "root";// 用户名
  12.     private static String password = "";// 密码
  13.     public static Connection getConn(){
  14.         Connection connection = null;
  15.         try{
  16.             Class.forName(driver);// 动态加载类
  17.             String ip = "10.0.2.2";// 写成本机地址,不能写成localhost,同时手机和电脑连接的网络必须是同一个
  18.             // 尝试建立到给定数据库URL的连接
  19.             connection = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/" + dbName,
  20.                     user, password);
  21.         }catch (Exception e){
  22.             e.printStackTrace();
  23.         }
  24.         return connection;
  25.     }
  26. }
复制代码
接着创建entity和User

位置如图,创建方法与上述创建JDBCUtils一样

代码如下:
  1. package com.example.party.entity;
  2. public class User {
  3.     private int id;
  4.     private String userAccount;
  5.     private String userPassword;
  6.     private String userName;
  7.     private int userType;
  8.     private int userState;
  9.     private int userDel;
  10.     public User() {
  11.     }
  12.     public User(int id, String userAccount, String userPassword, String userName, int userType, int userState, int userDel) {
  13.         this.id = id;
  14.         this.userAccount = userAccount;
  15.         this.userPassword = userPassword;
  16.         this.userName = userName;
  17.         this.userType = userType;
  18.         this.userState = userState;
  19.         this.userDel = userDel;
  20.     }
  21.     public int getId() {
  22.         return id;
  23.     }
  24.     public void setId(int id) {
  25.         this.id = id;
  26.     }
  27.     public String getUserAccount() {
  28.         return userAccount;
  29.     }
  30.     public void setUserAccount(String userAccount) {
  31.         this.userAccount = userAccount;
  32.     }
  33.     public String getUserPassword() {
  34.         return userPassword;
  35.     }
  36.     public void setUserPassword(String userPassword) {
  37.         this.userPassword = userPassword;
  38.     }
  39.     public String getUserName() {
  40.         return userName;
  41.     }
  42.     public void setUserName(String userName) {
  43.         this.userName = userName;
  44.     }
  45.     public int getUserType() {
  46.         return userType;
  47.     }
  48.     public void setUserType(int userType) {
  49.         this.userType = userType;
  50.     }
  51.     public int getUserState() {
  52.         return userState;
  53.     }
  54.     public void setUserState(int userState) {
  55.         this.userState = userState;
  56.     }
  57.     public int getUserDel() {
  58.         return userDel;
  59.     }
  60.     public void setUserDel(int userDel) {
  61.         this.userDel = userDel;
  62.     }
  63. }
复制代码
之后创建dao和UserDao


  1. package com.example.party.dao;
  2. import com.example.party.entity.User;
  3. import com.example.party.utils.JDBCUtils;
  4. import android.util.Log;
  5. import java.sql.Connection;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.util.HashMap;
  9. /**
  10. * author: yan
  11. * date: 2022.02.17
  12. * **/
  13. public class UserDao {
  14.     private static final String TAG = "mysql-party-UserDao";
  15.     /**
  16.      * function: 登录
  17.      * */
  18.     public int login(String userAccount, String userPassword){
  19.         HashMap<String, Object> map = new HashMap<>();
  20.         // 根据数据库名称,建立连接
  21.         Connection connection = JDBCUtils.getConn();
  22.         int msg = 0;
  23.         try {
  24.             // mysql简单的查询语句。这里是根据user表的userAccount字段来查询某条记录
  25.             String sql = "select * from user where userAccount = ?";
  26.             if (connection != null){// connection不为null表示与数据库建立了连接
  27.                 PreparedStatement ps = connection.prepareStatement(sql);
  28.                 if (ps != null){
  29.                     Log.e(TAG,"账号:" + userAccount);
  30.                     //根据账号进行查询
  31.                     ps.setString(1, userAccount);
  32.                     // 执行sql查询语句并返回结果集
  33.                     ResultSet rs = ps.executeQuery();
  34.                         int count = rs.getMetaData().getColumnCount();
  35.                         //将查到的内容储存在map里
  36.                         while (rs.next()){
  37.                             // 注意:下标是从1开始的
  38.                             for (int i = 1;i <= count;i++){
  39.                                 String field = rs.getMetaData().getColumnName(i);
  40.                                 map.put(field, rs.getString(field));
  41.                             }
  42.                         }
  43.                         connection.close();
  44.                         ps.close();
  45.                     if (map.size()!=0){
  46.                         StringBuilder s = new StringBuilder();
  47.                         //寻找密码是否匹配
  48.                         for (String key : map.keySet()){
  49.                             if(key.equals("userPassword")){
  50.                                 if(userPassword.equals(map.get(key))){
  51.                                     msg = 1;            //密码正确
  52.                                 }
  53.                                 else
  54.                                     msg = 2;            //密码错误
  55.                                 break;
  56.                             }
  57.                         }
  58.                     }else {
  59.                         Log.e(TAG, "查询结果为空");
  60.                         msg = 3;
  61.                     }
  62.                 }else {
  63.                     msg = 0;
  64.                 }
  65.             }else {
  66.                 msg = 0;
  67.             }
  68.         }catch (Exception e){
  69.             e.printStackTrace();
  70.             Log.d(TAG, "异常login:" + e.getMessage());
  71.             msg = 0;
  72.         }
  73.         return msg;
  74.     }
  75.     /**
  76.      * function: 注册
  77.      * */
  78.     public boolean register(User user){
  79.         HashMap<String, Object> map = new HashMap<>();
  80.         // 根据数据库名称,建立连接
  81.         Connection connection = JDBCUtils.getConn();
  82.         try {
  83.             String sql = "insert into user(userAccount,userPassword,userName,userType,userState,userDel) values (?,?,?,?,?,?)";
  84.             if (connection != null){// connection不为null表示与数据库建立了连接
  85.                 PreparedStatement ps = connection.prepareStatement(sql);
  86.                 if (ps != null){
  87.                     //将数据插入数据库
  88.                     ps.setString(1,user.getUserAccount());
  89.                     ps.setString(2,user.getUserPassword());
  90.                     ps.setString(3,user.getUserName());
  91.                     ps.setInt(4,user.getUserType());
  92.                     ps.setInt(5, user.getUserState());
  93.                     ps.setInt(6,user.getUserDel());
  94.                     // 执行sql查询语句并返回结果集
  95.                     int rs = ps.executeUpdate();
  96.                     if(rs>0)
  97.                         return true;
  98.                     else
  99.                         return false;
  100.                 }else {
  101.                     return  false;
  102.                 }
  103.             }else {
  104.                 return  false;
  105.             }
  106.         }catch (Exception e){
  107.             e.printStackTrace();
  108.             Log.e(TAG, "异常register:" + e.getMessage());
  109.             return false;
  110.         }
  111.     }
  112.     /**
  113.      * function: 根据账号进行查找该用户是否存在
  114.      * */
  115.     public User findUser(String userAccount) {
  116.         // 根据数据库名称,建立连接
  117.         Connection connection = JDBCUtils.getConn();
  118.         User user = null;
  119.         try {
  120.             String sql = "select * from user where userAccount = ?";
  121.             if (connection != null){// connection不为null表示与数据库建立了连接
  122.                 PreparedStatement ps = connection.prepareStatement(sql);
  123.                 if (ps != null) {
  124.                     ps.setString(1, userAccount);
  125.                     ResultSet rs = ps.executeQuery();
  126.                     while (rs.next()) {
  127.                         //注意:下标是从1开始
  128.                         int id = rs.getInt(1);
  129.                         String userAccount1 = rs.getString(2);
  130.                         String userPassword = rs.getString(3);
  131.                         String userName = rs.getString(4);
  132.                         int userType = rs.getInt(5);
  133.                         int userState = rs.getInt(6);
  134.                         int userDel = rs.getInt(7);
  135.                         user = new User(id, userAccount1, userPassword, userName, userType, userState, userDel);
  136.                     }
  137.                 }
  138.             }
  139.         }catch (Exception e){
  140.             e.printStackTrace();
  141.             Log.d(TAG, "异常findUser:" + e.getMessage());
  142.             return null;
  143.         }
  144.         return user;
  145.     }
  146. }
复制代码
编写登录页面


  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"
  4.     xmlns:tools="http://schemas.android.com/tools"
  5.     android:layout_width="match_parent"
  6.     android:layout_height="match_parent"
  7.     tools:context=".MainActivity">
  8.     <LinearLayout
  9.         android:layout_width="match_parent"
  10.         android:layout_height="match_parent"
  11.         android:orientation="vertical"
  12.         tools:layout_editor_absoluteX="219dp"
  13.         tools:layout_editor_absoluteY="207dp"
  14.         android:padding="50dp"
  15.         >
  16.         <LinearLayout
  17.             android:layout_width="match_parent"
  18.             android:layout_height="wrap_content"
  19.             android:orientation="horizontal">
  20.             <TextView
  21.                 android:id="@+id/textView"
  22.                 android:layout_width="wrap_content"
  23.                 android:layout_height="wrap_content"
  24.                 android:layout_weight="1"
  25.                 android:textSize="15sp"
  26.                 android:text="账号:" />
  27.             <EditText
  28.                 android:id="@+id/uesrAccount"
  29.                 android:layout_width="wrap_content"
  30.                 android:layout_height="wrap_content"
  31.                 android:layout_weight="1"
  32.                 android:ems="10"
  33.                 android:inputType="phone"
  34.                 android:text="" />
  35.         </LinearLayout>
  36.         <LinearLayout
  37.             android:layout_width="match_parent"
  38.             android:layout_height="wrap_content"
  39.             android:orientation="horizontal">
  40.             <TextView
  41.                 android:id="@+id/textView2"
  42.                 android:layout_width="wrap_content"
  43.                 android:layout_height="wrap_content"
  44.                 android:layout_weight="1"
  45.                 android:textSize="15sp"
  46.                 android:text="密码:"
  47.                 />
  48.             <EditText
  49.                 android:id="@+id/userPassword"
  50.                 android:layout_width="wrap_content"
  51.                 android:layout_height="wrap_content"
  52.                 android:layout_weight="1"
  53.                 android:ems="10"
  54.                 android:inputType="textPersonName"
  55.                 />
  56.         </LinearLayout>
  57.         <LinearLayout
  58.             android:layout_width="match_parent"
  59.             android:layout_height="wrap_content"
  60.             android:orientation="horizontal">
  61.         </LinearLayout>
  62.         <Button
  63.             android:layout_marginTop="50dp"
  64.             android:id="@+id/button2"
  65.             android:layout_width="match_parent"
  66.             android:layout_height="wrap_content"
  67.             android:text="登录"
  68.             android:onClick="login"
  69.             />
  70.         <Button
  71.             android:id="@+id/button3"
  72.             android:layout_width="match_parent"
  73.             android:layout_height="wrap_content"
  74.             android:onClick="reg"
  75.             android:text="注册" />
  76.     </LinearLayout>
  77. </androidx.constraintlayout.widget.ConstraintLayout>
复制代码
效果如图:

完善MainActivity


  1. package com.example.party;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.annotation.SuppressLint;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.os.Handler;
  7. import android.os.Message;
  8. import android.util.Log;
  9. import android.view.View;
  10. import android.widget.EditText;
  11. import android.widget.Toast;
  12. import com.example.party.dao.UserDao;
  13. /**
  14. * function:连接页面加载首页
  15. */
  16. public class MainActivity extends AppCompatActivity {
  17.     private static final String TAG = "mysql-party-MainActivity";
  18.     @Override
  19.     protected void onCreate(Bundle savedInstanceState) {
  20.         super.onCreate(savedInstanceState);
  21.         setContentView(R.layout.activity_main);
  22.     }
  23.     public void reg(View view){
  24.         startActivity(new Intent(getApplicationContext(),register.class));
  25.     }
  26.     /**
  27.      * function: 登录
  28.      * */
  29.     public void login(View view){
  30.         EditText EditTextAccount = findViewById(R.id.uesrAccount);
  31.         EditText EditTextPassword = findViewById(R.id.userPassword);
  32.         new Thread(){
  33.             @Override
  34.             public void run() {
  35.                 UserDao userDao = new UserDao();
  36.                 int msg = userDao.login(EditTextAccount.getText().toString(),EditTextPassword.getText().toString());
  37.                 hand1.sendEmptyMessage(msg);
  38.             }
  39.         }.start();
  40.     }
  41.     @SuppressLint("HandlerLeak")
  42.     final Handler hand1 = new Handler() {
  43.         @Override
  44.         public void handleMessage(Message msg) {
  45.             if (msg.what == 0){
  46.                 Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_LONG).show();
  47.             } else if (msg.what == 1) {
  48.                 Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_LONG).show();
  49.             } else if (msg.what == 2){
  50.                 Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_LONG).show();
  51.             } else if (msg.what == 3){
  52.                 Toast.makeText(getApplicationContext(), "账号不存在", Toast.LENGTH_LONG).show();
  53.             }
  54.         }
  55.     };
  56. }
复制代码
编写注册页面




  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"
  4.     xmlns:tools="http://schemas.android.com/tools"
  5.     android:layout_width="match_parent"
  6.     android:layout_height="match_parent"
  7.     tools:context=".MainActivity">
  8.     <LinearLayout
  9.         android:layout_width="match_parent"
  10.         android:layout_height="match_parent"
  11.         android:orientation="vertical"
  12.         tools:layout_editor_absoluteX="219dp"
  13.         tools:layout_editor_absoluteY="207dp"
  14.         android:padding="50dp"
  15.         >
  16.         <LinearLayout
  17.             android:layout_width="match_parent"
  18.             android:layout_height="wrap_content"
  19.             android:orientation="horizontal">
  20.             <TextView
  21.                 android:id="@+id/textView"
  22.                 android:layout_width="wrap_content"
  23.                 android:layout_height="wrap_content"
  24.                 android:layout_weight="1"
  25.                 android:textSize="15sp"
  26.                 android:text="账号:" />
  27.             <EditText
  28.                 android:id="@+id/uesrAccount"
  29.                 android:layout_width="wrap_content"
  30.                 android:layout_height="wrap_content"
  31.                 android:layout_weight="1"
  32.                 android:ems="10"
  33.                 android:inputType="phone"
  34.                 android:text="" />
  35.         </LinearLayout>
  36.         <LinearLayout
  37.             android:layout_width="match_parent"
  38.             android:layout_height="wrap_content"
  39.             android:orientation="horizontal">
  40.             <TextView
  41.                 android:id="@+id/textView2"
  42.                 android:layout_width="wrap_content"
  43.                 android:layout_height="wrap_content"
  44.                 android:layout_weight="1"
  45.                 android:textSize="15sp"
  46.                 android:text="密码:"
  47.                 />
  48.             <EditText
  49.                 android:id="@+id/userPassword"
  50.                 android:layout_width="wrap_content"
  51.                 android:layout_height="wrap_content"
  52.                 android:layout_weight="1"
  53.                 android:ems="10"
  54.                 android:inputType="textPersonName"
  55.                 />
  56.         </LinearLayout>
  57.         <LinearLayout
  58.             android:layout_width="match_parent"
  59.             android:layout_height="wrap_content"
  60.             android:orientation="horizontal">
  61.         </LinearLayout>
  62.         <Button
  63.             android:layout_marginTop="50dp"
  64.             android:id="@+id/button2"
  65.             android:layout_width="match_parent"
  66.             android:layout_height="wrap_content"
  67.             android:text="登录"
  68.             android:onClick="login"
  69.             />
  70.         <Button
  71.             android:id="@+id/button3"
  72.             android:layout_width="match_parent"
  73.             android:layout_height="wrap_content"
  74.             android:onClick="reg"
  75.             android:text="注册" />
  76.     </LinearLayout>
  77. </androidx.constraintlayout.widget.ConstraintLayout>                                
复制代码
页面如图

完善register

上一步创建activity_register.xml的时候会自动生成一个Class,位置如图,如果没有的话自己右键创建一个Class就可以。

  1. package com.example.party;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.annotation.SuppressLint;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.os.Handler;
  7. import android.os.Message;
  8. import android.util.Log;
  9. import android.view.View;
  10. import android.widget.EditText;
  11. import android.widget.Toast;
  12. import com.example.party.dao.UserDao;
  13. import com.example.party.entity.User;
  14. /**
  15. * function:连接注册页面
  16. */
  17. public class register extends AppCompatActivity {
  18.     private static final String TAG = "mysql-party-register";
  19.     EditText userAccount = null;
  20.     EditText userPassword = null;
  21.     EditText userName = null;
  22.     @Override
  23.     protected void onCreate(Bundle savedInstanceState) {
  24.         super.onCreate(savedInstanceState);
  25.         setContentView(R.layout.activity_register);
  26.         userAccount = findViewById(R.id.userAccount);
  27.         userPassword = findViewById(R.id.userPassword);
  28.         userName = findViewById(R.id.userName);
  29.     }
  30.     public void register(View view){
  31.         String userAccount1 = userAccount.getText().toString();
  32.         String userPassword1 = userPassword.getText().toString();
  33.         String userName1 = userName.getText().toString();
  34.         User user = new User();
  35.         user.setUserAccount(userAccount1);
  36.         user.setUserPassword(userPassword1);
  37.         user.setUserName(userName1);
  38.         user.setUserType(1);
  39.         user.setUserState(0);
  40.         user.setUserDel(0);
  41.         new Thread(){
  42.             @Override
  43.             public void run() {
  44.                 int msg = 0;
  45.                 UserDao userDao = new UserDao();
  46.                 User uu = userDao.findUser(user.getUserAccount());
  47.                 if(uu != null){
  48.                     msg = 1;
  49.                 }
  50.                 else{
  51.                     boolean flag = userDao.register(user);
  52.                     if(flag){
  53.                         msg = 2;
  54.                     }
  55.                 }
  56.                 hand.sendEmptyMessage(msg);
  57.             }
  58.         }.start();
  59.     }
  60.     @SuppressLint("HandlerLeak")
  61.     final Handler hand = new Handler()
  62.     {
  63.         public void handleMessage(Message msg) {
  64.             if(msg.what == 0) {
  65.                 Toast.makeText(getApplicationContext(),"注册失败",Toast.LENGTH_LONG).show();
  66.             } else if(msg.what == 1) {
  67.                 Toast.makeText(getApplicationContext(),"该账号已经存在,请换一个账号",Toast.LENGTH_LONG).show();
  68.             } else if(msg.what == 2) {
  69.                 Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_LONG).show();
  70.                 Intent intent = new Intent();
  71.                 //将想要传递的数据用putExtra封装在intent中
  72.                 intent.putExtra("a","注册");
  73.                 setResult(RESULT_CANCELED,intent);
  74.                 finish();
  75.             }
  76.         }
  77.     };
  78. }
复制代码
下面汇总一下都需要改变的文件!



然后运行就可以啦!
心得建议

我的大部分时间感觉都是花费在了连接数据库上。刚开始数据库一直连接无法连接,原因是连接的请求要放在一个新的线程里,不能直接在当前线程请求连接数据库。之后解决了连接问题后得到数据进行匹配都是比较简单的事情。
个人建议:如果出问题可以先建一个临时的项目然后按照【连接数据库】–> 【请求数据并在控制台输出】 --> 【建立前端页面交互】这样的过程一步一步进行调试。
祝成功!

来源:https://blog.csdn.net/changyana/article/details/122950467
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

魏晓东

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表