JDBC连接基本步骤

JDBC学习中 因为缺少实践 总是前学后忘 此博客用来记录一种常用的连接方式 

 1.添加数据库驱动

     在项目目录下新建名为lib的文件夹,将驱动jar包粘贴进来 ,选中 右键选择Add as Libary 完成添加

 2.加载驱动 获取链接 获取处理sql的对象 执行sql  处理结果集(非必要)  关闭资源 

   详见代码及注释

import java.sql.*;

public class JDBCTest02 {
    public static void main(String[] args) throws ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        //"jdbc:mysql://127.0.0.1:3306/test1?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC"
        //获取连接需要的三个参数 1.连接的路径(jdbc:mysql://ip地址:端口/要连接的数据库?一些配置 例如mysql8.0需要加时区信息 编码 等等) 2.用户 3.用户密码
        String url="jdbc:mysql://localhost:3306/atguigudb?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC &allowPublicKeyRetrieval=true";
        String user="root";
        String password="181028";
        //定义在 try-catch语句块外是为了方便处理异常 关闭资源
        Connection connection=null; //连接对象
        PreparedStatement preparedStatement=null; //处理sql的对象
        ResultSet resultSet=null;//查询操作返回的结果集 没有查询操作不用定义
        try {
            connection= DriverManager.getConnection(url,user,password);//用DriverManager对象获取连接对象
           // String sql="create table student5 (id int ,num int )";
            String sql2="select * from employees where salary=?";//?是占位符 可以有多个 用preparedStatement.set类型(占位符序号,内容)来填充
            preparedStatement=connection.prepareStatement(sql2);
            preparedStatement.setDouble(1,4800.00);
            resultSet= preparedStatement.executeQuery();//执行查询的sql 注意: 这个方法可以直接传sql语句 但不能传含占位符的sql语句
            //preparedStatement.executeUpdate(sql) 用来执行插入 删除 修改等操作的sql语句
            while (resultSet.next()){ //处理查询操作结果集  resultSet.next() 返回布尔类型的值 作用是移动光标 访问每一行数据
                //resultSet.getString(int) 将结果集中的数据以字符串形式返回 参数可以为列名 也可以为数字 参数为1就是表里第一列的数据 为2就是第二列的数据 以此类推
                System.out.println(resultSet.getString(2)+"  "+resultSet.getString(3));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally { //关闭资源  与获取资源的顺序相反 先关闭小的  分别try-catch
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

以上内容如有错误 感谢指出.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值