面试题:请写出一个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();
}
}
}
}