java链接mysql数据库
时间: 2023-06-29 19:03:20 浏览: 32
要在 Java 中链接 MySQL 数据库,你需要遵循以下步骤:
1. 下载适当的 MySQL JDBC 驱动程序,并将其添加到你的 Java 项目中。
2. 导入 java.sql 包和 javax.sql 包。
3. 使用以下代码来建立数据库连接:
```java
String url = "jdbc:mysql://localhost:3306/database_name";
String user = "username";
String password = "password";
Connection con = DriverManager.getConnection(url, user, password);
```
其中,"database_name" 是你要连接的数据库名称;"username" 和 "password" 是你的 MySQL 用户名和密码。
4. 通过 Connection 对象创建 Statement 对象:
```java
Statement stmt = con.createStatement();
```
5. 使用 Statement 对象执行 SQL 查询或更新:
```java
ResultSet rs = stmt.executeQuery("SELECT * FROM table_name");
int rowsAffected = stmt.executeUpdate("UPDATE table_name SET column_name = value WHERE id = 1");
```
6. 关闭连接和 Statement 对象:
```java
rs.close();
stmt.close();
con.close();
```
完整的示例代码:
```java
import java.sql.*;
public class Main {
public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost:3306/database_name";
String user = "username";
String password = "password";
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM table_name");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getFloat(3));
}
int rowsAffected = stmt.executeUpdate("UPDATE table_name SET column_name = value WHERE id = 1");
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
```
请注意,这只是一个基本示例。在实际应用程序中,你需要更好地管理连接,处理异常和关闭资源。
相关推荐
![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_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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)