android 连接mysql数据库问题

我也是初学,给你参考一下
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";//连接数据库的URL
private String User = "root"; //登录数据库的用户名和密码
private String Password = "num12369";
@Override
protected 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 连接mysql数据库问题,布布扣,bubuko.com

android 连接mysql数据库问题

上一篇:IOS-JSON数据解析


下一篇:android 获取app的版本号和版本名称