JDBC—数据库连接
一.加载驱动:
在打开与数据库的JDBC连接之前,需要加载数据库的驱动程序,驱动程序只需加载一次,不需要在每次打开连接之前都进行加载操作。且每个JDBC驱动都有对驱动程序类。如:
- mysql:
Class.forName("com.mysql.jdbc.Driver");
- oracle:
Class.forName("oracle.jdbc.driver.OracleDriver");
二.创建连接
创建连接是通过java.sql.DriverManager类中的getConnection()方法,如下:
- 没有密码:
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
Connection connection = DriverManager.getConnection(url);
- 需要密码:
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
Connection connection = DriverManager.getConnection(url, "root", "123456");
- 使用属性:
Properties properties = new Properties();
properties.put("user", "root");
properties.put("password", "123456");
Connection connection =DriverManager.getConnection(url, properties);
三.执行SQL语句
当数据库连接成功后,便可以执行诸如查询,修改之类的sql语句,代码如下:
Statement statement = connection.createStatement();
String sql = "select * from user";
ResultSet resultSet = statement.executeQuery(sql);
四.关闭连接
connection.close();
五.完整示例
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
connection = DriverManager.getConnection(url, "root", "123456");
statement = connection.createStatement();
String sql = "select * from user";
resultSet = statement.executeQuery(sql);
resultSet.beforeFirst();
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
}