import java.sql.*; //mysqld --console class Conn { Connection con; public Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("数据库驱动加载成功"); } catch(ClassNotFoundException e){ e.printStackTrace(); } try { con = DriverManager.getConnection("jdbc:mysql://localhost:3333/test_demo","root","123456"); System.out.println("数据库连接成功"); } catch (SQLException e) { e.printStackTrace(); } return con; } } public class JdbcTest { public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ Conn c = new Conn(); conn = c.getConnection(); //添加 增删改查操作 conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } }请在这串代码的基础上实现数据库的增删改查
时间: 2024-02-10 09:08:27 浏览: 31
好的,根据你的要求,我来编写一下基本的增删改查操作代码:
```
import java.sql.*;
class Conn {
Connection con;
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库驱动加载成功");
} catch(ClassNotFoundException e){
e.printStackTrace();
}
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3333/test_demo","root","123456");
System.out.println("数据库连接成功");
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
}
public class JdbcTest {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Conn c = new Conn();
conn = c.getConnection();
// 插入数据
stmt = conn.createStatement();
String sql = "INSERT INTO student (name, age, gender) VALUES ('张三', 20, '男')";
int count = stmt.executeUpdate(sql);
System.out.println("成功插入 " + count + " 条数据");
// 更新数据
sql = "UPDATE student SET age = 21 WHERE name = '张三'";
count = stmt.executeUpdate(sql);
System.out.println("成功更新 " + count + " 条数据");
// 删除数据
sql = "DELETE FROM student WHERE name = '张三'";
count = stmt.executeUpdate(sql);
System.out.println("成功删除 " + count + " 条数据");
// 查询数据
sql = "SELECT * FROM student";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("查询结果:");
while(rs.next()){
String name = rs.getString("name");
int age = rs.getInt("age");
String gender = rs.getString("gender");
System.out.println("姓名:" + name + ",年龄:" + age + ",性别:" + gender);
}
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){ }
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
```
这段代码中,我们添加了四个基本的数据库操作:
1. 插入数据:使用INSERT语句将一条新记录插入到student表中。
2. 更新数据:使用UPDATE语句将student表中名为“张三”的记录的年龄字段更新为21。
3. 删除数据:使用DELETE语句将student表中名为“张三”的记录删除。
4. 查询数据:使用SELECT语句查询student表中的所有记录,并将结果输出到控制台上。
注意:在运行程序之前,你需要确保已经创建了名为test_demo的数据库,并在其中创建了名为student的表,表结构包括name、age和gender三个字段。此外,你还需要将代码中的数据库连接字符串、用户名和密码替换为你自己的信息。