JDBC1

概念

JDBC:Java DataBase Connectivity Java数据库连接,Java语言操作数据库。
JDBC本质:是官方定义的一套操作所有关系型数据库的规则,即接口。各个数据库产商去实现这套接口,提供数据库驱动jar包,可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类

入门

步骤:
1️⃣导入驱动jar包
复制jar包到项目的libs目录下
add as library
2️⃣注册驱动
3️⃣获取数据库连接对象 Connection
4️⃣定义sql
5️⃣获取执行sql语句的对象 Statement
6️⃣执行sql,返回结果
处理结果
释放资源

public class jdbcdemo01 {
    public static void main(String[] args) throws Exception {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取数据库连接对象
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root");
        //定义sql语句
        String sql ="update account set balance = 500 where id =1";
        //获取执行sql对象
        Statement stmt = conn.createStatement();
        //执行sql
        int count = stmt.executeUpdate(sql);
        System.out.println(count);
        stmt.close();
        conn.close();
    }

各个对象

DriverManager:驱动管理对象

功能:
注册驱动 Class.forName(“com.mysql.jdbc.Driver”);
获取数据库连接
注意:MySQL5之后的驱动jar包可以省略注册驱动的步骤

Connection:数据库连接对象

方法:getConnection(String url,String user,String password)
参数:
url:指定连接的路径
语法:jdbc:mysql://ip地址(域名):端口号/数据库名称
“jdbc:mysql://localhost:3306/db3”, “root”, “root”
如果是本机mysql服务器可以简写jdbc:mysql://数据库名称
**user:**用户名
**password:**密码
功能:
1️⃣获取执行sql的对象
Statement createStatement()
PreparedStatement preparedStatement(String sql)
2️⃣管理事务:
①开启事务:void setAutoCommit(boolean autoCommit)调用该方法设置参数为false,即开启事务
②提交事务:commit()
③回滚事务:rollback()

Statement :执行sql对象

1️⃣执行sql
①boolean execute(String sql):可以执行任意的sql
②int executeUpdate(String sql):执行DML(insert/update/delete)语句、DDL(create/alter/drop)语句 返回值:影响的行数,通过这个影响的行数判断DML语句是否执行成功,返回值>0执行成功。
③ResultSet executeQuery(String sql):执行DQL(select)语句
2️⃣练习:
①account表 添加一条记录
②account表 修改记录
③account表 删除一条记录

/*
    添加一条记录 insert语句
 */
public class jdbcdemo02 {
    public static void main(String[] args) {
        Statement stmt= null;
        Connection conn =null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String sql= "insert into account values(null,'jackboy',3000)";
            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root");
                //获取执行sql的对象
                stmt = conn.createStatement();
                //执行sql语句
                int count = stmt.executeUpdate(sql);
                System.out.println(count);
                if(count>0){
                    System.out.println("添加成功");
                }else{
                    System.out.println("添加失败");
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            //释放资源
            //避免空指针异常
            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
/*
    account表 修改记录
 */
public class jdbcdemo03 {
    public static void main(String[] args) {
        Connection conn= null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root");
                //定义sql
                String sql ="update account set balance = 1500 where id =3";
                 stmt = conn.createStatement();
                int i = stmt.executeUpdate(sql);
                System.out.println(i);
                if(i>0){
                    System.out.println("成功修改");
                }else{
                    System.out.println("修改失败");
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn !=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

ResultSet:结果集对象

结果集对象,用来封装查询结果
next();游标向下移动一行
getXxx()获取数据 Xxx代表数据类型 如 getInt()
参数:
1️⃣int :代表列的编号 从1开始 getString(1)
2️⃣String:代表列名称 如getDouble(“balance”)
注意:
使用步骤:
1️⃣游标向下移动一行
2️⃣判断是否有数据
3️⃣获取数据

//循环判断游标是否是最后一行末尾
while( rs.next()){
                   //获取数据
                   int id = rs.getInt(1);
                   String name = rs.getString("name");
                   double balance = rs.getDouble(3);
                   System.out.println(id+" "+name+" "+balance);
               }

练习:查询emp表的数据将其封装为对象,然后打印
1️⃣定义一个emp类
2️⃣定义方法public List findAll(){}
3️⃣实现方法select *from emp;

PreparedStatement:执行sql对象

1️⃣SQL注入问题:在拼接sql时,有一些sql的特殊关键字参与字符串的拼接,造成安全性问题
①输入用户随便,输入密码:a’ or ‘a’ = 'a
②sql:select *from user where username = ’ ’ and password = ‘a’ or ‘a’ = ‘a’
2️⃣解决SQL注入问题:使用PreparedStatement对象解决
3️⃣预编译的SQL:参数使用?作为占位符
4️⃣步骤:
①定义sql
select *from user where username = ?and password = ?;
②获取执行SQL语句的对象Connection Preperedstatement (String sql)
③给?赋值:setXxx(参数1,参数2)
参数1: ?的位置编号 从1开始
参数2:?的值
④执行sql
5️⃣注意:后期都会使用PreparedStatement来完成增删改查的所有操作
可以防止SQL注入 效率更高

抽取JDBC工具类:JDBCUtils

目的:简化书写
分析:
1️⃣注册驱动抽取
2️⃣抽取一个方法获取连接对象
需求:不想传递参数,还得保证工具类的通用性
解决:配置文件
3️⃣抽取一个方法释放资源

/**
     * 演示jdbc工具类
     * @return
     */
    public List<Emp> findAll2(){
        Connection conn  =null;
        Statement stmt = null;
        ResultSet rs = null;
        List<Emp> list = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select *from emp";
            //获取sql对象
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            Emp emp = null;
            list =new ArrayList<Emp>();
            while(rs.next()){
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");
                emp =new Emp();
                emp.setId(id);
                emp.setName(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);
                list.add(emp);
            }

        } catch ( SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs,
                    stmt,
                    conn);
        }
        return list;
    }
/*
    jdbc工具类
 */
public class JDBCUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    /**
     *文件的读取
     */
    static {
        //读取资源文件,获取值
        //加载文件
        try {
            //1.Properties集合类
            Properties pro =new Properties();
            pro.load(new FileReader("D:\\IdeaProjects\\itcast\\day01_jdbc\\jdbc.properties"));
            url= pro.getProperty("url");
            user= pro.getProperty("user");
            password=pro.getProperty("password");
            driver= pro.getProperty("driver");
            //注册驱动
            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 获取连接
      * @return连接对象
     */

    public static Connection getConnection() throws SQLException {

        return DriverManager.getConnection(url,user,password);
    }

    /**
     * 释放资源
     * @param stmt
     * @param conn
     */
    public static void close(Statement stmt,Connection conn){
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    } public static void close(ResultSet rs,Statement stmt, Connection conn){
        if (rs !=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }
jdbc_properties
url =jdbc:mysql://localhost:3306/db3
user=root
password=root
driver=com.mysql.jdbc.Driver
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值