如何通过jdbc连接数据库
时间: 2023-11-22 22:56:31 浏览: 32
你可以使用Java提供的java.sql包中的API来连接和操作数据库,具体步骤如下:
1. 导入数据库驱动包,例如MySQL的驱动包com.mysql.jdbc.Driver。
2. 使用Class.forName()方法加载驱动类,例如Class.forName("com.mysql.jdbc.Driver")。
3. 使用DriverManager.getConnection()方法获取数据库连接,例如DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", "username", "password"),其中jdbc:mysql是数据库类型,localhost:3306是数据库的地址和端口号,dbname是数据库名,username和password是数据库登录账号和密码。
4. 通过获取到的Connection对象,创建一个Statement或PreparedStatement对象,使用executeQuery()方法执行SQL查询语句,使用executeUpdate()方法执行SQL增、删、改语句。
5. 最后使用ResultSet对象获取查询结果集,关闭数据库连接等。
示例代码:
```java
import java.sql.*;
public class JdbcTest {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", "username", "password");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM table");
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t" + rs.getString("name"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException 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();
}
}
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)