(在上一篇文章中,我们详细的介绍了连接数据库的方法,以及eclipse操作数据库信息的相关方法,在这里我们将主要讲封装。)

主要内容:

  • 一般的连接数据库测试
  • 把连接数据库的方法封装成一个类和测试
  • 一个简单的插入表实例
  • 查询数据实例
  • 封装查询的数据库的信息
  • 封装信息后的查询数据库

一.一般的数据库连接测试

 public class TestConnection1 {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/test?"//数据库url
+ "useUnicode=true&characterEncoding=UTF8";//防止乱码
String user="h4";
String pass="111";
Connection conn=DriverManager.getConnection(url, user, pass); System.out.println(conn+",成功连接数据库");
conn.close();
}
}

二.我们不可能每写一个处理信息功能就写一次连接,这样太麻烦,那么为了方便以后的应用,我们通常把数据库连接封装起来。

具体实现步骤如下:

1.定义变量:

private static String DRIVER_CLASS;
private static String URL;
private static String USERRNAME;
private static String PASSWORD;

2.在你建的eclipse根目录下新建一个File文件Properties;

文件内容为你定义的变量所指向的对象:

driver=com.mysql.jdbc.Driver
                                                   url=jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=UTF8
                                                   user=h4
                                                   pass=111

3.构建一个Properties对象:Properties p=new Properties();

4. java.io下的类FileInputStream的方法;FileInputStream(String name) :通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。
                                                    来获取这个文件里面的资料:FileInputStream fis=new FileInputStream("db.properties");

5. 用3构建的变量p来下载资料:p.load(fis);

6.利用getProperty();获取参数:

DRIVER_CLASS=p.getProperty("driver");
                                         URL=p.getProperty("url");
                                         USERRNAME=p.getProperty("user");
                                         PASSWORD=p.getProperty("pass");

7.写一个连接数据库的方法getConection();

8.写一个关闭数据库的方法close(Connection conn);

写好后代码如下:

 public class jdbcutil {
private static String DRIVER_CLASS;
private static String URL;
private static String USERRNAME;
private static String PASSWORD;
private static Properties p=new Properties();
static{
try {
FileInputStream fis=new FileInputStream("db.properties");
p.load(fis);
DRIVER_CLASS=p.getProperty("driver");
URL=p.getProperty("url");
USERRNAME=p.getProperty("user");
PASSWORD=p.getProperty("pass");
Class.forName(DRIVER_CLASS);
fis.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConection(){
Connection conn=null;
try{
conn=DriverManager.getConnection(URL, USERRNAME, PASSWORD);
}
catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn) {
try {
if (conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
} }

那么封装好之后,我们来写一个测试类,测试连接

 public class TestConnection2 {

     public static void main(String[] args) throws Exception {
Connection conn=jdbcutil.getConection();//利用封装好的类名来调用连接方法便可
System.out.println(conn+",成功连接数据库");
jdbcutil.close( conn);//同样利用类名调用关闭方法即可
}
}

三.连接成功,我们写一个简单的向数据库插入表的实例。

 public class TestDDl {

     public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
conn=jdbcutil.getConection();//连接数据库
String createTableSql= " create table user_test1( "+//记住引号和单词间一定要有空格
" id int, "+
" name varchar(32) , "+
" password varchar(32) , "+
" birthday date "+
" ) ";
try {
stmt=conn.createStatement();
stmt.execute(createTableSql);
} catch (SQLException e) {
e.printStackTrace();
}
jdbcutil.close(null, stmt, conn);//关闭数据库
}
}

四.我们在写一个查询数据库数据的实例。(有三种方法)

 public class TestDQL {
public static void main(String[] args){
Connection conn=null;//定义为空值
Statement stmt=null;
ResultSet rs=null;
String sql="select * from employees";//sql语句
conn=jdbcutil.getConection();
try {
stmt=conn.createStatement();//创建一个Statement语句对象
rs=stmt.executeQuery(sql);//执行sql语句
while(rs.next()){
System.out.print(rs.getInt(1)+",");
System.out.print(rs.getString(2)+",");//直接使用参数
System.out.print(rs.getString(3)+",");
System.out.print(rs.getString(4)+",");
System.out.println(rs.getString(5));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);//关闭数据库
}
}
}
//第二种方法如下:
 public class TestDQl2 {

     public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String sql="select * from employees";
conn=jdbcutil.getConection();
try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
while(rs.next()){
System.out.print(rs.getInt("userid")+",");//里面直接写要查找的内容名称
System.out.print(rs.getString("employee_id")+",");
System.out.print(rs.getString("last_name")+",");
System.out.print(rs.getString("salary")+",");
System.out.println(rs.getString("department_id"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);
}
}
}
 //第三种方法如下:
public class TestDQL3 {
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String sql="select * from employees";
conn=jdbcutil.getConection();
try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
while(rs.next()){
int index=1;
System.out.print(rs.getInt(index++)+",");
System.out.print(rs.getString(index++)+",");
System.out.print(rs.getString(index++)+",");
System.out.print(rs.getString(index++)+",");
System.out.println(rs.getString(index++));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);
}
}
}

五.在四里面我们写了查询员工资料的信息,但是有的时候我们要保存起来方便之后更好的查找,那怎么办呢?没错,封装。

 public class employees implements Serializable {
private Integer userid;
private String employee_id;
private String last_name;
private String salary;
private String department_id; public employees() {
super();
} public employees(String employee_id, String last_name, String salary, String department_id) {
super();
this.employee_id = employee_id;
this.last_name = last_name;
this.salary = salary;
this.department_id = department_id;
} @Override
public String toString() {
return "employees [userid=" + userid + ", employee_id=" + employee_id + ", last_name=" + last_name
+ ", salary=" + salary + ", department_id=" + department_id + "]";
} public Integer getUserid() {
return userid;
} public void setUserid(Integer userid) {
this.userid = userid;
} public String getEmployee_id() {
return employee_id;
} public void setEmployee_id(String employee_id) {
this.employee_id = employee_id;
} public String getLast_name() {
return last_name;
} public void setLast_name(String last_name) {
this.last_name = last_name;
} public String getSalary() {
return salary;
} public void setSalary(String salary) {
this.salary = salary;
} public String getDepartment_id() {
return department_id;
} public void setDepartment_id(String department_id) {
this.department_id = department_id;
}
}

六.封装好后的查询和上面没封装之前有点变化。

 public class TestDQL4 {
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
List<employees> emps=new ArrayList<>();//构造集合对象 String sql="select * from employees"; conn=jdbcutil.getConection();//获取数据库连接 try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
while(rs.next()){//遍历结果集
int index=1;
employees emp=new employees();//构造员工类对象
emp.setUserid(rs.getInt(index++));//获取值
emp.setEmployee_id(rs.getString(index++));
emp.setLast_name(rs.getString(index++));
emp.setSalary(rs.getString(index++));
emp.setDepartment_id(rs.getString(index++));
emps.add(emp);//放到集合中去
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);//关闭连接
}
for(employees emp:emps){//遍历
System.out.println(emp);
}
}
}

