单独使用JDBC编程

一.jdbc编程步骤

1、 加载数据库驱动

2、 创建并获取数据库链接

3、 创建jdbc statement对象

4、 设置sql语句

5、 设置sql语句中的参数(使用preparedStatement)

6、 通过statement执行sql并获取结果

7、 对sql执行结果进行解析处理

8、 释放资源(resultSet、preparedstatement、connection)

Public static void main(String[] args) {
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            
            try {
                //加载数据库驱动
                Class.forName("com.mysql.jdbc.Driver");
                
                //通过驱动管理类获取数据库链接
                connection =  DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "mysql");
                //定义sql语句 ?表示占位符
            String sql = "select * from user where username = ?";
                //获取预处理statement
                preparedStatement = connection.prepareStatement(sql);
                //设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
                preparedStatement.setString(1, "王五");
                //向数据库发出sql执行查询,查询出结果集
                resultSet =  preparedStatement.executeQuery();
                //遍历查询结果集
                while(resultSet.next()){
                    System.out.println(resultSet.getString("id")+"  "+resultSet.getString("username"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                //释放资源
                if(resultSet!=null){
                    try {
                        resultSet.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(preparedStatement!=null){
                    try {
                        preparedStatement.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(connection!=null){
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }

        }

 

问题总结:

1、程序中存在硬编码(数据驱动加载,创建数据连接、sql语句),不利于系统维护。

设想解决硬编码:可以sql语句等信息配置在xml中。

 

2、数据库连接使用时打开不时立即关闭,频繁开关连接对数据库资源是一种浪费。

设想解决方案:使用数据库连接池。

 

3、向preparedStatement设置参数时 将参数下标 号(从1开始)硬编码在代码,并且将向占位符号设置的参数也硬编码了。

设想解决方案:可以自动通过程序将java类型对象映射到preparedStatement中。

 

4、从Resultset中取出结果集进行遍历,将列名硬编码

设想解决方案:可以自动通过程序将sql查询结果集映射到时java对象中,自动完成将sql查询的列值构造成一个java对象。

 

posted @ 2018-01-10 18:40  无~所~谓  阅读(174)  评论(0编辑  收藏  举报