JDBC 小结
JDBC 小结
步骤总结
- 加载驱动
- 连接数据库 DriverManager
- 获得执行sql的对象 Statement
- 获得返回的结果集
- 释放连接
// 1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.加载用户信息
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
String username = "root";
String password = "132654";
// 3.连接成功,数据库对象 connection代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
// 4.执行sql对象 statement执行sql的对象
Statement statement = connection.createStatement();
// 5.执行sql的对象 去执行sql
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql); // 返回的结果集
while (resultSet.next()) {
System.out.println("id=" + resultSet.getObject("id"));
System.out.println("name=" + resultSet.getObject("name"));
System.out.println("pwd=" + resultSet.getObject("password"));
System.out.println("email=" + resultSet.getObject("email"));
System.out.println("birthday=" + resultSet.getObject("birthday"));
System.out.println("===============================");
}
// 释放连接
resultSet.close();
statement.close();
connection.close();
RsultSet 查询的结果集:封装了所有的查询结果
获取指定的数据类型
resultSet.getObject();
resultSet.getString();
resultSet.getInt();
resultSet.getDouble();
resultSet.getDate();
resultSet.getBigDecimal();
resultSet.getTime();
resultSet.getObject();
resultSet.getString();
resultSet.getInt();
resultSet.getDouble();
resultSet.getDate();
resultSet.getBigDecimal();
resultSet.getTime();
遍历、指针
resultSet.next();
resultSet.beforeFirst();
resultSet.afterLast();
resultSet.previous();
resultSet.absolute(row);
释放资源 必不可少
释放连接
resultSet.close();
statement.close();
connection.close();
配置文件
配置文件(db.properties)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=132654
工具类(JdbcUtils)
public class JdbcUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try {
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
// 1.驱动只用加载一次
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
// 释放连接资源
public static void release(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
}

浙公网安备 33010602011771号