好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

JDBC(重点)

JDBC(重点)

数据库驱动

驱动 : 声卡、显卡、数据库

JDBC

SUN公司为了简化开发人员的(对数据库的统一)操作,提高了一个(java操作数据库的)规范,俗称 JDBC

这些规范的具体实现由具体的厂商去做。

对于开发人员来说,只需要掌握JDBC接口的操作即可

? java.sql

? javax.sql

还需要导入一个数据库驱动包 mysql-connector-java-5.1.47.jar :

https://mvnrepository测试数据/artifact/mysql/mysql-connector-java/5.1.47

第一个JDBC程序

创建一个普通项目

创建测试数据库

 CREATE DATABASE jdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci;
USE jdbcStudy;
CREATE TABLE users(
    id INT PRIMARY KEY,
    NAME VARCHAR(40),
    PASSWORD VARCHAR(40),
    email VARCHAR(60),
    birthday DATE
);
INSERT INTO users(id,NAME,PASSWORD,email,birthday)
VALUES(1,‘zhangsan‘,‘123456‘,‘zs@sina测试数据‘,‘1980-12-04‘),
(2,‘lisi‘,‘123456‘,‘lisi@sina测试数据‘,‘1981-12-04‘),
(3,‘wangwu‘,‘123456‘,‘wangwu@sina测试数据‘,‘1979-12-04‘);
 

导入包 : mysql-connector-java-5.1.47.jar

编写测试代码

步骤总结:

1.加载驱动

2.连接数据库 DriverManager

3.获得执行sql的对象 Statement

4.获得返回的结果集

5.释放连接

 public class jdbcTest01 {
    public static void main(String[] args) throws Exception {
        // 1、加载驱动
        Class.forName("com.mysql.jdbc.Driver");   // 固定写方,加载驱动
        // 2、用户信息和 url
        //        useUnicode=true               支持中文编码
        //        characterEncoding=utf8        设置中文集为utf8
        //        useSSL=true                   设置安全的连接
        String url="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";    //由于我的mysql版本较高,不能安全连接
        String username="root";
        String password="123456";
        // 3、连接 数据库对象 Connection 代表数据库
        Connection conn = DriverManager.getConnection(url,username,password);
        // 4、执行SQL对象Statement 执行SQL的对象
        Statement stmt = conn.createStatement();
        //5、执行SQL的对象 去 执行SQL 可能存在的结果 查看返回结果
        String sql = "SELECT * FROM users";
        ResultSet rs = stmt.executeQuery(sql);   // 返回结果集合
        while (rs.next())
        {
            System.out.println("id="+rs.getObject("id"));
            System.out.println("name="+rs.getObject("NAME"));
            System.out.println("pwd="+rs.getObject("PASSWORD"));
            System.out.println("email="+rs.getObject("email"));
            System.out.println("birth="+rs.getObject("birthday"));
        }
        // 6、释放资源
        rs.close();
        stmt.close();
        conn.close();

    }
}
 

DriverManager

 // DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");   // 固定写方,加载驱动
Connection conn = DriverManager.getConnection(url,username,password);
// conn 代表数据库
// 数据库设置自动提交
// 事务提交
// 事务回滚
conn.rollback();
conn测试数据mit();
conn.setAutoCommit();
 

URL

 String url="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
//MySQL  端口号:3306
//jdbc:mysql://主机地址:端口号/数据库名?参数1&参数2&参数3
//oralce 端口号:1521
// jdbc:oracle:thin:@主机地址:1521:sid
 

Statement 执行sql的对象

 String sql = "SELECT *FROM users"; //编写SQL
Statement stmt = conn.createStatement();// 执行SQL对象Statement 执行SQL的对象
stmt.executeQuery(); //查询操作返回 ResultSet
stmt.execute();      // 执行任何SQL
stmt.executeUpdate(); // 更新、插入、删除   返回一个受影响的行数
 

