以下是使用命令行在 MySQL 中创建 Library 数据库,并创建 book 表的示例代码:

Step 1: 打开命令行窗口并登录到 MySQL 数据库

mysql -u username -p

其中,username 是你的 MySQL 用户名。

Step 2: 创建 Library 数据库

CREATE DATABASE Library;

Step 3: 进入 Library 数据库

USE Library;

Step 4: 创建 book 表

CREATE TABLE book (
  id INT PRIMARY KEY AUTO_INCREMENT,
  title VARCHAR(255),
  author VARCHAR(255),
  price DECIMAL(10, 2)
);

在这个示例中,book 表包含 id、title、author 和 price 四个字段。id 是主键,并自动递增;title 和 author 是字符串类型;price 是十进制类型。

完成上述步骤后,就可以使用 SQL 命令向 book 表中插入数据、修改数据、删除数据、查询数据。

以下是使用 Java 代码连接 MySQL 数据库,并向 book 表中插入数据、修改数据、删除数据、查询数据的示例代码:

import java.sql.*;

public class Main {
    public static void main(String[] args) {
        try {
            // 建立数据库连接
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/Library", "username", "password");
            Statement statement = connection.createStatement();

            // 插入数据
            String insertQuery = "INSERT INTO book (title, author, price) VALUES ('Book 1', 'Author 1', 9.99)";
            statement.executeUpdate(insertQuery);

            // 修改数据
            String updateQuery = "UPDATE book SET price = 14.99 WHERE id = 1";
            statement.executeUpdate(updateQuery);

            // 删除数据
            String deleteQuery = "DELETE FROM book WHERE id = 1";
            statement.executeUpdate(deleteQuery);

            // 查询数据
            String selectQuery = "SELECT * FROM book";
            ResultSet resultSet = statement.executeQuery(selectQuery);
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String title = resultSet.getString("title");
                String author = resultSet.getString("author");
                double price = resultSet.getDouble("price");

                System.out.println("ID: " + id);
                System.out.println("Title: " + title);
                System.out.println("Author: " + author);
                System.out.println("Price: " + price);
            }

            // 关闭连接
            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,需要将 "username" 和 "password" 替换为你的 MySQL 用户名和密码。

此代码段使用 JDBC 驱动程序连接到 MySQL 数据库,并执行插入、更新、删除和查询操作。最后,将结果打印到控制台上。

请确保已经下载并导入了 MySQL 的 JDBC 驱动程序。


原文地址: https://www.cveoy.top/t/topic/pxme 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录