029 JDBC 开发

简书:http://www.jianshu.com/p/9b2601c79489

1. 开发流程

// 注册了两次驱动程序,造成浪费,推荐使用反射
// DriverManager.registerDriver(new Driver());
// new Driver();
// 1. 注册JDBC的驱动
Class.forName("com.mysql.jdbc.Driver");

// 2. 获得数据库连接,DriverManager类中的静态方法
String url = "jdbc:mysql://localhost:3306/luoDatabase";
String userName = "Luo";
String password = "lingli520";
Connection connection = DriverManager.getConnection(url, userName, password);
System.out.println(connection);     // 返回的该接口的实现类

// 3. 获得语句执行平台,通过数据库连接对象,获取到SQL语句的执行者对象
Statement statement = connection.createStatement();

// 4. 执行SQL语句
statement.executeUpdate("INSERT INTO users(uId, uName,uAddress) VALUES (10,'luo','江西'),(11,'wangge','江西2'),(12,'Luo','江西3'),(13,'Luo_Luo','江西4');");

// 5. 结果处理

// 6. 释放一堆资源
statement.close();  // 释放执行者对象
connection.close(); // 释放连接对象

2. 查询

// 查询数据
ResultSet resultSet = statement.executeQuery("SELECT * FROM users;");

// 5. 结果处理
while (resultSet.next()) {
    System.out.println(resultSet.getInt("uId") + "\t" + resultSet.getString("uName") + "\t" + resultSet.getString("uAddress"));
}

// 6. 释放一堆资源
resultSet.close();

3. SQL注入攻击案例

statement.executeQuery("SELECT * FROM users where uName = '" + name + "' AND uPassword = '" + pwd + "';");
// 这个时候只需要输入pwd的时候注入一些SQL代码就能达到SQL注入攻击的目的

4. 防止注入攻击(采用占位符?)

采用PreparedStatement(实现SQL的预编译,多次高效执行SQL语句)
statement.executeQuery("SELECT * FROM users where uName = ? AND uPassword = ?;");

5. 工具类

public class JdbcUtils {
    private static Connection con;

    private JdbcUtils() {
    }

    static {
        try {
            // 1. 添加MySql驱动
            Class.forName("com.mysql.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/luoDatabase";
            String userName = "Luo";
            String password = "lingli520";

            // 2. 获取一个连接
            con = DriverManager.getConnection(url, userName, password);

        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e + "连接失败");
        }

    }

    /**
     * 发起获得一个连接
     *
     * @return 返回数据库连接
     */
    public static Connection getConnection() {
        return con;
    }

    /**
     * 关闭资源类
     *
     * @param con   数据库连接对象
     * @param state state
     * @param rs    结果集
     */
    public static void close(Connection con, Statement state, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (state != null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

6. 配置文件的设置

# 1. 配置文件放在bin目录下
# 2. 配置文件名字以properties为扩展名(database.properties)
# 3. 数据以键值对的形式存储

7. 读取配置文件的工具类

/*
 *  编写数据库连接的工具类,JDBC工具类
 *  获取连接对象采用读取配置文件方式
 *  读取文件获取连接,执行一次,static{}
 */
public class JDBCUtilsConfig {
    private static Connection con ;
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    static{
        try{
            readConfig();
            Class.forName(driverClass);
            con = DriverManager.getConnection(url, username, password);
        }catch(Exception ex){
            throw new RuntimeException("数据库连接失败");
        }
    }

    private static void readConfig()throws Exception{
        InputStream in = JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
         Properties pro = new Properties();
         pro.load(in);
         driverClass=pro.getProperty("driverClass");
         url = pro.getProperty("url");
         username = pro.getProperty("username");
         password = pro.getProperty("password");
    }

    /**
     * 获取数据库的连接对象
     */
    public static Connection getConnection(){
        return con;
    }

    /**
     * 关闭资源类
     *
     * @param con   数据库连接对象
     * @param state state
     * @param rs    结果集
     */
    public static void close(Connection con, Statement state, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (state != null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

总结

JDBC的代码冗余很多,因此下一篇将介绍简化版的Apache的DBUtils.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值