好的,下面是关于实验九和实验十的示例代码。
**实验九:使用JDBC访问数据库**
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class BookDatabaseDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/Books"; // 数据库连接URL
String user = "root"; // 数据库用户名
String password = "yourpassword"; // 数据库密码
try {
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
// 插入数据
String insertSql = "INSERT INTO book_message (书名, 作者, 出版社, 出版时间, 价格) "
+ "VALUES ('Java编程', 'FishC', '清华大学出版社', '2021-10-10', 59.9)";
statement.executeUpdate(insertSql);
// 更新数据
String updateSql = "UPDATE book_message SET 价格 = 49.9 WHERE 书名 = 'Java编程'";
statement.executeUpdate(updateSql);
// 查询数据
String querySql = "SELECT * FROM book_message";
ResultSet resultSet = statement.executeQuery(querySql);
while (resultSet.next()) {
System.out.println("书名: " + resultSet.getString("书名"));
System.out.println("作者: " + resultSet.getString("作者"));
System.out.println("出版社: " + resultSet.getString("出版社"));
System.out.println("出版时间: " + resultSet.getString("出版时间"));
System.out.println("价格: " + resultSet.getDouble("价格"));
}
// 删除数据
String deleteSql = "DELETE FROM book_message WHERE 书名 = 'Java编程'";
statement.executeUpdate(deleteSql);
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
**实验十:多线程编程**
class Bank {
private int count = 0;
public synchronized void deposit(String customer, int amount) {
count += amount;
System.out.println(customer + "汇款: " + amount + "元,账户总额: " + count + "元");
}
}
class Customer implements Runnable {
private Bank bank;
private String customerName;
public Customer(Bank bank, String customerName) {
this.bank = bank;
this.customerName = customerName;
}
public void run() {
for (int i = 0; i < 3; i++) {
bank.deposit(customerName, 100);
}
}
}
public class BankingSimulation {
public static void main(String[] args) {
Bank bank = new Bank();
Thread customer1 = new Thread(new Customer(bank, "顾客1"));
Thread customer2 = new Thread(new Customer(bank, "顾客2"));
customer1.start();
customer2.start();
}
}
请确保您已经安装并正确配置了MySQL数据库(或使用其他类型的数据库并调整代码中的连接字符串)以运行实验九的代码。实验十的代码不依赖于数据库,可以直接运行。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |