Android Studio连接MySql实现登录注册(附源代码)

本文主要介绍了android studio连接mysql实现登录注册,分享给大家,具体如下:

一、创建工程

1、创建一个空白工程

2、随便起一个名称

3、设置网络连接权限

 <uses-permission android:name="android.permission.internet"/>

二、引入mysql驱动包

1、切换到普通java工程

2、在libs当中引入mysql的jar包

将mysql的驱动包复制到libs当中

三、编写数据库和dao以及jdbc相关代码

1、在数据库当中创建表

sql语句

/*
navicat mysql data transfer

source server         : localhost_3306
source server version : 50562
source host           : localhost:3306
source database       : test

target server type    : mysql
target server version : 50562
file encoding         : 65001

date: 2021-05-10 17:28:36
*/

set foreign_key_checks=0;

-- ----------------------------
-- table structure for `student`
-- ----------------------------
drop table if exists `student`;
create table `student` (
  `sid` int(11) not null auto_increment,
  `sname` varchar(255) not null,
  `sage` int(11) not null,
  `address` varchar(255) not null,
  primary key (`sid`)
) engine=innodb auto_increment=3 default charset=utf8;

-- ----------------------------
-- records of student
-- ----------------------------
insert into `student` values ('1', 'andi', '21', '21212');
insert into `student` values ('2', 'a', '2121', '2121');

-- ----------------------------
-- table structure for `users`
-- ----------------------------
drop table if exists `users`;
create table `users` (
  `uid` int(11) not null auto_increment,
  `name` varchar(255) not null,
  `username` varchar(255) not null,
  `password` varchar(255) not null,
  `age` int(255) not null,
  `phone` longblob not null,
  primary key (`uid`)
) engine=innodb auto_increment=6 default charset=utf8;

-- ----------------------------
-- records of users
-- ----------------------------
insert into `users` values ('2', '123', 'hbv环保局', '123', '33', 0x3133333333333333333333);
insert into `users` values ('3', '1233', '反复的', '1233', '12', 0x3132333333333333333333);
insert into `users` values ('4', '1244', '第三代', '1244', '12', 0x3133333333333333333333);
insert into `users` values ('5', '1255', 'sas', '1255', '33', 0x3133333333333333333333);

2、在android studio当中创建jdbcutils类

切换会android视图

注意链接数据库的地址是:jdbc:mysql://10.0.2.2:3306/test

package com.example.myapplication.utils;


import java.sql.connection;
import java.sql.drivermanager;
import java.sql.sqlexception;

public class jdbcutils {



    static {

        try {
            class.forname("com.mysql.jdbc.driver");
        } catch (classnotfoundexception e) {
            e.printstacktrace();
        }

    }

    public static connection getconn() {
        connection  conn = null;
        try {
            conn= drivermanager.getconnection("jdbc:mysql://10.0.2.2:3306/test","root","root");
        }catch (exception exception){
            exception.printstacktrace();
        }
        return conn;
    }

    public static void close(connection conn){
        try {
            conn.close();
        } catch (sqlexception throwables) {
            throwables.printstacktrace();
        }
    }
}

3、创建user实体类

package com.example.myapplication.entity;public class user {    private int id;    private string name;    private string username;    private string password;    private int age;    private string phone;    public user() {    }    public user(int id, string name, string username, string password, int age, string phone) {        this.id = id;        this.name = name;        this.username = username;        this.password = password;        this.age = age;        this.phone = phone;    }    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;    }    public string getusername() {        return username;    }    public void setusername(string username) {        this.username = username;    }    public string getpassword() {        return password;    }    public void setpassword(string password) {        this.password = password;    }    public int getage() {        return age;    }    public void setage(int age) {        this.age = age;    }    public string getphone() {        return phone;    }    public void setphone(string phone) {        this.phone = phone;    }}

4、创建dao层和userdao

