JDBC链接数据库

以下是我写的非常详细的JDBC链接数据库的过程,耐心看完,肯定会有收获的。

1、加载驱动Class.forName("com.mysql.jdbc.Driver");

     这时会出现ClassNotFoundException,类没有找到异常,我们需要利用try-catch捕获并处理这个异常。

try{

Class.forName("com.mysql.jdbc.Driver");

2、获取连接对象connection

利用DriverManger的getConnection方法与数据库建立链接,并将值赋给Connection类的对象connection,具体代码如下:

//这里会抛出SQLException异常,也要用try-catch捕获异常

Connection connection = DriverManger.getConnection("  //要设置为全局变量

url:jdbc:mysql://localhost:3306/java?useUnicode=true&characterEncoding=UTF-8",user:"root",password:"123456"

")

3、写sql语句 (这里以查询学生表中id>=5的学生信息为例) 这里要提前建立一个student类

String sql = “SELECT id,`name`,age,gender FROM student WHERE id>= ?”;

4、创建statement  这里要用statement的子类PreparedStatement,因为它会对sql语句进行预编译。

PreparedStatement preparedStatement = connection.preparedStatement(sql); //要设置为全局变量

填上占位符 ?的值,调用preparedStatement的setInt()方法

preparedStatement.setInt(paremeter:1,x:5);

//打印查询语句

system.out.println(preparedStatement);

5、执行sql语句  调用preparedStatement的excuteQurey()方法,将结果赋到ResultSet结果集中

ResultSet resultSet = preparedStatement.excuteQurey(); //要设置为全局变量

//创建集合接收student对象

ArraryList<student> list = new ArraryList<>();

//遍历结果集

while(resultSet.next()){

//取出学生信息

Int id = resultSet.getInt("id");

String name = resultSet.getString("name");

Int age = resultSet.getInt("age");

String gender = resultSet.getString("gender");

//将学生信息封装到Student类中

Student student = new Student(id,name,age,gender);

//将student对象添加到list集合中

list.add(student);

}

//遍历并输出list集合中的student对象

for(Student student : list){

 System.out.println(student);

}

}catch(ClassNotFoundException e{

 e.printStactTrace();

}catch(SQLException throwables){

throwables.printStactTrace();

}finally{

//关闭连接

//因为要判断connection,prepqredStatement,resultSet是否为空,所以要将以上变量设置为全局变量,并将初始值设置为null,并判断变量是否为空。

//先打开的后关闭

//如果不加限制条件,则会报空指针异常

if(resultSet != null){

try{

resultSet.close();  //这里close也会出现SQLException异常,同样捕获

}catch(SQLException throwables){

throwables.printStactTrace();

}

if(preparedStatement != null){

try{

preparedStatement.close();  //这里close也会出现SQLException异常,同样捕获

}catch(SQLException throwables){

throwables.printStactTrace();

}

if(connection != null){

try{

connection.close();  //这里close也会出现SQLException异常,同样捕获

}catch(SQLException throwables){

throwables.printStactTrace();

}

这样就算是成功了,下面是具体代码:

@Test
    public void test(){
        int selectid = 5;
        //定义全局变量
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
           // 1、加载驱动Class.forName("");
            Class.forName("com.mysql.jdbc.Driver");
            // 2、获得连接对象Connection
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java?useUnicode=true&characterEncoding=UTF-8","root","123456");
            String sql = "SELECT id,`name`,age,gender FROM student where id >= ?";
            // 4、创建Statement(一艘船)
            //PreparedStatement 使用预编译的sql
            statement = connection.prepareStatement(sql);
            //填上 ? 占位符的值
            statement.setInt(1,selectid);
            System.out.println(statement);
            // 5、执行sql语句
            //            (1) 更新类(更改了表里面数据):delete/update/insert     executeUpdate()
            //    返回值:int,表示你影响的行数
            //            (2)查询(没有改变表里面数据):  select                              executeQuery()
            //    返回值:结果集ResultSet
            resultSet = statement.executeQuery();
            ArrayList<Student> arrayList = new ArrayList<>();
            //next()方法判断下一行有没有,如果有指向下一行
            while (resultSet.next()){
                //每遍历一次循环,就拿出数据库查询结果里面的一行记录,就是一个学生信息,
                //就可以封装成一个student对象
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                Student student = new Student(id,name,age,gender);
                arrayList.add(student);
            }
            for (Student student : arrayList) {
                System.out.println(student);
            }
            // 6、关闭连接
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //先打开的后关闭
            //如果不加限制条件会报空指针异常
            if (resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null){
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        }

    }

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值