ResultSet 查询的结果集 :封装了所有的查询结果

获得指定的数据类型
 rs.getObject();  // 在不知道列类型的情况下使用
// 如果知道列的类型就使用指定的类型
rs.getString();
rs.getInt();
rs.getFloat();
rs.getDate();
......
 
遍历、指针
 rs.beforeFirst();      // 移动到最前面
rs.afterLast();       // 移动到最后面
rs.next();           // 移动到下一个数据
rs.previous();      // 移动到前一行
rs.absolute(row);  // 移动到指定行
 

释放资源

 rs.close();
stmt.close();
conn.close();  // 耗资源,用完关掉!
 

statement对象

Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。

Statement对象的executeUpdate方法,用于向数据库发送增、删、改的sqli语句,executeUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。

Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象。

CRUD操作-create 使用executeUpdate(String sql) 方法完成数据添加操作,实例操作:
 Statement st = conn.createstatement();
String sq1 = "insert into user(.... ) values(.....) ";
int num = st.executeUpdate(sql);
if(num>0){
    system.out.println("插入成功!! ! ");
}
 
CRUD操作-delete

使用executeUpdate(String sql) 方法完成数据删除操作,实例操作:

 Statement st = conn.createstatement();
string sq1 = "delete from user where id=1";
int num = st.executeUpdate(sql);
if(num>0){
    system.out.println("删除成功!! ! ");
}
 
CRUD操作-update

使用executeUpdate(String sql) 方法完成数据修改操作,实例操作:

 Statement st = conn.createstatement();
string sq1 = "update user set name=‘‘ where name=‘‘";
int num = st.executeUpdate(sql);
if(num>0){
    system.out.println("修改成功!! ! ");
}
 
CRUD操作-read

使用executeQuery(String sql) 方法完成数据修改操作,实例操作:

 Statement st = conn.createstatement();
string sq1 = "select * from user where id=1";
ResultSet rs = st.executeQuery(sql);
while(rs.next(){
    //根据获取列的数据类型,分别调用rs的响应方法映射到java对象中
}
 

编写工具类

创建资源文件 db.properties

 url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username = root
password = 123456
driver = com.mysql.jdbc.Driver
 

新建工具类,写有连接数据库使用的代码,方便其他类调用 jdbcUtils.java

 public class jdbcUtils {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
        try {
            InputStream in = jdbcUtils.class.getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //驱动只需要加载一次
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws Exception{
        return DriverManager.getConnection(url,username,password);
    }
    //释放连接资源
    public static void release(Connection conn, Statement st, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
 

进行增删改测试

 public static void main(String[] args) {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            conn = jdbcUtils.getConnection();
            st = conn.createStatement();  //创建Statement对象
            /* //新增
            String sql = "INSERT INTO users (id,`NAME`,`PASSWORD`,`email`,`birthday`)" +
                    "VALUES(4,‘小李‘,‘123456‘,‘12344555@qq测试数据‘,‘2020-1-1‘)";*/
            /*//删除
            String sql = "delete from users where id = ‘4‘";*/
            String sql = "update users set name = ‘saxon‘ where id = ‘1‘";
            int i =  st.executeUpdate(sql);
            if(i>0){ //如果数据大于0
                System.out.println("插入成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jdbcUtils.release(conn,st,rs);
        }
    }
 

进行查询测试

 public static void main(String[] args) {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            conn = jdbcUtils.getConnection();
            st = conn.createStatement();  //创建Statement对象
            String sql = "select * from users";
            rs = st.executeQuery(sql);
            while (rs.next()){
                System.out.println("name="+rs.getString("NAME"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jdbcUtils.release(conn,st,rs);
        }
    }
 

JDBC(重点)

标签:cst   strong   响应   use   out   test   res   mvn   回滚   

查看更多关于JDBC(重点)的详细内容...

  阅读:23次

上一篇: MySQL事务ACID特性

下一篇:MySQL区分大小写