android 做登陆与mysql数据库交互
16lz
2021-01-23
tomcat服务器端:public class LoginOrRegServlet extends HttpServlet { //登录和注册服务器private static final long serialVersionUID = 1L;private static final String Driver = "com.mysql.jdbc.Driver"; //mysql驱动private static final String ConnectUrl = "jdbc:MySQL://localhost:3306/itosystem";//连接数据库的URLprivate String User = "root"; //登录数据库的用户名和密码private String Password = "num12369";@Overrideprotected void service(HttpServletRequest request,HttpServletResponse response) {String connUserName; //取得请求中的用户名和密码String connPassword;String Action; //判断请求中是登录还是注册boolean isNull = false; //根据用户名查询数据库是否查到Connection conn = null; DataOutputStream dos = null;Statement statement = null;ResultSet rs = null;connUserName = request.getParameter("userName");//取得请求中的各种值connPassword = request.getParameter("password");Action = request.getParameter("action");System.out.println(connUserName + "-" + connPassword+"-"+Action);try { //设置驱动和连接数据库Class.forName(Driver); conn = DriverManager.getConnection(ConnectUrl, User, Password);} catch (Exception e1) {e1.printStackTrace();}if(Action.equals("reg")){ //if请求为注册try {if (conn != null) { //if数据库连接成功statement = conn.createStatement(); //取得对数据库的操作对象rs = statement.executeQuery("select password from user where name='"+ connUserName + "'"); //根据请求中的用户名使用mysql语句对数据库的查询操作dos = new DataOutputStream(response.getOutputStream()); //对请求做出回应的对象if(!rs.next()){ //如果没有查到记录,表明用户名可以使用statement.executeUpdate("insert into user values('"+connUserName+"','"+connPassword+"')"); //执行插入操作dos.writeInt(5); //回应给客户端的值(值可以随意),5表示成功}else{ dos.writeInt(10); //10表示用户已存在}dos.flush(); //关闭各种对象dos.close();rs.close();statement.close();conn.close();}else{System.out.println("数据库连接失败");}} catch (Exception e) {System.out.println("产生异常");e.printStackTrace();}//注册结束}else if(Action.equals("login")){//if请求为登录try { if (conn != null) {statement = conn.createStatement();rs = statement.executeQuery("select password from user where name='"+ connUserName + "'"); //查询数据库dos = new DataOutputStream(response.getOutputStream());while(rs.next()){//if查询到有这个用户名的记录String backPassword;backPassword = rs.getString("password"); //从数据库获得这个用户名的密码if (backPassword.equals(connPassword)) { //用数据库返回的密码和连接请求中的密码对比dos.writeInt(10); //如果相等,返回值,登录成功}else{dos.writeInt(0); //否则登录失败}isNull = true; //查到有记录,将其赋值为true}if(!isNull){ //if没查到记录dos.writeInt(5); //返回5,表示用户不存在 }dos.flush(); //关闭各种对象dos.close();rs.close(); statement.close();conn.close();} else {System.out.println("数据库连接失败");}} catch (Exception e) {e.printStackTrace();}}}//登录操作结束}
更多相关文章
- Android实现动态显示或隐藏密码输入框的内容
- android数据库使用小结
- Android 记住密码功能
- android:sqlite 数据库的事务详解
- Android : 登录并保存密码
- Android SQLite数据库升级的问题
- Android sqlite 数据库操作
- Android 自定义Listview 如何绑定Sqlite数据库数据