写这篇纪念一下我这两个星期的学习成果,其中过程应该和你看这篇博客的经历差不多!真心希望能让后来者少走弯路,CSDN上有关这方面的博客很多,很乱,让很多新人无从下手,这是我写这篇博客的原因!
完成安卓客户端对服务器数据库的增删该查操作
一.客户端的登录和注册(增删)
二.通过客户端修改密码(改)
三.从服务器获取数据库的数据返回客户端并将其显示出来(查)
写JavaWeb的工具(netBeans)
集成工具包XAMMP
服务器上的数据库(MySQL-Front)
7种Jar包(可以评论,我私发给你)
关于增删的操作可以查看我之前的博客
登录和注册的源代码
查询操作的实现
用一个简单的例子说一下
android的activity-xml文件上只需要有一个按钮就可以了,监听这个按钮!
接下来是Mainactivity代码
public class MainActivity extends AppCompatActivity {
public static final String PATH = "你自己的URL";
Button start_btn;
//创建消息队列
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
String name = bundle.getString("username");
start_btn.setText(name);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start_btn = (Button) findViewById(R.id.btn_1);
start_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// MyThread myThread = new MyThread();
//myThread.start();
// MyThread domeThread = new MyThread();
//domeThread.start();
//DomeThread domeThread = new DomeThread();
//domeThread.start();
//需要调用哪个就将前面的斜杠删掉就可以
}
});
}
class DomeThread extends Thread {
@Override
public void run() {
List parma = new java.util.ArrayList();
parma.add(new BasicNameValuePair("username", "你需要查询数据的主码"));
try {
//请求执行对象
HttpClient client = new DefaultHttpClient();
//设置请求方式
HttpPost post = new HttpPost(PATH);
//绑定参数
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parma);
//把绑定参数设置到请求对象中
post.setEntity(entity);
//执行请求对象
HttpResponse response = client.execute(post);
//判断是否成功
if (response.getStatusLine().getStatusCode() == 200) {
//获取服务器数据
String str = EntityUtils.toString(response.getEntity());
//获取消息池对象,打开消息池
Message msg = handler.obtainMessage();
//创建数据储存对象
Bundle bundle = new Bundle();
bundle.putString("username", str);
//设置Message数据
msg.setData(bundle);
//将消息对象发送给消息队列
handler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
*获取服务器数据。
*
**/
class MyThread extends Thread {
String str;
@Override
public void run() {
try {
//构造请求地址
URL url = new URL(PATH);
//打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置可读取服务器数据
connection.setDoInput(true);
//设置连接超时
connection.setConnectTimeout(5000);
//设置请求方式
connection.setRequestMethod("POST");
//请求连接
connection.connect();
//判断是否连接成功
int code = connection.getResponseCode();
Log.e("tag", code + "");
if (code == 200) {
//通过Connection获取服务端的输入流
InputStream is = connection.getInputStream();
byte[] buffer = new byte[1024];
int length = 0;
//读取服务器数据
while ((length = is.read(buffer)) != -1) {
str = new String(buffer, 0, length);
Log.i("tag", str);
}
}
//冲这个消息池中获取对象。
Message msg = handler.obtainMessage();
//创建数据存放对象
Bundle bundle = new Bundle();
bundle.putString("name", str);
//把数据存放到msg中
msg.setData(bundle);
//hanlder发送数据
handler.sendMessage(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这部分代码是我借鉴一位前辈的
前辈的源代码
这里面的查的数据是直接写上固定死的,想要改成客户端输入也简单,将主码改为String username=edittext.gettext()再传进去就可以了。
服务器端的代码+数据库
表名course,字段分别是username,classname,coursename,num,requested;
UserDAO
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class UserDAO {
/**
* 查询给定用户名的用户的详细信息
*
* @param userName 给定的用户名
* @return 查询到的封装了详细信息的User对象
*/
public static User queryUser(String userName) {
//获得数据库的连接对象
Connection connection = DBManager.getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
//生成SQL代码
StringBuilder sqlStatement = new StringBuilder();
sqlStatement.append("SELECT * FROM user WHERE UserName=?");
//设置数据库的字段值
try {
preparedStatement = connection.prepareStatement(sqlStatement.toString());
preparedStatement.setString(1, userName);
resultSet = preparedStatement.executeQuery();
User user = new User();
if (resultSet.next()) {
user.setUserName(resultSet.getString("UserName"));
user.setPassword(resultSet.getString("Password"));
return user;
} else {
return null;
}
} catch (SQLException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
DBManager.closeAll(connection, preparedStatement, resultSet);
}
}
public static User Userinsert(String userName,String Password) {
//获得数据库的连接对象
Connection connection = DBManager.getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
//生成SQL代码
StringBuilder sqlStatement = new StringBuilder();
sqlStatement.append("insert into user(UserName,Password) values(?,?)");
//设置数据库的字段值
try {
preparedStatement = connection.prepareStatement(sqlStatement.toString());
preparedStatement.setString(1, userName);
preparedStatement.setString(2, Password);
User user = new User();
int row = preparedStatement.executeUpdate();
if (row>0) {
user.setUserName(resultSet.getString("UserName"));
user.setPassword(resultSet.getString("Password"));
return user;
} else {
return null;
}
} catch (SQLException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
DBManager.closeAll(connection, preparedStatement, resultSet);
}
}
public static User UserSaved(String username, String name, String college, String classname, String identity) {
Connection connection=DBManager.getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
StringBuilder sqlStatement = new StringBuilder();
sqlStatement.append("insert into information(username,name,college,classname,identity) values(?,?,?,?,?)");
//设置数据库的字段值
try {
preparedStatement = connection.prepareStatement(sqlStatement.toString());
preparedStatement.setString(1,username);
preparedStatement.setString(2,name);
preparedStatement.setString(3,college);
preparedStatement.setString(4,classname);
preparedStatement.setString(5,identity);
User user = new User();
int row = preparedStatement.executeUpdate();
if (row>0) {
user.setusername(resultSet.getString("username"));
user.setname(resultSet.getString("name"));
user.setcollege(resultSet.getString("college"));
user.setclassname(resultSet.getString("classname"));
user.setidentity(resultSet.getString("identity"));
return user;
} else {
return null;
}
} catch (SQLException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
DBManager.closeAll(connection, preparedStatement, resultSet);
}
}
public static User CourseInsert(String username,String classname, String coursename, String num, String requested) {
Connection connection=DBManager.getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
StringBuilder sqlStatement = new StringBuilder();
sqlStatement.append("insert into course(username,classname,coursename,num,requested) values(?,?,?,?,?)");
//设置数据库的字段值
try {
preparedStatement = connection.prepareStatement(sqlStatement.toString());
preparedStatement.setString(1,username);
preparedStatement.setString(2,classname);
preparedStatement.setString(3,coursename);
preparedStatement.setString(4,num);
preparedStatement.setString(5,requested);
User user = new User();
int row = preparedStatement.executeUpdate();
if (row>0) {
user.setusername(resultSet.getString("username"));
user.setclassname(resultSet.getString("classname"));
user.setcoursename(resultSet.getString("coursename"));
user.setnum(resultSet.getString("num"));
user.setrequested(resultSet.getString("requested"));
return user;
} else {
return null;
}
} catch (SQLException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
DBManager.closeAll(connection, preparedStatement, resultSet);
}
}
public static User CourseSelect(String username) {
Connection connection=DBManager.getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
StringBuilder sqlStatement = new StringBuilder();
sqlStatement.append("select * from course where username=?");
//设置数据库的字段值
try {
preparedStatement = connection.prepareStatement(sqlStatement.toString());
preparedStatement.setString(1,username);
User user = new User();
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
user.setusername(resultSet.getString("username"));
user.setclassname(resultSet.getString("classname"));
user.setcoursename(resultSet.getString("coursename"));
user.setnum(resultSet.getString("num"));
user.setrequested(resultSet.getString("requested"));
return user;
} else {
return null;
}
} catch (SQLException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
DBManager.closeAll(connection, preparedStatement, resultSet);
}
}
}
融合了增删该查的UserDAO,有点乱仔细看就可以
User
public class User {
//用户姓名
//用户姓名
private String UserName;
//用户密码
private String Password;
private String username;
private String name;
private String college;
private String classname;
private String identity;
private String coursename;
private String num;
private String yaoqiu;
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 String getusername() {
return username;
}
public void setusername(String username) {
this.username = username;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getcollege() {
return college;
}
public void setcollege(String college) {
this.college = college;
}
public String getclassname() {
return classname;
}
public void setclassname(String classname) {
this.classname = classname;
}
public String getidentity() {
return identity;
}
public void setidentity(String identity) {
this.identity = identity;
}
public void setcoursename(String coursename) {
this.coursename=coursename;
}
public String getcoursename() {
return coursename;
}
public void setnum(String num) {
this.num=num;
}
public String getnum() {
return num;
}
public void setrequested(String requested) {
this.requested=requested;
}
public String getrequested() {
return requested;
}
}
DBManager
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
/**
* 数据库管理类,提供连接数据库和拆解链接功能
*
* @author Implementist
*/
public class DBManager extends HttpServlet {
ServletConfig config; //定义一个ServletConfig对象
private static String UserName; //定义的数据库用户名
private static String Password; //定义的数据库连接密码
private static String url="jdbc:mysql://localhost:3306/myfirstapp"; //定义数据库连接URL
private static Connection connection; //定义连接
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config); //继承父类的init()方法
this.config = config; //获取配置信息
UserName = config.getInitParameter("DBUsername"); //获取数据库用户名
Password = config.getInitParameter("DBPassword"); //获取数据库连接密码
url = config.getInitParameter("ConnectionURL"); //获取数据库连接URL
}
/**
* 获得数据库连接对象
*
* @return 数据库连接对象
*/
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(url, UserName, Password);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | SQLException ex) {
Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
}
return connection;
}
/**
* 关闭所有的数据库连接资源
*
* @param connection Connection 链接
* @param statement Statement 资源
* @param resultSet ResultSet 结果集合
*/
public static void closeAll(Connection connection, Statement statement,
ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException ex) {
Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
CourseSelect///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 com.alibaba.fastjson.JSON;
import java.io.OutputStream;
/**
*
* @author YANG
*/
public class CourseSelect extends HttpServlet {
/**
* Processes requests for both HTTP GET
and POST
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
}
}
//
/**
* Handles the HTTP GET
method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
}
/**
* Handles the HTTP POST
method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//获得请求中传来的用户名和密码
String username=request.getParameter("username").trim();
User user=UserDAO.CourseSelect(username);
String array[]=new String[5];
array[0]=user.getusername();
array[1]=user.getclassname();
array[2]=user.getcoursename();
array[3]=user.getnum();
array[4]=user.getrequested();
OutputStream outputStream = response.getOutputStream();
for(int i=0;i
}
查出来的数据显示在Button里面
放一张图片