面试题:请写出一个jdbc

面试题:请写出一个jdbc

package com.neutech.jdbc;
 
import java.sql.*;
 
/**
* @Author rxj
* @Date 2021/12/20 9:53
* @Version 1.0
*/
 
public class JdbcTest {
    public static final String URL = "jdbc:mysql://localhost:3306/fruits?serverTimezone=Asia/Shanghai&useSSL=false";//连接数据库
    public static final String USER_NAME = "root";//数据库名字
    public static final String PASSWORD = "123456";//数据库密码
 
    public static void main(String[] args) {
//        编写JDBC步骤
        Connection conn = null;
        Statement stmt = null;
//        只用于DQL语句
        ResultSet rs = null;
        try {
            //0.使用反射获取驱动
            Class.forName("com.mysql.jdbc.Driver");
            //1.创建连接
            long start = System.currentTimeMillis();
            conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
            long end = System.currentTimeMillis();
            System.out.println(end - start);//这里输出的是每次访问数据库的时间
            //2.创建语句Statement
            stmt = conn.createStatement();
            //3、创建要执行的sql语句
            String sql = "select * from fruits limit 5,10 ";
            rs=stmt.executeQuery(sql);
//            4.遍历结果集
            while (rs.next()) {
//                5、结果集的操作
//              输出的语句要根据你数据库的具体信息编辑
                System.out.println(rs.getString("f_id")
                        + "\t" + rs.getInt("s_id")
                        + "\t" + rs.getString("f_name")
                        + "\t" + rs.getDouble("f_price"));
            }
 
        } catch (SQLException e) {
            System.out.println("出现SQL 异常");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            System.out.println("类找不到异常,请自查原因");
            e.printStackTrace();
        }finally {
//            6.关闭资源
            try {
                if (rs !=null){
                    rs.close();
                }
                if (stmt !=null){
                    stmt.close();
                }
                if (conn !=null){
                    conn.close();
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
 
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值