编写一个JAVA程序,完成数据库的创建,并使用JDBC分别完成数据库的插入,删除,修改,查询操作
时间: 2025-01-12 15:53:32 浏览: 19
以下是一个使用Java和JDBC完成数据库创建、插入、删除、修改和查询操作的示例程序。这个示例使用了MySQL数据库,你需要确保已经安装了MySQL并创建了一个数据库用户。
```java
import java.sql.*;
public class JDBCExample {
// 数据库连接参数
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC";
static final String USER = "root";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册JDBC驱动
Class.forName(JDBC_DRIVER);
// 打开连接
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 创建表
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS employees " +
"(id INTEGER not NULL, " +
" name VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
// 插入数据
System.out.println("Inserting records into the table...");
sql = "INSERT INTO employees (id, name, age) VALUES (1, 'John', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO employees (id, name, age) VALUES (2, 'Jane', 25)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
// 查询数据
System.out.println("Fetching records from the table...");
sql = "SELECT id, name, age FROM employees";
ResultSet rs = stmt.executeQuery(sql);
// 处理结果集
while(rs.next()){
// 检索每行数据
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// 显示结果
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
rs.close();
// 更新数据
System.out.println("Updating records in the table...");
sql = "UPDATE employees SET age = 31 WHERE id = 1";
stmt.executeUpdate(sql);
System.out.println("Updated records in the table...");
// 删除数据
System.out.println("Deleting records from the table...");
sql = "DELETE FROM employees WHERE id = 2";
stmt.executeUpdate(sql);
System.out.println("Deleted records from the table...");
// 关闭连接
stmt.close();
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();
}
}
System.out.println("Goodbye!");
}
}
```
这个程序完成了以下操作:
1. 注册JDBC驱动
2. 连接到数据库
3. 创建表
4. 插入数据
5. 查询数据
6. 更新数据
7. 删除数据
8. 关闭连接
请注意,你需要将数据库URL、用户名和密码替换为你自己的数据库连接信息。
阅读全文
相关推荐

