package com.example.myapplication.dao;import com.example.myapplication.entity.user;import com.example.myapplication.utils.jdbcutils;import java.sql.connection;import java.sql.preparedstatement;import java.sql.resultset;import java.sql.sqlexception;public class userdao {    public boolean login(string name,string password){        string sql = "select * from users where name = ? and password = ?";        connection  con = jdbcutils.getconn();        try {            preparedstatement pst=con.preparestatement(sql);            pst.setstring(1,name);            pst.setstring(2,password);            if(pst.executequery().next()){                return true;            }        } catch (sqlexception throwables) {            throwables.printstacktrace();        }finally {            jdbcutils.close(con);        }        return false;    }    public boolean register(user user){        string sql = "insert into users(name,username,password,age,phone) values (?,?,?,?,?)";        connection  con = jdbcutils.getconn();        try {            preparedstatement pst=con.preparestatement(sql);            pst.setstring(1,user.getname());            pst.setstring(2,user.getusername());            pst.setstring(3,user.getpassword());            pst.setint(4,user.getage());            pst.setstring(5,user.getphone());            int value = pst.executeupdate();            if(value>0){                return true;            }        } catch (sqlexception throwables) {            throwables.printstacktrace();        }finally {            jdbcutils.close(con);        }        return false;    }    public user finduser(string name){        string sql = "select * from users where name = ?";        connection  con = jdbcutils.getconn();        user user = null;        try {            preparedstatement pst=con.preparestatement(sql);            pst.setstring(1,name);            resultset rs = pst.executequery();            while (rs.next()){               int id = rs.getint(0);               string namedb = rs.getstring(1);               string username = rs.getstring(2);               string passworddb  = rs.getstring(3);               int age = rs.getint(4);                string phone = rs.getstring(5);               user = new user(id,namedb,username,passworddb,age,phone);            }        } catch (sqlexception throwables) {            throwables.printstacktrace();        }finally {            jdbcutils.close(con);        }        return user;    }}

四、编写页面和activity相关代码

1、编写登录页面

<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.constraintlayout 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">    <linearlayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical"        tools:layout_editor_absolutex="219dp"        tools:layout_editor_absolutey="207dp"        android:padding="50dp"        >        <linearlayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal">            <textview                android:id="@+id/textview"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_weight="1"                android:textsize="15sp"                android:text="账号:" />            <edittext                android:id="@+id/name"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_weight="1"                android:ems="10"                android:inputtype="textpersonname"                android:text="" />        </linearlayout>        <linearlayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal">            <textview                android:id="@+id/textview2"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_weight="1"                android:textsize="15sp"                android:text="密码:"                />            <edittext                android:id="@+id/password"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_weight="1"                android:ems="10"                android:inputtype="textpersonname"               />        </linearlayout>        <linearlayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal">        </linearlayout>        <button            android:layout_margintop="50dp"            android:id="@+id/button2"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="登录"            android:onclick="login"            />        <button            android:id="@+id/button3"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:onclick="reg"            android:text="注册" />    </linearlayout></androidx.constraintlayout.widget.constraintlayout>

效果

2、编写注册页面代码

<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.constraintlayout 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">    <linearlayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical"        tools:layout_editor_absolutex="219dp"        tools:layout_editor_absolutey="207dp"        android:padding="50dp"        >        <linearlayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal">            <textview                android:id="@+id/textview"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_weight="1"                android:textsize="15sp"                android:text="账号:" />            <edittext                android:id="@+id/name"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_weight="1"                android:ems="10"                android:inputtype="textpersonname"                android:text="" />        </linearlayout>        <linearlayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal">            <textview                android:id="@+id/textview2"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_weight="1"                android:textsize="15sp"                android:text="密码:"                />            <edittext                android:id="@+id/password"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_weight="1"                android:ems="10"                android:inputtype="textpersonname"                />        </linearlayout>        <linearlayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal">        </linearlayout>        <button            android:layout_margintop="50dp"            android:id="@+id/button2"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="登录"            android:onclick="login"            />        <button            android:id="@+id/button3"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:onclick="reg"            android:text="注册" />    </linearlayout></androidx.constraintlayout.widget.constraintlayout>

