java链接数据库增删改
时间: 2023-08-19 14:03:46 浏览: 66
Java 连接数据库可以使用 JDBC(Java Database Connectivity)技术,具体的增删改操作可以通过执行 SQL 语句来实现。
下面是一个简单的示例代码,演示如何使用 JDBC 连接 MySQL 数据库,并进行增删改操作:
```java
import java.sql.*;
public class Main {
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = null;
Statement stmt = null;
try {
// 1. 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 2. 建立数据库连接
conn = DriverManager.getConnection(url, user, password);
// 3. 创建 Statement 对象
stmt = conn.createStatement();
// 4. 执行 SQL 语句
String sql = "INSERT INTO user(name, age) VALUES('Tom', 18)";
int rows = stmt.executeUpdate(sql);
System.out.println("插入了 " + rows + " 条数据");
sql = "UPDATE user SET age = 19 WHERE id = 1";
rows = stmt.executeUpdate(sql);
System.out.println("更新了 " + rows + " 条数据");
sql = "DELETE FROM user WHERE id = 2";
rows = stmt.executeUpdate(sql);
System.out.println("删除了 " + rows + " 条数据");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 5. 关闭数据库连接
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
上述代码使用 `com.mysql.jdbc.Driver` 驱动连接 MySQL 数据库,然后创建一个 Statement 对象来执行 SQL 语句。具体的增删改操作通过执行相应的 SQL 语句来实现,其中 `executeUpdate` 方法返回受影响的行数。
需要注意的是,上述代码仅为示例代码,实际开发中需要根据具体情况进行修改。
相关推荐
![](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)