其实我们可以继续封装,把遍历结果集给封装起来。

 public class TestDQL5 {

     public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
List<employees> emps=new ArrayList<>(); String sql="select * from employees"; conn=jdbcutil.getConection(); try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
emps=resultSetToEmployees(rs);
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);
}
for(employees emp:emps){
System.out.println(emp);
}
}
public static List<employees> resultSetToEmployees(ResultSet rs){
List<employees> emps=new ArrayList<>();
try {
while(rs.next()){
int index=1;
employees emp=new employees();
emp.setUserid(rs.getInt(index++));
emp.setEmployee_id(rs.getString(index++));
emp.setLast_name(rs.getString(index++));
emp.setSalary(rs.getString(index++));
emp.setDepartment_id(rs.getString(index++));
emps.add(emp);
}
} catch (SQLException e) {
e.printStackTrace();
} return emps;
}
}

如果是一个人查询信息呢?还可以这样封装。

 public class TestDQL6 {
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
List<employees> emps=new ArrayList<>(); String sql="select * from employees"; conn=jdbcutil.getConection(); try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
while(rs.next()){
employees emp=resultSetToEmployee(rs);
emps.add(emp);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);
}
for(employees emp:emps){
System.out.println(emp);
}
}
public static employees resultSetToEmployee(ResultSet rs){
employees emp=null;
try {
int index=1;
emp=new employees();
emp.setUserid(rs.getInt(index++));
emp.setEmployee_id(rs.getString(index++));
emp.setLast_name(rs.getString(index++));
emp.setSalary(rs.getString(index++));
emp.setDepartment_id(rs.getString(index++));
} catch (SQLException e) {
e.printStackTrace();
}
return emp;
}
}

