怎样使用jdbc连接数据库
时间: 2023-11-22 08:06:09 浏览: 22
1. 导入jdbc驱动包:将jdbc驱动包添加到项目的classpath中。
2. 加载驱动:使用Class.forName()方法加载驱动。
3. 建立连接:使用DriverManager.getConnection()方法建立与数据库的连接。
4. 创建语句对象:使用Connection对象的createStatement()方法创建Statement对象或使用PreparedStatement对象。
5. 执行语句:使用Statement对象或PreparedStatement对象的executeQuery()方法执行查询语句,使用executeUpdate()方法执行更新语句。
6. 处理结果集:使用ResultSet对象获取查询结果。
7. 关闭连接:使用Connection对象的close()方法关闭连接。
示例代码:
```java
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立连接
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 创建语句对象
stmt = conn.createStatement();
// 执行查询语句
String sql = "select * from user";
rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String password = rs.getString("password");
System.out.println("id=" + id + ", name=" + name + ", password=" + password);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)