软件工程实践JDBC笔记

软件工程实践JDBC笔记

案例1:使用JDBC直接访问mysql数据库;

代码:TestJDBC.java

1、加载mysql

/ 1.加载驱动mysql8.0版本
Class.forName("com.mysql.cj.jdbc.Driver");
// mysql5.71版本
// Class.forName("com.mysql.jdbc.Driver");

2、建立连接

/ 2.建立连接
conn = DriverManager.getConnection("jdbc:mysql:///myschool?serverTimezone=Hongkong", "root", "cwc182534Castiel");

“jdbc:mysql://myschool?serverTimezone=Hongkong”, “用户名” , “密码”

myschool是database

?后给变量赋值

3、编写SQL语句

// 3.编写SQL语句
String sql = "insert into users(username,password) values('Rose','123')";

4、创建命令对象

// 4.创建命令对象
Statement stmt = conn.createStatement();

5、执行命令对象

// 5.执行命令对象
stmt.executeUpdate(sql);

6、查询语句

// 编写SQL语句
            String selectUser = "select * from users";
            // 执行并接收查询结果
            ResultSet rest = stmt.executeQuery(selectUser);
//            System.out.println("rest = " + rest);

7、关闭连接

// 循环读出数据
    while (rest.next()) {
        int id = rest.getInt("id");
        String username = rest.getString("username");
        System.out.println(id + " " + username);
    }
} catch (Exception e) {

    e.printStackTrace();
} finally {
    try {
        // 关闭连接
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

循环读出数据,记得进行异常处理

案例2:预编译(参数化)SQL命令

TestParameters

1、编写带参数的SQL语句

// 3.编写带参数的SQL语句	
String sql = "insert into users(username,password) values(?,?)";

用? ?来代替

2、预编译SQL语句

// 4.预编译SQL语句
PreparedStatement stmt = conn.prepareStatement(sql);
System.out.println("stmt = " + stmt);

用PreparedStatement预编译

输出:

stmt = com.mysql.cj.jdbc.ClientPreparedStatement: insert into users(username,password) values(** NOT SPECIFIED , NOT SPECIFIED **)

3、赋予各字段相应的参数

// 5.赋予各字段相应的参数
stmt.setString(1, "Mike");
stmt.setString(2, "345");
System.out.println("stmt = " + stmt);

通过setString来赋予字段相应的参数

输出:

stmt = com.mysql.cj.jdbc.ClientPreparedStatement: insert into users(username,password) values(‘Mike’,‘345’)

4、执行命令对象

// 6.执行命令对象
stmt.executeUpdate();

5、执行参数化的查询语句(同上)

// 1.编写参数化SQL语句
String selectUser = "select * from users where id=?";
// 2.预编译
PreparedStatement pstmt = conn.prepareStatement(selectUser);
System.out.println("pstmt = " + pstmt);
// 3.赋予各字段相应的参数
pstmt.setInt(1, 2);
System.out.println("pstmt = " + pstmt);
// 执行并接收查询结果
ResultSet rest = pstmt.executeQuery();

案例3:封装JDBC为DBUtil数据库访问辅助类

数据库访问辅助类(数据访问助手)

CRUD–共性,访问数据库

把数据库访问独立出来,把数据库访问封装到一个DBUtil类中,

干净的访问数据库的辅助类DBUtil类。

代码:DBUtil

1、加载数据驱动类
public DBUtil() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            // Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
2、建立连接对象
public Connection getConnection() {
        try {
            return DriverManager.getConnection("jdbc:mysql:///myschool?serverTimezone=Hongkong", "root", "cwc182534Castiel");
            // return DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool","root","root");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
3、执行更新数据库的SQL命令
public boolean execUpdate(String sql) {
        conn = getConnection();
        try {
            Statement stmt = conn.createStatement();
            if (stmt.executeUpdate(sql) > 0) {
                return true;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

stmt.executeUpdate(sql)返回的是一个int整型,代表更新了(应影响了)多少行的数据。

java.sql.Statement public abstract int executeUpdate(String sql) throws java.sql.SQLException

4、执行查询
// 4.执行查询
    public ResultSet execQuery(String sql) {
        conn = getConnection();
        try {
            Statement stmt = conn.createStatement();
            return stmt.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

ResultSet是executeQuery的返回类型

5、关闭数据库
// 5.关闭数据库
public void DBclose() {
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

注意异常处理!(SQLException)

代码:TestDBUtil.java

调用DBUtil中的方法
public class TestDBUtil {
    public static void main(String[] args) {

        // 1. 创建DBUtil对象
        DBUtil db = new DBUtil();

        // 2.编写SQL语句
        String sql = "insert into users(username,password) values('Rain','123')";

        // 3.执行DBUtil的方法
        db.execUpdate(sql);

        / 查询
        // 1.编写SQL语句
        String selectUser = "select * from users";

        // 2.执行并接收查询结果
        ResultSet rest = db.execQuery(selectUser);
        try {
            while (rest.next()) {
                int id = rest.getInt("id");
                String username = rest.getString("username");
                System.out.println(id + " " + username);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

案例4:在DBUtil数据库访问辅助类中预编译SQL命令

代码:DBUtilPara

1、加载数据驱动类(同上)
2、建立连接对象(同上)
3、执行更新数据库的预编译SQL命令
public boolean execUpdate(String sql, Object[] params) {
        conn = getConnection();
        try {

            // 1.创建预编译命令对象
            PreparedStatement stmt = conn.prepareStatement(sql);

            // 2.设置为字段匹配参数
            for (int i = 0; params != null && i < params.length; i++) {

                Object param = params[i];
                if (param instanceof Integer) {
                    stmt.setInt(i + 1, Integer.parseInt(param.toString()));
                }
                if (param instanceof Float) {
                    stmt.setFloat(i + 1, Float.parseFloat(param.toString()));
                }
                if (param instanceof Double) {
                    stmt.setDouble(i + 1, Double.parseDouble(param.toString()));
                }
                if (param instanceof String) {
                    stmt.setString(i + 1, param.toString());
                }
            }

            // 3.执行预编译命令
            if (stmt.executeUpdate() > 0) {
                return true;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
  1. 使用PreparedStatement来存储要预编译的sql语句;

  2. 根据传进来的Objectp[] 数组 params,一个一个读取,根据不同的数据类型,

    来调用PreparedStatemnet的对于不同数据的set方法来填充预编译语句;

  3. 有操作就进行预编译

4、执行预编译查询
public ResultSet execQuery(String sql, Object[] params) {
        conn = getConnection();
        try {
            // 1.创建预编译命令对象
            PreparedStatement stmt = conn.prepareStatement(sql);
            // 2.设置为字段匹配参数
            for (int i = 0; params != null && i < params.length; i++) {

                Object param = params[i];
                if (param instanceof Integer) {
                    stmt.setInt(i + 1, Integer.parseInt(param.toString()));
                }
                if (param instanceof Float) {
                    stmt.setFloat(i + 1, Float.parseFloat(param.toString()));
                }
                if (param instanceof Double) {
                    stmt.setDouble(i + 1, Double.parseDouble(param.toString()));
                }
                if (param instanceof String) {
                    stmt.setString(i + 1, param.toString());
                }
            }

            // 3.执行预编译命令
            return stmt.executeQuery();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

(同3中的执行更新数据库的预编译SQL命令,对于传入的Object[] params数组里的数据一一读入,一一处理)

5、关闭数据库(同上)

代码:TestParaDBUtil

调用DBUtilPara中的方法
//该类使用参数化的DBUtil类,读取DBUtilPara类
public class TestParaDBUilt {

    public static void main(String[] args) {
        // 1. 创建DBUtil对象
        DBUtilPara db = new DBUtilPara();

        // 2.编写SQL语句
        String sql = "insert into users(username,password) values(?,?)";

        // 3.封装参数
        Object[] params = { "Martin", "3333" };

        // 4.执行DBUtil的方法
        db.execUpdate(sql, params);

        / 查询
        // 1编写SQL语句
        String selectUser = "select * from users where id=?";

        // 2.封装参数
        Object[] selparams = { 2 };

        // 3.执行并接收查询结果
        ResultSet rest = db.execQuery(selectUser, selparams);

        try {
            while (rest.next()) {
                int id = rest.getInt("id");
                String username = rest.getString("username");
                System.out.println(id + " " + username);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

注意要预编译语句用??处理

案例5:将连接字符写入.properities配置文件

代码:DBUtilConfig

1、静态代码块(类初次被加载时执行且仅会被执行一次)
//静态代码块,在类初次被加载的时候执行且仅会被执行一次
    static {
        try {
            // 在Java中,其配置文件常为.properties文件,是以键值对的形式进行参数配置的。
            // 用Properties类来读取.properties文件数据

            // 步骤说明:1.调用类加载器的方法加载资源,返回的字节流
            // DBUtilConfig.class是获得当前对象所属的class对象
            // getClassLoader()是取得该Class对象的类装载器
            // getResourceAsStream(“database.properties”)
            InputStream ins = DBUtilConfig.class.getClassLoader().getResourceAsStream("database.properties");

            // 2.使用Properties类,从.properties属性文件对应的文件输入流中,加载属性列表到Properties类对象,
            Properties props = new Properties();
            props.load(ins);

            // 3.通过getProperty方法用指定的键在此属性列表中搜索属性, 动态获取.properties配置文件中的数据
            driver = props.getProperty("driver");
            url = props.getProperty("url");
            username = props.getProperty("username");
            password = props.getProperty("password");

            // 4、加载驱动
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值