数据库连接 中的测试事例,包括工具类,配置文件,查询,增加,以及查询后返回对象

---------

方法一览

//从控制台输入信息进行查询最后会返回一个学生对象
@Test
public void serStu(){
//1,输入查询类型
int type=getsertypefromconsle();
//2,具体查询学生信息
Student student=serchstudeng(type);
//3,打印学生
printstudeng(student);
}

---------------------

输入台获取选择类型

/*
* 从控制台读入一个整数判断查询类型
* 1,按照学号查询
* 否则返回输入错误
*/
private int getsertypefromconsle(){
System.out.println("输入查询类型 1,为查询用户号 :输入类型为2按照姓名查询");
Scanner scanner=new Scanner(System.in);
int type=scanner.nextInt();
if(type!=1&&type!=2){
System.out.print("输入错误");
throw new RuntimeException();
}
return type;

}

-----------------------

根据类型查询学生

/*
* 具体查询学生信息的方法
* 若存在返回一个学生对象
* 不存在则返回null
*
*/
private Student serchstudeng(int type) {
// TODO Auto-generated method stub
String sqlString="select id ,name, scno from users where ";
// 根据type 确定用户需要查询信息
Scanner scanner=new Scanner(System.in);
if(type==1){
System.out.println("请输入学号");
int xueString=scanner.nextInt();
sqlString=sqlString+"id="+xueString+"";
}if(type==2){
System.out.println("输入姓名");
String nameString=scanner.next();
sqlString=sqlString+"name='"+nameString+"'";
}
//根据type 确定sql 语句
//执行查询
Student student=getstudeng(sqlString);
//将查询结果返回并作为studeng 封装
return student;
}

------------------------------------------------

学生信息的封装

private Student getstudeng(String sqlString) {
// TODO Auto-generated method stub
Student student=null;
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;


try {
Tools tools=new Tools();
connection=tools.getconnetion();
statement=(Statement) connection.createStatement();
//String sqq="select id,name,scno from users where "+sqlString+"";
resultSet=(ResultSet)statement.executeQuery(sqlString);
if(resultSet.next()){
student=new Student(resultSet.getInt(1),resultSet.getString(2),resultSet.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
Tools.realese(resultSet, connection, statement);
}

return student;
}

------------------------------------------

打印方法

private void printstudeng(Student student) {
// TODO Auto-generated method stub
if(student!=null){
System.out.println(student.getId()+"------>"+student.getSconString());
}else{
System.out.println("没有查到任何结果");
}
}

--------------------------------

学生类

package com.hu.testing;

public class Student {
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getNameString() {
return nameString;
}

public void setNameString(String nameString) {
this.nameString = nameString;
}

public String getSconString() {
return sconString;
}

public void setSconString(String sconString) {
this.sconString = sconString;
}

int id;
public Student(int id, String nameString, String sconString) {
super();
this.id = id;
this.nameString = nameString;
this.sconString = sconString;
}
public Student() {
}

String nameString;
String sconString;

public void addstu(Student student){

}
}

posted @ 2016-11-24 15:08  afterhoursprogramer  阅读(160)  评论(0编辑  收藏  举报