Android studio與mysql-jdbc連接,實(shí)現(xiàn)登錄界面
Android studio 與mysql連接-我用的是jdbc連接.坑很多,謹(jǐn)慎使用.首先我們需要在工程里面導(dǎo)入mysql驅(qū)動(dòng),我用的是5.1.49.在Ocral官網(wǎng)下載就可以了.鏈接在下面,我也會(huì)放在文末.(https://dev.mysql.com/downloads/connector/j/).最好使用5.1.49版本.mysql8.0也可以用這個(gè)驅(qū)動(dòng).8.0以上的驅(qū)動(dòng)總是有各種各樣的問(wèn)題.反正我是放棄了.有勇氣的大佬可以去嘗試. 下載完之后解壓 將jar文件復(fù)制到工程文件libs下路徑如下 ./myAppliation(我的工程名)/app/libs/ 然后再添加依靠.復(fù)制之后將工程調(diào)整到project視圖,找到app里面的libs,現(xiàn)在libs里面就已經(jīng)能看到這個(gè)驅(qū)動(dòng)了,不過(guò)這個(gè)時(shí)候還是沒(méi)有完成依靠添加.
右擊驅(qū)動(dòng),然后點(diǎn)擊Add AS Library
選擇ok 就添加完成了.
這時(shí)候我們已經(jīng)將驅(qū)動(dòng)完全添加了.
添加如下目錄包,都必須要添加. 創(chuàng)建一個(gè)JDBCUtils類
package com.example.myapplication.utils;import android.util.Log;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;public class JDBCUtils {static {try {Log.v("MainActivity","222");Class.forName("com.mysql.jdbc.Driver");//(1)Log.v("MainActivity","333");} catch (ClassNotFoundException e) {e.printStackTrace();}}public static Connection getConn() {String ip = "192.168.206.226";int port = 3306;String dbName = "test";String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName;String user = "1111";String password = "1111";Connection conn = null;try {Log.v("MainActivity",url);conn = DriverManager.getConnection(url, user, password);//(2)Log.v("MainActivity","連接成功");}catch (Exception exception){exception.printStackTrace();Log.v("MainActivity","連接失敗");}return conn;}public static void close(Connection conn){try {conn.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}
其中一些奇奇怪怪的日志輸出是我調(diào)試用的,可以不用添加. (1) Class.forName(“com.mysql.jdbc.Driver”); Class.forName()方法要求JVM查找并加載指定的類到內(nèi)存中,(JVM是java虛擬機(jī)的縮寫,是Java運(yùn)行環(huán)境的一部分,它是來(lái)解析和運(yùn)行Java程序的.)告訴jvm去com.mysql.jdbc這個(gè)路徑下找Drive. (2)jdbc連接數(shù)據(jù)庫(kù)需要使用DriverManager類的getConnection()方法,這里面有很多踩坑的地方,百分之50的坑都是因?yàn)檫@里,第一,ip地址,不要用localhost,如果用真機(jī)測(cè)試,要查看本機(jī)ip地址(只需要win+r然后cmd然后ipconfig得到ipv4地址就是我們要用的IP地址),如果要是用模擬機(jī)測(cè)試的話需要把IP地址改成10.0.0.1 .端口號(hào)就是自己的mysql端口號(hào)一般來(lái)說(shuō)是3306.第二,user和password分別是數(shù)據(jù)庫(kù)用戶名和用戶名密碼,這里的數(shù)據(jù)庫(kù)用戶名要給到所有權(quán)限,除了常規(guī)權(quán)限之外.主要是遠(yuǎn)程訪問(wèn)mysql> grant all privileges on . to 用戶名@’%’ identified by “password”;并且最好不要用root因?yàn)槿绻胷oot的話系統(tǒng)會(huì)認(rèn)為不安全,開(kāi)通權(quán)限失敗,所以我們這里創(chuàng)建了一個(gè)全新的用戶并且賦予所有的權(quán)限.密碼就是用戶密碼啦,這個(gè)沒(méi)什么所謂的啦…第三,就是時(shí)區(qū)處理的問(wèn)題.這里mysql驅(qū)動(dòng)5.0和8.0有很多區(qū)別,我們這里說(shuō)的就是5.0版本.5.0是可以不做處理的.全部都是博主踩的血坑!!!
添加網(wǎng)絡(luò)權(quán)限 完成以上內(nèi)容之后我們需要添加網(wǎng)絡(luò)權(quán)限,在AndroidManifest.xml里面.
<uses-permission android:name="android.permission.INTERNET" />
登錄前端 因?yàn)檫@篇文章不是主要講前端的,所以我們就用最簡(jiǎn)單的界面.activity_main.xml
<?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"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:layout_editor_absoluteX="220dp"tools:layout_editor_absoluteY="220dp"android:padding="60dp"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:textSize="15sp"android:text="賬號(hào):" /><EditTextandroid: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><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:textSize="15sp"android:text="密碼:"/><EditTextandroid:id="@+id/password"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:ems="10"android:inputType="textPersonName"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"></LinearLayout><Buttonandroid:layout_marginTop="60dp"android:id="@+id/button2"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="登錄"android:onClick="LOGIN"/><Buttonandroid:id="@+id/button3"android:layout_width="match_parent"android:layout_height="wrap_content"android:onClick="REG"android:text="注冊(cè)" /></LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
大家可以DIY可以做的更好看一點(diǎn),以后我會(huì)繼續(xù)發(fā)帖慢慢完善.
MainActivity.java 這里就是我們的后端啦.直接上程序.
(1)在安卓4.0起,為了避免連接失敗形成阻塞,連接數(shù)據(jù)庫(kù)這邊必須要放在子線程里面。創(chuàng)建new thread就可以,要注意一個(gè)常識(shí),在子線程內(nèi)沒(méi)有辦法直接與顯示界面交互,需要建立handle。
package com.example.myapplication;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;import com.example.myapplication.dao.UserDao;public class MainActivity extends AppCompatActivity {// Button button=findViewById(R.id.button3);@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//Button regbutton=this.findViewById(R.id.button2);}public void REG(View view){// Log.v("MainActivity","www");//Intent intent=new Intent(MainActivity.this,RegisterActivity.class);//startActivity(intent);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(){(1)@Overridepublic void run() {Log.v("MainActivity","www");UserDao userDao = new UserDao();Log.v("MainActivity","ww");boolean a = userDao.login(EditTextname.getText().toString(),EditTextpassword.getText().toString());int msg = 0;if(a){msg = 1;}hand1.sendEmptyMessage(msg);}}.start();}final Handler hand1 = new Handler(){@Overridepublic void handleMessage(Message msg) {if(msg.what == 1){Toast.makeText(getApplicationContext(),"登錄成功",Toast.LENGTH_LONG).show();try{Thread.sleep(1000);//單位:毫秒} catch (Exception e) {}
注冊(cè)界面
<?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=".RegisterActivity"><LinearLayoutandroid: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"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:textSize="15sp"android:text="賬號(hào):" /><EditTextandroid:id="@+id/name"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:ems="10"android:inputType="textPersonName"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:textSize="15sp"android:text="昵稱:" /><EditTextandroid:id="@+id/username"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:ems="10"android:inputType="textPersonName"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:textSize="15sp"android:text="密碼:"/><EditTextandroid:id="@+id/password"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:ems="10"android:inputType="textPassword"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:textSize="15sp"android:text="手機(jī):"/><EditTextandroid:id="@+id/phone"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:ems="10"android:inputType="phone"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"></LinearLayout><Buttonandroid:layout_marginTop="50dp"android:id="@+id/button2"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="注冊(cè)"android:onClick="register"/><Buttonandroid:id="@+id/button3"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="重置" /></LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
隨便填的兩個(gè)注冊(cè)內(nèi)容,主要的就是昵稱和密碼。
注冊(cè)界面后端
package com.example.myapplication;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;import com.example.myapplication.dao.UserDao;
import com.example.myapplication.entity.User;public class RegisterActivity extends AppCompatActivity {EditText name = null;EditText username = null;EditText password = null;EditText phone = null;@Overrideprotected 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);}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();if(cname.length() < 2 || cusername.length() < 2 || cpassword.length() < 2 ){Toast.makeText(getApplicationContext(),"輸入信息不符合要求請(qǐng)重新輸入",Toast.LENGTH_LONG).show();return;}User user = new User();user.setName(cname);user.setUsername(cusername);user.setPassword(cpassword);user.setPhone(cphone);new Thread(){@Overridepublic void run() {int msg = 0;Log.v("MainActivity",",,,,,,");UserDao userDao = new UserDao();Log.v("MainActivity",user.getName());User uu = userDao.findUser(user.getName());//String the_name=uu.getUsername();// Log.v("MainActivity","the_name:");//Log.v("MainActivity",the_name);if(uu != null){msg = 1;}else {boolean flag = userDao.register(user);if (flag) {msg = 2;}}hand.sendEmptyMessage(msg);System.out.println(msg);try {Thread.sleep(2000);//單位:毫秒} catch (InterruptedException e) {e.printStackTrace();}}}.start();}final Handler hand = new Handler(){@Overridepublic void handleMessage(Message msg) {if(msg.what == 0){Toast.makeText(getApplicationContext(),"注冊(cè)失敗",Toast.LENGTH_LONG).show();}if(msg.what == 1){Toast.makeText(getApplicationContext(),"該賬號(hào)已經(jīng)存在,請(qǐng)換一個(gè)賬號(hào)",Toast.LENGTH_LONG).show();}if(msg.what == 2){//startActivity(new Intent(getApplication(),MainActivity.class));Intent intent = new Intent();//將想要傳遞的數(shù)據(jù)用putExtra封裝在intent中intent.putExtra("a","註冊(cè)");setResult(RESULT_CANCELED,intent);finish();}}};
}
這里面的主要內(nèi)容和上一個(gè)mainactivity是一樣的。增加了一些邏輯判斷,來(lái)判斷用戶輸入是否合法。
創(chuàng)建user.Dao類,用來(lái)寫一些與數(shù)據(jù)庫(kù)交互的函數(shù)。需要有一些數(shù)據(jù)庫(kù)語(yǔ)言基礎(chǔ)。
package com.example.myapplication.dao;import android.content.Intent;
import android.provider.Settings;
import android.util.Log;
import android.view.View;import com.example.myapplication.entity.Book;
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;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;import static java.sql.DriverManager.getConnection;public class UserDao {public boolean login(String name, String password){String sql = "select * from users where name = ? and password = ?";(1)Log.v("MainActivity","111");Connection con = JDBCUtils.getConn();Log.v("MainActivity","444");try {PreparedStatement pst=con.prepareStatement(sql);(2)Log.v("MainActivity","888");pst.setString(1,name);(3)pst.setString(2,password);if(pst.executeQuery().next()){(4)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,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.setString(4,user.getPhone());int value = pst.executeUpdate();if(value>0){return true;}} catch (SQLException throwables) {throwables.printStackTrace();}finally {JDBCUtils.close(con);}return false;}}
實(shí)例化類
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;
private byte agree;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 String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}
}
總結(jié)
以上是生活随笔 為你收集整理的Android studio开发.<大学访客车辆预约管理系统> 的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。