java数据库jdbc增删查改
时间: 2023-07-25 15:20:17 浏览: 101
java-JDBC数据库增删改查
4星 · 用户满意度95%
好的,我可以为您解答这个问题。
Java中使用JDBC(Java Database Connectivity)来连接数据库,实现对数据库的增删查改操作。下面是一个简单的示例代码:
1. 建立连接
```java
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
```
2. 插入数据
```java
Statement stmt = conn.createStatement();
String sql = "insert into student (name, age, sex) values ('Tom', 20, 'male')";
int result = stmt.executeUpdate(sql);
if(result > 0){
System.out.println("插入成功!");
}
```
3. 查询数据
```java
Statement stmt = conn.createStatement();
String sql = "select * from student";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String sex = rs.getString("sex");
System.out.println(id + " " + name + " " + age + " " + sex);
}
```
4. 修改数据
```java
Statement stmt = conn.createStatement();
String sql = "update student set age = 22 where id = 1";
int result = stmt.executeUpdate(sql);
if(result > 0){
System.out.println("修改成功!");
}
```
5. 删除数据
```java
Statement stmt = conn.createStatement();
String sql = "delete from student where id = 1";
int result = stmt.executeUpdate(sql);
if(result > 0){
System.out.println("删除成功!");
}
```
以上是一个简单的示例,您可以根据自己的需要进行修改和扩展。
阅读全文