JDBC连接数据库方法的封装,以及查询数据方法的封装的更多相关文章

  1. Java学习-029-JSON 之三 -- 模仿 cssSelector 封装读取 JSON 数据方法

    前文简单介绍了如何通过 json-20141113.jar 提供的功能获取 JSON 的数据,敬请参阅:Java学习-028-JSON 之二 -- 数据读取. 了解学习过 JQuery 的朋友都知道, ...

  2. Hibernate原生SQL查询数据转换为HQL查询数据方法

    HQL形式:(构造方法不支持timestamp类型) public List<Device> queryByMatherBoardId(String matherBoardId) { St ...

  3. Spring查询方法的注入 为查询的方法注入某个实例

    //这里是客户端的代码 当调用CreatePersonDao这个抽象方法或者虚方法的时候由配置文件返回指定的实例 为查询的方法注入某个实例 start static void Main(string[ ...

  4. SpringBoot JDBC 源码分析之——NamedParameterJdbcTemplate 查询数据返回bean对象

    1,NamedParameterJdbcTemplate 查询列表 /***测试***/ public void queyBeanTest(){ String s = "select * f ...

  5. Sqlite数据库添加数据以及查询数据方法

    只是两个添加查询方法而已,怕时间长不用忘了

  6. 用python实现数据库查询数据方法

    哈喽,好久没来了,最近搞自动化发现了很多代码弯路,特别分享出来给能用到的朋友 因为公司业务的关系,每做一笔功能冒烟测试,我们就要对很多的数据库表中的字段进行校验,当时我就想反正总是要重复的运行这些SQ ...

  7. JDBC查询数据实例

    在本教程将演示如何在JDBC应用程序中,查询数据库的一个表中数据记录. 在执行以下示例之前,请确保您已经准备好以下操作: 具有数据库管理员权限,以在给定模式中数据库表中查询数据记录. 要执行以下示例, ...

  8. SSH框架的多表查询(方法二)增删查改

     必须声明本文章==>http://www.cnblogs.com/zhu520/p/7773133.html  一:在前一个方法(http://www.cnblogs.com/zhu520/p ...

  9. SSH框架的多表查询(方法二)

     必须声明本文章==>http://www.cnblogs.com/zhu520/p/7773133.html  一:在前一个方法(http://www.cnblogs.com/zhu520/p ...

随机推荐

  1. 高阶篇:4.3)FTA故障树分析法-DFMEA的另外一张脸

    本章目的:明确什么是FTA,及与DFMEA的关系. 1.FTA定义 故障树分析(FTA) 其一:故障树分析(Fault Tree Analysis,简称FTA)又称事故树分析,是安全系统工程中最重要的 ...

  2. Go语言包和文件

    工作空间 Go语言工作空间:编译工具对源码目录有严格要求,每个工作空间 (workspace) 必须由bin.pkg.src三个目录组成. src ---- 项目源码目录,里面每一个子目录,就是一个包 ...

  3. flask开发笔记

    目录 虚拟环境 Debug模式 配置文件 url传入参数 url反转 重定义向 模板 创建 jinjia2语法 模板继承 flash 加载静态文件 MySQL数据库命令 配置 更新.提交.删除 模型操 ...

  4. acl权限使用

    1.acl的设置技巧 *setfacl 用法: setfactl [-bkRd] [{-m|-x} acl参数] 目标文件名 -m:设置后续的acl参数给文件使用,不可与-x合用 -x:删除后续的ac ...

  5. mybatis映射文件模板mapper.xml格式

    1.定义基础的映射 对象DO与数据库字段间的映射 <resultMap id="UserResult" type="UserDO"> <res ...

  6. openerp学习笔记 按客户电话、名称模糊查找选择客户(name_search)及客户名称自定义显示(name_get)

    #同时按手机.电话.名称模糊查找选择客户    def name_search(self, cr, user, name, args=None, operator='ilike', context=N ...

  7. jQuery 学习笔记(TryjQuery)

    第一集.页面加载完成后执行 js 代码: $(document).ready(function(){ $("h1").text("Where to?"); }) ...

  8. Oracle 行列转换总结

    行列转换包括以下六种情况:*列转行*行转列*多列转换成字符串*多行转换成字符串*字符串转换成多列*字符串转换成多行 下面分别进行举例介绍. 首先声明一点,有些例子需要如下10g及以后才有的知识:a.掌 ...

  9. Linux修改BASH命令提示符

    Shell命令提示符及颜色是由PS1来配置: 1.其中PS1常用的参数含义如下: \d :#代表日期,格式为weekday month date,例如:"Mon Aug 1" \H ...

  10. [转载+补充][PY3]——环境配置(2)——windows下安装pycharm并连接Linux的python环境

    原文地址:<你所会用到的Python学习环境和工具> 1. 下载安装Pycharm专业版 具体方法略.Pycharm5激活方法参考http://www.cnblogs.com/snsdzj ...