JDBC

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/nmdshh/article/details/100701379

在jdbc代码中,加载驱动、创建链接、关闭资源的代码都是固定的,可以将这些代码放在一个类里面,这样就可以不用重复写这些代码,节省时间和精力。

新建一个DBUtill类把那几个固定的代码放入该类

package com.lzfthh;
import java.sql.*;
public class Dbutill {
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/zjgm?user=root&password=123456&characterEncoding=utf-8&useSSL=true");
        return connection;
    }
    public static void closeAll(ResultSet resultset,Statement statement,Connection connection) throws SQLException {
        if(resultset!=null){
            resultset.close();
        }
        statement.close();
        connection.close();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

主程序代码

package com.lzfthh;
import java.sql.*;
public class test {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1 加载驱动
        Connection connection = Dbutill.getConnection();
        //2 创建链接
        System.out.println("创建连接成功");
        //3 写sql
        String sql ="select * from stu";
        //4 得到statement对象
        PreparedStatement statement = connection.prepareStatement(sql);
        //5 执行sql
        ResultSet resultSet =statement.executeQuery();
        //6 处理结果集
        while (resultSet.next()){
            int id =resultSet.getInt(1);
            String name =resultSet.getString(2);
            int age = resultSet.getInt(3);
            System.out.println(id+name+age);
        }
        //7关闭资源
        Dbutill.closeAll(resultSet,statement,connection);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
                                </div>
            <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e44c3c0e64.css" rel="stylesheet">
                </div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值