3、建立一个实现add,checklogin,getUser方法的类
package service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import model.User;
import util.DBO;
public class ManagerImpls implements Manager{//implements连接对应的接口,进行接口的实现
public boolean add(User u) {//注册添加的方法
boolean falst = false;
try {
Connection conn = DBO.getConnection();
String sql = “insert into user(tel,password,code) value(?,?,?)”;
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1, u.getTel());
pst.setString(2,u.getPassword());
pst.setString(3, u.getCode());
//int rows = pst.executeUpdate();//受影响的行数
int rows = pst.executeUpdate();
if (rows > 0) {
falst = true;
System.out.println(“添加完成”);
} else {
System.out.println(“添加失败!”);
}
} catch (Exception e) {
e.printStackTrace();
}
return falst;
}
public boolean checkLogin(int tel,String password) {//登录的方法
boolean flag = false;
Statement st = null;
ResultSet r = null;
java.sql.Connection conn = null;
conn = DBO.getConnection();
try {
st = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
String sql = "select * from user where tel= "+tel ;
try {
r = st.executeQuery(sql);
while (r.next()) {
if (r.getString("password").equals(password)) {
\\通过比较,得知是不是已经注册的值,判断是否可以登录
flag = true;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
public List getUser()//获得对象信息的方法
{
ArrayList list = new ArrayList();
java.sql.Connection conn = null;
java.sql.Statement st = null;
ResultSet r = null;
try {
conn = DBO.getConnection();
String sql = "select * from user " ;
st = conn.createStatement();
r = (ResultSet) st.executeQuery(sql);
while(r.next())
{
User user = new User();
user.setTel(r.getInt("tel"));
user.setPassword(r.getString("password"));
user.setCode(r.getString("code"));
list.add(user);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
4、对应的测试程序,
package test;
import java.sql.Connection;
import java.util.List;
import model.User;
import service.Manager;
import service.ManagerImpls;
import util.DBO;
public class Test {
public static void main(String[] args) {
Connection conn = DBO.getConnection();
if(conn != null)
{
System.out.println(“Connection Success.”);
}
Manager m = new ManagerImpls();
// for(int i=789;i<791;i++){//如果测试每次添加是否成功,需要更换新的值,添加过的值不能再进行添加
// User user = new User();
// user.setTel(i);
// user.setPassword(“password”);
// user.setCode(“code”);
// boolean flag = m.add(user);
// }
if(m.checkLogin(0, “password”)==true)
{
System.out.println(“登录成功!”);
}
/* Manager sm = new ManagerImpls();
List list = sm.getUser();
User stu = new User();
System.out.println(stu.getPassword());
System.out.println(stu.getCode());*/
}
}
接下来是相关代码