JDBC是Java语言用于与不同类型数据库进行交互的一种标准接口。通过JDBC,Java应用程序可以连接到数据库,执行SQL语句,并处理来自数据库的结果。
以下是JDBC的一些关键概念和用法:
1.连接数据库,通过JDBC,可以使用数据库特定的驱动程序来连接到数据库。连接通常需要数据库的URL、用户名和密码。
String url = "jdbc:mysql://localhost:3306/数据库名";
String username = "username";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
2.执行查询,可以使用连接对象创建一个Statement对象,并通过该对象执行SQL查询。
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");
while (resultSet.next()) {
// 处理结果集中的数据
}
3.执行数据库更新操作,如插入、更新和删除。
Statement statement = connection.createStatement();
int rowsAffected = statement.executeUpdate("INSERT INTO mytable (column1, column2) VALUES (value1, value2)");
4使用PreparedStatement,PreparedStatement 可以预编译SQL语句,提高效率和安全性。
String sql = "INSERT INTO mytable (column1, column2) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, value1);
preparedStatement.setString(2, value2);
int rowsAffected = preparedStatement.executeUpdate();
5关闭连接,使用完数据库连接后,应该及时释放资源。
statement.close(); connection.close(); // 关闭数据库连接