给一个jdbc例子
时间: 2023-07-07 14:05:49 浏览: 41
当使用Java编写数据库应用程序时,通常需要使用JDBC API来与数据库进行交互。以下是一个基本的JDBC示例:
```java
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) throws SQLException {
// Step 1: Load the JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Unable to load JDBC driver");
e.printStackTrace();
return;
}
// Step 2: Establish the database connection
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// Step 3: Create a statement
Statement statement = connection.createStatement();
// Step 4: Execute the query
ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");
// Step 5: Process the results
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// Step 6: Close the connection and release resources
resultSet.close();
statement.close();
connection.close();
}
}
```
这个示例展示了如何使用JDBC API连接到MySQL数据库,执行一个简单的查询,并处理结果。请注意,此示例中使用的是MySQL JDBC驱动程序。要运行此示例,您需要将MySQL JDBC驱动程序添加到类路径中。