【转载】使用注解和反射实现通用性…

来源:互联网 发布:淘宝折扣网站取名 编辑:程序博客网 时间:2024/06/07 03:19
本文出处:http://ibeginner.sinaapp.com/index.php?m=Home&c=Index&a=detail&id=c5f98d452938346e3ec7c0d3630c6a62

接着上篇:使用注解和反射实现通用性的 jdbc操作数据库之最简单的 jdbc 操作_1

3,得到connection 之后就可以使用它来获取PreparedStatement,然后执行 SQL 语句,请看下面的代码;

public class CoreDao{

 

      // 定义数据库的链接

      private Connection conn;

      // 定义sql语句的执行对象

      private PreparedStatement pstmt;

      // 定义查询返回的结果集合

      private ResultSet resultSet;

 

 

      public void list(){

            conn =DBConnUtils.getConnection();

            Stringsql = "select *from user";

            try {

                  //  预编译 SQL 语句

                  pstmt conn.prepareStatement(sql);

                  //  执行查询

                  resultSet pstmt.executeQuery();

                  while (resultSet.next()){

                        System.out.println("username= " resultSet.getString("username"

                                    ",birth = " resultSet.getDate("birth"

                                    ",detail_time = " resultSet.getDate("detail_time"));

                  }

            catch (SQLExceptione) {

                  e.printStackTrace();

            }

      }

    

      

      public static void main(String[]args) {

            new CoreDao().list();

      }

}

运行 main 方法,看到如下打印信息;

【转载】使用注解和反射实现通用性的 <wbr>jdbc操作数据库之最简单的 <wbr>jdbc <wbr>操作_2

可以看到代码正确获取到数据库的数据库;

 

4关闭数据库链接释放资源

         有经验的开发者一眼就能看出上述代码的问题了!!!不知道你是否也发现了呢?代码并没有关闭 connection 释放资源。如果不释放并且随着访问量的增加 connection 会越来越多,导致服务器内存被占满,出现内存溢出问题!!所以记得一定要关闭数据库连接。

public void list(){

            conn =DBConnUtils.getConnection();

            Stringsql = "select *from user";

            try {

                  //…… 代码同上,不在列出

            catch (SQLExceptione) {

                  e.printStackTrace();

            finally  //关闭数据库连接释放资源

                  try {

                     if (null !=pstmt) {

                          pstmt.close();

                     }

               catch (SQLExceptione) {

                     e.printStackTrace();

               }

               try {

                     if (null !=pstmt) {

                          conn.close();

                     }

               catch (SQLExceptione) {

                     e.printStackTrace();

               }

            }

      }

 

最后给出完成的增上改查的代码示例;

package com.ubuntuvim.core;


 

public class CoreDao{

 

      // 定义数据库的链接

      private Connection conn;

      // 定义sql语句的执行对象

      private PreparedStatement pstmt;

      // 定义查询返回的结果集合

      private ResultSet resultSet;

      

      private int commId =35;

 

      

      //  新增数据

      @Test

      public void add(){

            conn =DBConnUtils.getConnection();

            Stringsql = " insertinto user(id, username, birth) values(?, ?, ?)";

            try {

                  //  预编译 SQL 语句

                  pstmt conn.prepareStatement(sql);

                  pstmt.setInt(1, commId);  //为了方便测试直接指定了 id,实际使用中通常不需要指定 id,默认设置为自增类型即可

                  pstmt.setString(2, "新增测试");  //1表示 SQL 语句中的第一个问号

                  pstmt.setDate(3, new Date(System.currentTimeMillis()));

                  //  执行SQL

                  int i= pstmt.executeUpdate();

                  // 提交事务

                  conn.commit();

                  if (i> 0)

                        System.out.println(新增成功...");

            catch (SQLExceptione) {

                  e.printStackTrace();

                  // 出错回滚事务

                  try {

                        conn.rollback();

                  catch (SQLExceptione1) {

                        e1.printStackTrace();

                  }

            finally  //关闭数据库连接释放资源

                  try {

                        if (null != pstmt){

                              pstmt.close();

                        }

                  catch (SQLExceptione) {

                        e.printStackTrace();

                  }

                  try {

                        if (null != pstmt){

                              conn.close();

                        }

                  catch (SQLExceptione) {

                        e.printStackTrace();

                  }

            }

      }

 

      //  测试查询

      public void list(){

            

            conn =DBConnUtils.getConnection();

            Stringsql = "select *from user";

            try {

                  //  预编译 SQL 语句

                  pstmt conn.prepareStatement(sql);

                  //  执行查询

                  resultSet pstmt.executeQuery();

                  while (resultSet.next()){

                        

                        System.out.println("id= " resultSet.getInt("id")+ ",username = " resultSet.getString("username"

                                    ",birth = " resultSet.getDate("birth"

                                    ",detail_time = " resultSet.getObject("detail_time"));

                  }

            catch (SQLExceptione) {

                  e.printStackTrace();

            finally  //关闭数据库连接释放资源

                  try {

                        if (null != pstmt){

                              pstmt.close();

                        }

                  catch (SQLExceptione) {

                        e.printStackTrace();

                  }

                  try {

                        if (null != pstmt){

                              conn.close();

                        }

                  catch (SQLExceptione) {

                        e.printStackTrace();

                  }

            }

      }

      

      //  测试更新

      public void update(){

            conn =DBConnUtils.getConnection();

            Stringsql = " updateuser set username = ? where id = ?";

            try {

                  //  预编译 SQL 语句

                  pstmt conn.prepareStatement(sql);

                  pstmt.setString(1, "update_test"); //

                  pstmt.setInt(2, commId);  //

                  //  执行更新

                  int i= pstmt.executeUpdate();

                  if (i> 0)

                        System.out.println(更新成功...");

                  

                  //记得要提交

                  conn.commit();

            catch (SQLExceptione) {

                  e.printStackTrace();

                  //  如果更新出错,执行回滚

                  try {

                        conn.rollback();

                  catch (SQLExceptione1) {

                        e1.printStackTrace();

                  }

            finally  //关闭数据库连接释放资源

                  try {

                        if (null != pstmt){

                              pstmt.close();

                        }

                  catch (SQLExceptione) {

                        e.printStackTrace();

                  }

                  try {

                        if (null != pstmt){

                              conn.close();

                        }

                  catch (SQLExceptione) {

                        e.printStackTrace();

                  }

            }

      }

      

      //  测试删除,删除的代码与更新的代码基本是一样的,

      //  只是 SQL 的不同而已,所以可以把更新和删除合并为一个方法,

      //  会在后续的文章实现合并

      public void del(){

            conn =DBConnUtils.getConnection();

            Stringsql =  deletefrom user where id = ?";

            try {

                  //  预编译 SQL 语句

                  pstmt conn.prepareStatement(sql);

                  pstmt.setInt(1, commId);  //删除 id 35的数据

                  //  执行更新

                  int i= pstmt.executeUpdate();

                  if (i> 0)

                        System.out.println(删除成功...");

                  

                  //记得要提交

                  conn.commit();

            catch (SQLExceptione) {

                  e.printStackTrace();

                  //  如果更新出错,执行回滚

                  try {

                        conn.rollback();

                  catch (SQLExceptione1) {

                        e1.printStackTrace();

                  }

            finally  //关闭数据库连接释放资源

                  try {

                        if (null != pstmt){

                              pstmt.close();

                        }

                  catch (SQLExceptione) {

                        e.printStackTrace();

                  }

                  try {

                        if (null != pstmt){

                              conn.close();

                        }

                  catch (SQLExceptione) {

                        e.printStackTrace();

                  }

            }

      }

    

      

      public static void main(String[]args) {

            new CoreDao().list();

            new CoreDao().add();

            new CoreDao().list();

            new CoreDao().update();

            new CoreDao().list();

            new CoreDao().del();

            new CoreDao().list();

      }

}

 

 【转载】使用注解和反射实现通用性的 <wbr>jdbc操作数据库之最简单的 <wbr>jdbc <wbr>操作_2

到此相信你已经学会最简单的 jdbc 操作数据了。对数据库的操作基本上都是在增删改查的基本上添加复杂的业务逻辑。当然,使用 jdbc 也可调用存储过程,但是本系列文章暂时不讨论,本系列文章主要讲讲怎么从简单的 jdbc 一步步提升为基于注解的通用性 jdbc 操作。

      最终想达到的目标是:

1.   查询能返回 list  model对象数组

2.   新增方法只需要传入 model对象即可

3.   不需要手动一个个写 getter/settersptmt.setXxx()

4.   怎么使用 java 注解并解析定义的注解(仿照 java  Persistence 类)

如果需要完成的项目请从我的 github 空间上下载,网址为:https://github.com/ubuntuvim/jdbc_db_converstion

0 0
原创粉丝点击