Android Studio连接mysql数据库方法
Posted 刘下来邦我吧
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Studio连接mysql数据库方法相关的知识,希望对你有一定的参考价值。
采用配置:
Android Studio北极狐+Lollipop版模拟器+Navicat15+mysql5.7.27+mysql-connector-java-5.1.38.jar
mysql下载地址
MySQL :: Download MySQL Community Server (Archived Versions)
选择:
Windows (x86, 64-bit), ZIP Archive |
1、下载后解压,放在自己喜欢的文件,将bin包加入环境配置的PATH路径即可。
2、管理员方式打开cmd,导入bin包所在目录,使用指令mysqld -install。(下载数据库)
3、使用指令mysqld -initialize。(初始化数据库)
4、回到bin上一级文件夹,发现多了几个文件夹,其中有一个data文件夹,点开进入,找到err结尾的文件,一个个用记事本打开,找到A temporary password is generated for root@localhost:,后面是你的mysql初始密码
5、管理员打开cmd,输入net start mysql,启动数据库,输入mysql -uroot -p密码 password 新密码
6、输入mysql -uroot -p新密码,做验证,验证成功则mysql配置完成(还有一步远程配置,留在Navicat中配置)
Navicat下载地址
https://pan.baidu.com/s/1Xn_ddT8v3RgAihROPFcq_A?pwd=phu5
下载后按照提示配置即可,记得断网。
配置完后
1、点开连接-新建连接-mysql,连接名随便取,密码为数据库密码,输入完成后,双击左侧连接,绿了说明连接成功。
2、点击上方的“用户”,双击root@localhost,将主机从localhost改为%。(这一步如果单机应该可以省略)。
3、打开cmd,输入ipconfig,找到自己的iPv4地址,在Navicat中点开连接-新建连接-mysql,连接名随便取,密码为数据库密码,主机改为自己的iPv4地址。
下载mysql-connector-java-5.1.38.jar
https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.38
找到Files栏下载jar即可
配置android Studio
1、打开项目,导入jar包,将下载的jar包放入项目/app/libs内,右键,点击Add As Library。
2、配置环境,在AndroidManifest.xml中加入
<uses-permission android:name="android.permission.INTERNET" />
3、 编写类,一共要编写三个类:JDBCUtils、User、UserDao。JDBCUtils用于连接数据库,User是信息存储类,UserDao是数据库与前端交互类。
编写类
JDBCUtils类:
package utils;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCUtils
private static final String TAG = "mysql11111";
static
try
Class.forName("com.mysql.jdbc.Driver");
Log.v(TAG, "加载JDBC驱动成功");
catch (ClassNotFoundException e)
Log.e(TAG, "加载JDBC驱动失败");
e.printStackTrace();
public static Connection getConn()
Connection conn = null;
try
conn= DriverManager.getConnection("jdbc:mysql://10.0.2.2:3306/lls?useUnicode=true&characterEncoding=utf-8&useSSL=false","root","123456");
Log.d(TAG, "数据库连接成功");
catch (Exception exception)
Log.d(TAG, "数据库连接失败");
exception.printStackTrace();
return conn;
public static void close(Connection conn)
try
conn.close();
catch (SQLException throwables)
throwables.printStackTrace();
后续如果出现问题可以单击下方Logcat,点击搜索框,输入设定的TAG(此处设定为mysql111111),查看驱动是否成功,连接是否成功。
上面的static是进行驱动。getConn函数是获取一个连接,如果连接失败了,返回的conn就是个空。
getConnection函数内10.0.2.2:3306/后的是数据库名,此处需要在Navicat中,打开自己的连接后,右键连接,创建数据库。后续的两个变量是用户名和密码。
close函数是关闭数据库。
User类:
package entity;
public class User
private int id;
private String name;
private int age;
private String password;
private String phone_number;
private String address;
public User()
public User(int id,String name,int age,String password,String phone_number,String address)
this.id=id;
this.name=name;
this.age=age;
this.password=password;
this.phone_number=phone_number;
this.address=address;
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 int getAge()
return age;
public void setAge(int age)
this.age=age;
public String getPassword()
return password;
public void setPassword(String password)
this.password=password;
public String getPhone_number()
return phone_number;
public void setPhone_number(String phone_number)
this.phone_number=phone_number;
public String getAddress()
return address;
public void setAddress(String address)
this.address=address;
非常明显,就是一个存储用户信息类,没什么好说的。
UserDao:
package dao;
import entity.User;
import 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 phone_number,String password)
String sql = "select * from users where phone_number = ? and password = ?";
Connection con = JDBCUtils.getConn();
try
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1,phone_number);
pst.setString(2,password);
if(pst.executeQuery().next())
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);
int age = rs.getInt(2);
String passworddb = rs.getString(3);
String phone_number = rs.getString(4);
String address = rs.getString(5);
user = new User(id,namedb,age,passworddb,phone_number,address);
catch (SQLException throwables)
throwables.printStackTrace();
finally
JDBCUtils.close(con);
return user;
public User findPhone_number(String phone_number)
String sql = "select * from users where phone_number = ?";
Connection con = JDBCUtils.getConn();
User user = null;
try
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1,phone_number);
ResultSet rs = pst.executeQuery();
while (rs.next())
int id = rs.getInt(0);
String namedb = rs.getString(1);
int age = rs.getInt(2);
String passworddb = rs.getString(3);
String phone_numberdb = rs.getString(4);
String address = rs.getString(5);
user = new User(id,namedb,age,passworddb,phone_numberdb,address);
catch (SQLException throwables)
throwables.printStackTrace();
finally
JDBCUtils.close(con);
return user;
可以稍微学一下语法,这里主要用到sql语句,设计的函数就算最基本的用于我们的页面搭建中的login、findUser等函数了。页面搭建的过程中也只需要调用这个类中的这几个函数即可。
Android Studio 实现登录注册-源代码 二(Servlet + 连接MySql数据库)
Android Studio 实现登录注册-源代码 (连接MySql数据库) | |
---|---|
Android Studio 实现登录注册-源代码 二(Servlet + 连接MySql数据库) | |
[Android Studio 实现登录注册-源代码 三(Servlet + 连接MySql数据库)实现学生信息的查询 (JSON通信)] |
一、Android 项目当中设置明文传输
1、设置明文传输的xml
<?xml version="1.0" encoding="UTF-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true"/>
</network-security-config>
2、引入上述创建的xml
android:networkSecurityConfig="@xml/network_security_config"
二、在MyEclipse当中创建Web项目
1、创建项目
引入MySQL的驱动包
2、创建实体类User
package 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;
}
}
3、创建JDBCUtils工具类
package dao;
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://127.0.0.1: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();
}
}
}
4、创建UserDao类
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import entity.User;
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(1);
String namedb = rs.getString(2);
String username = rs.getString(3);
String passworddb = rs.getString(4);
int age = rs.getInt(5);
String phone = rs.getString(6);
user = new User(id,namedb,username,passworddb,age,phone);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(con);
}
return user;
}
}
5、创建对应的LoginServlet
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.UserDao;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
response.setCharacterEncoding("UTF-8");
UserDao dao = new UserDao();
boolean login = dao.login(name, password);
String msg = "";
if(login){
msg = "成功";
}else{
msg = "失败";
}
PrintWriter out = response.getWriter();
out.println(msg);
out.flush();
out.close();
}
}
三、在Android Studio当中调用Servlet
(一)实现登录功能
1、创建连接Servlet的工具类(PostUtil)
package com.example.application01.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
//访问servlet
public class PostUtil {
//访问的serlver不一样
//传递的参数不一样
public static String Post(String url,String data)
{
String msg = "";
try{
//http://ms-yffprtappszi:8080/AndroidWeb/LoginServlet
HttpURLConnection conn = (HttpURLConnection) new URL("http://10.0.2.2:8080/AndroidWeb/"+url).openConnection();
//设置请求方式,请求超时信息
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
//设置运行输入,输出:
conn.setDoOutput(true);
conn.setDoInput(true);
//Post方式不能缓存,需手动设置为false
conn.setUseCaches(false);
//我们请求的数据:
//获取输出流
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.flush();
if (conn.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line=null;
while ((line = reader.readLine()) != null) {
response.append(line);
}
msg=response.toString();
}
}catch(Exception e)
{
e.printStackTrace();
}
return msg;
}
}
2、在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;
import com.example.application01.utils.PostUtil;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
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() {
String data="";
try {
data = "name="+ URLEncoder.encode(EditTextname.getText().toString(), "UTF-8")+
"&password="+ URLEncoder.encode(EditTextpassword.getText().toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String request = PostUtil.Post("LoginServlet",data);
int msg = 0;
if(request.equals("成功")){
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();
}
以上是关于Android Studio连接mysql数据库方法的主要内容,如果未能解决你的问题,请参考以下文章
Android Studio 实现登录注册-源代码 二(Servlet + 连接MySql数据库)
Android Studio 实现登录注册-源代码 二(Servlet + 连接MySql数据库)
Android studio连接MySQL并完成简单的登录注册功能
Android Studio使用JDBC远程连接mysql的注意事项(附示例)
Android Studio 实现实现学生信息的增删改查 -源代码 四(Servlet + 连接MySql数据库)
Android Studio 实现实现学生信息的查询 -源代码 三(Servlet + 连接MySql数据库) (JSON通信)