如何在java程序中调用数据库
时间: 2023-11-17 18:05:42 浏览: 64
1. 导入数据库驱动程序:在程序中导入数据库驱动程序,以便与数据库建立连接。不同的数据库驱动程序有不同的导入方式,一般需要在项目中添加数据库驱动包,并在代码中导入相应的类。
2. 建立连接:在程序中建立与数据库的连接,可以使用JDBC提供的DriverManager类,该类提供了静态方法getConnection(),用于建立与数据库的连接,连接参数包括数据库的URL、用户名和密码等。
3. 创建Statement对象:创建一个Statement对象,用于执行SQL语句。可以使用Connection对象的createStatement()方法创建Statement对象。
4. 执行SQL语句:使用Statement对象执行SQL语句,可以使用Statement对象的execute()、executeQuery()和executeUpdate()方法执行不同类型的SQL语句。
5. 处理结果集:如果执行的SQL语句返回了结果集,可以使用ResultSet对象处理结果集。可以使用Statement对象的executeQuery()方法获取ResultSet对象。
6. 关闭连接:执行完SQL语句后,需要关闭与数据库的连接,可以使用Connection对象的close()方法关闭连接。
示例代码:
```java
import java.sql.*;
public class Test {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1. 导入数据库驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 2. 建立连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "123456");
// 3. 创建Statement对象
stmt = conn.createStatement();
// 4. 执行SQL语句
rs = stmt.executeQuery("SELECT * FROM user");
// 5. 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("id: " + id + ", name: " + name + ", age: " + age);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
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();
}
}
}
}
```