java加载数据库
时间: 2023-10-11 20:17:55 浏览: 45
在Java中,要加载数据库需要使用JDBC(Java Database Connectivity)驱动程序。以下是加载MySQL数据库的示例代码:
1. 首先,需要下载并安装MySQL JDBC驱动程序。
2. 在Java中,使用以下代码加载驱动程序:
```java
Class.forName("com.mysql.jdbc.Driver");
```
3. 创建数据库连接对象:
```java
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
```
其中,"jdbc:mysql://localhost:3306/mydatabase" 是连接字符串,其中"mydatabase"是数据库名称,"username"是数据库用户名,"password"是数据库密码。
4. 创建Statement对象并执行SQL查询:
```java
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
```
其中,"mytable"是数据库表名。
5. 遍历结果集并获取结果:
```java
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
// do something with the data
}
```
6. 关闭数据库连接:
```java
rs.close();
stmt.close();
conn.close();
```
完整的示例代码如下:
```java
import java.sql.*;
public class Main {
public static void main(String[] args) {
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Connect to the database
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// Create a statement and execute a query
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// Process the results
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println(name + " is " + age + " years old.");
}
// Close the database connection
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)