3、完善mainactivity

package com.example.application01;import androidx.appcompat.app.appcompatactivity;import android.content.intent;import android.os.bundle;import android.os.handler;import android.os.message;import android.view.view;import android.widget.edittext;import android.widget.toast;import com.example.application01.dao.userdao;public class mainactivity extends appcompatactivity {    @override    protected void oncreate(bundle savedinstancestate) {        super.oncreate(savedinstancestate);        setcontentview(r.layout.activity_main);    }    public void reg(view view){        startactivity(new intent(getapplicationcontext(),registeractivity.class));    }    public void login(view view){        edittext edittextname = (edittext)findviewbyid(r.id.name);        edittext edittextpassword = (edittext)findviewbyid(r.id.password);        new thread(){            @override            public void run() {                userdao userdao = new userdao();                boolean aa = userdao.login(edittextname.gettext().tostring(),edittextpassword.gettext().tostring());                int msg = 0;                if(aa){                    msg = 1;                }                hand1.sendemptymessage(msg);            }        }.start();    }    final handler hand1 = new handler()    {        @override        public void handlemessage(message msg) {            if(msg.what == 1)            {                toast.maketext(getapplicationcontext(),"登录成功",toast.length_long).show();            }            else            {                toast.maketext(getapplicationcontext(),"登录失败",toast.length_long).show();            }        }    };}

4、完善registeractivity

package com.example.application01;import androidx.appcompat.app.appcompatactivity;import android.content.intent;import android.os.bundle;import android.os.handler;import android.os.message;import android.view.view;import android.widget.edittext;import android.widget.toast;import com.example.application01.dao.userdao;import com.example.application01.entity.user;public class registeractivity extends appcompatactivity {    edittext name = null;    edittext username = null;    edittext password = null;    edittext phone = null;    edittext age = null;    @override    protected void oncreate(bundle savedinstancestate) {        super.oncreate(savedinstancestate);        setcontentview(r.layout.activity_register);         name = findviewbyid(r.id.name);         username = findviewbyid(r.id.username);         password = findviewbyid(r.id.password);         phone = findviewbyid(r.id.phone);         age = findviewbyid(r.id.age);    }    public void register(view view){        string cname = name.gettext().tostring();        string cusername = username.gettext().tostring();        string cpassword = password.gettext().tostring();        system.out.println(phone.gettext().tostring());        string cphone = phone.gettext().tostring();        int cgae = integer.parseint(age.gettext().tostring());        if(cname.length() < 2 || cusername.length() < 2 || cpassword.length() < 2 ){            toast.maketext(getapplicationcontext(),"输入信息不符合要求请重新输入",toast.length_long).show();            return;        }        user user = new user();        user.setname(cname);        user.setusername(cusername);        user.setpassword(cpassword);        user.setage(cgae);        user.setphone(cphone);        new thread(){            @override            public void run() {                int msg = 0;                userdao userdao = new userdao();                user uu = userdao.finduser(user.getname());                if(uu != null){                    msg = 1;                }                boolean flag = userdao.register(user);                if(flag){                    msg = 2;                }                hand.sendemptymessage(msg);            }        }.start();    }    final handler hand = new handler()    {        @override        public void handlemessage(message msg) {            if(msg.what == 0)            {                toast.maketext(getapplicationcontext(),"注册失败",toast.length_long).show();            }            if(msg.what == 1)            {                toast.maketext(getapplicationcontext(),"该账号已经存在,请换一个账号",toast.length_long).show();            }            if(msg.what == 2)            {                //startactivity(new intent(getapplication(),mainactivity.class));                intent intent = new intent();                //将想要传递的数据用putextra封装在intent中                intent.putextra("a","註冊");                setresult(result_canceled,intent);                finish();            }        }    };}

五、运行测试效果

到此这篇关于android studio连接mysql实现登录注册(附源代码) 的文章就介绍到这了,更多相关android studio 登录注册内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