javaweb调用数据库
时间: 2023-07-08 08:06:41 浏览: 115
在JavaWeb中,我们可以使用Java Database Connectivity (JDBC) API来调用数据库。以下是一个简单的示例代码,演示如何使用JDBC连接MySQL数据库:
```java
import java.sql.*;
public class DatabaseConnection {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/mydatabase";
// 数据库的用户名与密码
static final String USER = "root";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// 注册 JDBC 驱动器
Class.forName(JDBC_DRIVER);
// 打开一个连接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
System.out.println("实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM students";
ResultSet rs = stmt.executeQuery(sql);
// 处理结果集
while(rs.next()){
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 姓名: " + name);
System.out.println(", 年龄: " + age);
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
```
在这个示例中,我们首先定义了一个连接到MySQL数据库的URL,用户名和密码。然后,我们使用JDBC驱动程序注册并使用DriverManager类获取数据库连接。接下来,我们使用创建的连接创建一个Statement对象,并使用它执行查询。最后,我们通过循环处理结果集中的每一行,从每一行中提取数据并显示它们。最后,我们关闭所有打开的资源。
请注意,这只是一个简单的示例,您可能需要根据您的具体需求进行更改。另外,为了使代码更加模块化和易于维护,您应该将数据库连接和查询逻辑放在不同的类和方法中。
阅读全文
相关推荐


















