MySQL实例开发(SequoiaDB高级课程)

实验 1 搭建 MySQL 实例应用开发环境
使用 JDBC 配置连接信息,查询 employee 表:

Class.forName("com.mysql.jdbc.Driver");
// MySQL username
String user = "root";
// MySQL password
String password = "root";
// MySQL connection address
String url = "jdbc:mysql://sdbserver1:3306/mysqlTest?useSSL=false";
// Get connection object conn through configuration
Connection conn = DriverManager.getConnection(url, user, password);
// Create a Statement object to send SQL statements to the database
Statement stmt = conn.createStatement();
// Get the result set rs
ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
boolean isHeaderPrint = false;
// Traverse the result set
while (rs.next()) {
    // Get the table structure
    ResultSetMetaData md = rs.getMetaData();
    // Get the number of rows
    int col_num = md.getColumnCount();
    if (!isHeaderPrint){
        // Traverse the database field names
        for (int i = 1; i  <= col_num; i++) {
            System.out.print(md.getColumnName(i) + "\t");
        }
        isHeaderPrint = true;
    }
    System.out.println();
    // Traverse each line to find the information
    for (int i = 1; i <= col_num; i++) {
        System.out.print(rs.getString(i) + "\t");
    }
}
// Close stmt and conn
stmt.close();
conn.close();

配置连接池:
创建C3P0的ComboPooledDataSource对象,配置数据库连接信息:

private static ComboPooledDataSource dataSource=new ComboPooledDataSource();

static {
    try {
        // Set up the registered driver
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        //url
        dataSource.setJdbcUrl("jdbc:mysql://sdbserver1:3306/mysqlTest");
        // Database username
        dataSource.setUser("root");
        // Database password
        dataSource.setPassword("root");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

将下方代码粘贴到 TODO code 2 区域内,获取数据库连接:

try {
    // Get connection
    conn = dataSource.getConnection();
} catch (SQLException e) {
    throw new RuntimeException("database conn error"+e);
}

将下方代码粘贴到 TODO code 3 区域内,释放资源:

if (rs!=null){
    try {
        rs.close();// Return rs
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
if (stmt!=null){
    try {
        stmt.close();//Return stmt
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
if (conn!=null){
    try {
        conn.close();//Return conn
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

将下方代码粘贴到 TODO code 1 区域内,验证连接池,查询 employee 表信息:

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
    // 使用 C3P0 工具类获得 conn
    conn = UtilsC3P0.getConnection();
    System.out.println(conn);
    // 获得执行者对象
    stmt = conn.createStatement();
    // 执行 SQL 语句
    rs = stmt.executeQuery("SELECT * FROM employee");
    // 获取表结构
    ResultSetMetaData metaData = rs.getMetaData();
    // 获取列数
    int columnCount = metaData.getColumnCount();
    // 遍历结果集
    while (rs.next()){
        // 遍历 employee 表的内容
        for (int i = 1; i <= columnCount; i++) {
            System.out.print(rs.getString(i) + "\t");
        }
        System.out.println();
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    //关闭资源
    UtilsC3P0.close(rs, stmt, conn);
}

将下方代码粘贴到 TODO code 1 区域内,使用 now 函数获取当前日期时间:

// Write a SQL statement to get the current date and time
String sql = "SELECT NOW();";
// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Get the result set
rs = stmt.executeQuery(sql);
// Traverse the result set
while (rs.next()) {
    // Traverse to get the current date and time
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

实验 2 数据库、表和索引
将下方代码粘贴到 TODO code 1 区域内,创建数据库 employee:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "CREATE DATABASE employee";
// Execute sql
stmt.executeUpdate(sql);

删除数据库:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "DROP DATABASE employee";
// Execute sql
stmt.executeUpdate(sql);

创建表employee:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "CREATE TABLE employee " +
    "(" +
    "empno INT AUTO_INCREMENT PRIMARY KEY, " +
    "ename VARCHAR(128), " +
    "age INT" +
    ")";
// Execute sql
stmt.executeUpdate(sql);

创建普通索引:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "ALTER TABLE employee_idx ADD INDEX(ename)";
// Execute sql
stmt.executeUpdate(sql);

为表 employee_idx 的字段 empno 创建唯一索引:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "ALTER TABLE employee_idx ADD UNIQUE INDEX(empno)";
// Execute sql
stmt.executeUpdate(sql);

为表 employee_idx 的字段 ename,age 创建复合索引:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "ALTER TABLE employee_idx ADD UNIQUE INDEX(ename,age)";
// Execute sql
stmt.executeUpdate(sql);

删除表 employee_idx 的索引 ename:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "ALTER TABLE employee_idx DROP INDEX ename";
// Execute sql
stmt.executeUpdate(sql);

给表 employee_pk 的 empno 字段添加主键

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "ALTER TABLE employee_pk ADD PRIMARY KEY(empno)";
// Execute sql
stmt.executeUpdate(sql);

删除表 employee_pk 的主键

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "ALTER TABLE employee_pk DROP PRIMARY KEY";
// Execute sql
stmt.executeUpdate(sql);

实验 3 数据类型
在这里插入图片描述
创建整型字段的表,插入并查询数据:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write SQL to create integer table
String sql = "CREATE TABLE integerTab(a TINYINT,b SMALLINT,c MEDIUMINT,d INT,e BIGINT)";
// Execute sql
stmt.executeUpdate(sql);
// Write sql to insert data
String sql2 = "INSERT INTO integerTab VALUES(111,222,333,444,555)";
// Execute sql
stmt.executeUpdate(sql2);
// Write sql to query the integer table
String sql3 = "SELECT * FROM integerTab";
// Return to the result set, and traverse to view the results
rs = stmt.executeQuery(sql3);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
创建浮点和定点型字段的表,插入并查询数据:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write SQL to create a table to store floating-point and fixed-point data
String sql = "CREATE TABLE doubleTab(a FLOAT,b DOUBLE,c DECIMAL(5,2))";
// Execute sql
stmt.executeUpdate(sql);
// Write sql to insert data
String sql2 = "INSERT INTO doubleTab VALUES(1.11,2.22,333.33)";
String sql3 = "INSERT INTO doubleTab VALUES(2.89,1,33.345)";
// Execute sql
stmt.executeUpdate(sql2);
stmt.executeUpdate(sql3);
// Write sql to view table doubleTab
String sql4 = "SELECT * FROM doubleTab";
// Return and traverse the result set to view the data
rs = stmt.executeQuery(sql4);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
创建日期时间类型字段的表,插入并查询数据:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write SQL to create tables to store data of date and time type
String sql = "CREATE TABLE dateTab(a DATE,b TIME,c DATETIME,d TIMESTAMP)";
// Execute sql
stmt.executeUpdate(sql);
// Write sql to insert data
String sql2 = "INSERT INTO dateTab VALUES('2020-3-31','15:20:36','2020-3-31 15:20:36',null)";
stmt.executeUpdate(sql2);
// Query the data of table dateTab
String sql4 = "SELECT * FROM dateTab";
rs = stmt.executeQuery(sql4);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述在这里插入图片描述
创建字符串类型字段的表,插入并查询数据:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write SQL to create a table of string type fields
String sql = "CREATE TABLE strTab(a CHAR(32),b VARCHAR(32),c TINYTEXT,d TEXT,e MEDIUMTEXT,f LONGTEXT)";
// Execute sql
stmt.executeUpdate(sql);

String sql2 = "INSERT INTO strTab VALUES('aaaaa','bbbbb','ccccc','ddddd','eeeee','fffff')";
stmt.executeUpdate(sql2);
String sql4 = "SELECT * FROM strTab";
rs = stmt.executeQuery(sql4);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

创建 lob 类型字段的表,插入 /opt/sequoiadb/ 路径下的文件 om_ver.conf 到表中,并查询数据:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql to create a table lobTab that stores lob
String sql = "CREATE TABLE lobTab(id INT,name VARCHAR(32),file BLOB)";
// Execute sql
stmt.executeUpdate(sql);
// Write sql to insert data
String sql2 = "INSERT INTO lobTab(id,name,file) VALUES(?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql2);
ps.setInt(1,1);
ps.setString(2,"bob");
// Read file om_ver.conf
InputStream in = new FileInputStream("/opt/sequoiadb/om_ver.conf");
ps.setBlob(3,in);
// Execute sql
ps.executeUpdate();
// Write sql to query lobTab
String sql4 = "SELECT * FROM lobTab";
rs = stmt.executeQuery(sql4);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t\t");
    }
    System.out.println();
}

实验 4 数据查询

检索表 employee 数据:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql to query the employee table
String sql = "SELECT * FROM employee";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

查询 empno 为1的员工信息:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT * FROM employee WHERE empno = 10001";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

查询表 employee 的信息,只返回前三行

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT * FROM employee LIMIT 3";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

查询 ename 中包含 art 的员工信息:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT * FROM employee WHERE ename LIKE '%art%'";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

查询 employee 表信息,并按 empno 倒序展示:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT * FROM employee ORDER BY empno DESC";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

UNION:
第一条 SELECT 检索 age 大于22的员工信息,第二条 SELECT 检索 empno 为10002的员工信息:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT * FROM employee WHERE age > 22 UNION SELECT * FROM employee WHERE empno = 10002";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

GROUP BY:
查询表 products 的 vend_id,并根据 vend_id 分组,查出每组的个数:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT vend_id,COUNT(*) AS num_prods FROM products GROUP BY vend_id";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

JOIN:
在这里插入图片描述
使用内连接,获取两个表中字段匹配关系的记录:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT a.runoob_id, a.runoob_author, b.runoob_count FROM info_tbl a INNER JOIN count_tbl b ON a.runoob_author = b.runoob_author";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

使用左连接,获取两个表中字段匹配关系的记录:

// Traverse the query results
stmt = conn.createStatement();
// Write sql
String sql = "SELECT a.runoob_id, a.runoob_author, b.runoob_count FROM info_tbl a LEFT JOIN count_tbl b ON a.runoob_author = b.runoob_author;";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

使用右连接,获取两个表中字段匹配关系的记录:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT a.runoob_id, a.runoob_author, b.runoob_count FROM info_tbl a RIGHT JOIN count_tbl b ON a.runoob_author = b.runoob_author;";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

实验 5 数据操作

向表 emplyee 中插入数据:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql2 = "INSERT INTO employee VALUES (10007, 'Bob', 48),(10008, 'Rose', 21)";
// Execute sql to insert data into employee
stmt.executeUpdate(sql2); 
// Write sql
String sql3 = "SELECT * FROM employee;";
// Query employee to get the result set
rs = stmt.executeQuery(sql3);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

INSERT SELECT:INSERT SELECT 语句从一个表复制数据,然后把数据插入到一个已存在的表中。
从 employee 表复制数据,然后把数据插入到 employeeBak 表中

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql to create table
String sql = "CREATE TABLE employeeBak " +
    "(" +
    "empno INT AUTO_INCREMENT PRIMARY KEY, " +
    "ename VARCHAR(128), " +
    "age INT" +
    ")";
// Execute sql
stmt.executeUpdate(sql);
// Write sql to insert data
String sql2 = "INSERT INTO employeeBak SELECT * FROM employee";
// Execute sql
stmt.executeUpdate(sql2);
// Write sql query table employeeBak
String sql3 = "SELECT * FROM employeeBak;";
rs = stmt.executeQuery(sql3);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

CREATE table AS SELECT:创建 oldEmployee 表,并复制 employee 中 age 大于20的内容。
创建 oldEmployee 表,并复制 employee 中 age 大于20的内容:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Create sql
String sql = "create table oldEmployee select * from employee where age > 20";
// Execute sql
stmt.executeUpdate(sql);
// Write sql query table: oldEmployee
String sql3 = "select * from oldEmployee;";
// Return the result set
rs = stmt.executeQuery(sql3);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

删除表 oldEmployee 表中 name 等于 Chirs 的行:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "DELETE FROM employee WHERE ename = 'Chirs'";
// Execute sql
stmt.executeUpdate(sql);
// Write sql to query table employee
String sql3 = "SELECT * FROM employee;";
rs = stmt.executeQuery(sql3);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述在这里插入图片描述

使用 truncate 清除表 oldEmployee 表内的数据,保存表结构:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql1 = "TRUNCATE TABLE employee";
// Execute sql
stmt.executeUpdate(sql1);
// View the existence of table structure
String sql2 = "DESC employee;";
rs = stmt.executeQuery(sql2);
System.out.println("表结构为:");
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}
// Write sql to see whether the table data exists
String sql3 = "SELECT * FROM employee";
rs = stmt.executeQuery(sql3);
System.out.println("表数据为:");
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

使用 drop 删除表 employee:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "DROP TABLE employee";
// Execute sql
stmt.executeUpdate(sql);

UPDATE:
将表 employee 中 name 为 Parto 的 age 修改为23:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "UPDATE employee SET age = 23 WHERE ename = 'Parto'";
// Execute sql
stmt.executeUpdate(sql);
// Write sql
String sql3 = "SELECT * FROM employee WHERE ename ='Parto'";
// Execute sql
rs = stmt.executeQuery(sql3);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

REPLACE:
MySQL 中 REPLACE 函数是直接替换 MySQL 数据库中某字段中的特定字符串,不再需要自己写函数去替换,用起来非常方便。
使用 REPLACE 将表 employee 中 Kyoichi 替换为 Kyoic:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "UPDATE employee SET ename = REPLACE(ename,'Kyoichi','Kyoic')";
// Execute sql
stmt.executeUpdate(sql);
// Write sql query table: employee
String sql3 = "SELECT * FROM employee WHERE ename ='Kyoic'";
// Execute sql
rs = stmt.executeQuery(sql3);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

实验 6 执行计划和 CASE 表达式
在这里插入图片描述查看 SELECT * FROM employee 的执行计划:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql3 = "EXPLAIN SELECT * FROM employee WHERE ename ='Parto'";
// Execute sql
rs = stmt.executeQuery(sql3);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

为表 employee 的列 ename 创建索引,再次查看执行计划,发现执行计划改变:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql to modify index
String sql = "ALTER TABLE employee ADD INDEX(ename)";
// Execute sql
stmt.executeUpdate(sql);
// Write SQL to view the execution plan
String sql3 = "EXPLAIN SELECT * FROM employee WHERE ename = 'Parto'";
// Execute sql
rs = stmt.executeQuery(sql3);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

CASE表达式:

CASE 表达式,当 ename 为 ‘Parto’ 时,显示为 ‘P’,不符合 WHEN 条件的 ,显示为 ‘XX’:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql3 = "SELECT ename," +
    "    CASE ename" +
    "        WHEN 'Parto' THEN 'P'" +
    "        WHEN 'Georgi' THEN 'G'" +
    "        WHEN 'Chirs' THEN 'C'" +
    "        ELSE 'XX'" +
    "    END AS mark\n" +
    "FROM" +
    "    employee";
// Execute sql
rs = stmt.executeQuery(sql3);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

查询表 employee,当 empno 字段为 null 时,按 age 排序,其余情况按 empno 排序:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT " +
    "    *" +
    "FROM" +
    "    employee\n" +
    "ORDER BY (CASE" +
    "    WHEN empno IS NULL THEN age" +
    "    ELSE empno\n" +
    "END);";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

实验 7 常用函数
在这里插入图片描述
检索mysql在字符串列表 ‘oracle,sql server,mysql,db2’ 中的位置:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT FIND_IN_SET('mysql','oracle,sql server,mysql,db2');";
// Execute sql
rs = stmt.executeQuery(sql);
// Traverse the query results
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
检索 SQL 在字符串中第一次出现的位置:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT POSITION('SQL' IN 'hello SSQL-MySQL')";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
LOWER():
将 ’SQL Course‘ 转换为小写:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT LOWER('SQL Course')";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
在这里插入图片描述
查询表 products 中 vend_price 的平均值:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT AVG(vend_price) FROM products;";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述使用函数 CURDATE() , CURTIME() , NOW() , UNIX_TIMESTAMP(),返回当前日期、当前时间、当前的日期和时间、日期 ‘2020-4-1’ 的 UNIX 时间戳:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "select CURDATE(),CURTIME(),UNIX_TIMESTAMP('2020-4-1') AS unix_timestamp,NOW();";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

返回日期 ‘2020-04-01‘ 为一年中的第几周、返回日期 ‘2020-04-01’ 的年份、返回 ’1585670400’ 时间戳的日期值:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT WEEK('2020-04-01'),YEAR('2020-04-01'),FROM_UNIXTIME('1585670400');";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

返回 ‘17:21:33’ 的小时值、返回 ’‘17:21:33’‘ 的分钟值、返回 ’2020-04-01‘ 的月份名:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT HOUR('17:21:33'),MINUTE('17:21:33'),MONTHNAME('2020-04-01');";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

返回按字符串fmt格式化日期date值、返回一个日期或时间值加上一个时间间隔的时间值、返回起始时间和结束时间之间的天数:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT DATE_FORMAT(NOW(),'%d %b %y'),DATE_ADD(now(),INTERVAL 1 DAY),DATEDIFF('2020-01-14 14:32:59','2020-01-02');";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
返回当前数据库名、版本号、用户名、字符串 ’abc‘ 的字符集:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT DATABASE(),VERSION(),USER(),CHARSET('abc')";
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

返回最近生成的AUTO_INCREMENT值、返回服务器的连接数、返回字符串 ’abc‘ 的字符排列方式:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT LAST_INSERT_ID(),CONNECTION_ID(),COLLATION('abc')";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
使用 PASSWORD() 加密字符串 abcd:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT PASSWORD('abcd')";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
使用 MD5() 加密字符串 abcd:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT MD5('abcd')";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
使用 ENCODE() 加密:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
stmt.executeUpdate("INSERT INTO lobTab VALUES(4,'jerry',encode('this is a file','key'));");
// Execute sql
String sql = "select * from lobTab where id = 4";
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

实验 8 视图和触发器
在这里插入图片描述
创建视图 employee_view ,视图数据来源于 employee表:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Execute sql
stmt.executeUpdate("CREATE OR REPLACE VIEW employee_view AS SELECT * FROM employee;");

查看视图 employee_view 数据:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT * FROM employee_view";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

删除视图 employee_view:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Execute
stmt.executeUpdate("DROP VIEW employee_view;");

更新修改视图里的记录:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Execute sql
stmt.executeUpdate("UPDATE employee_view SET age = 38 WHERE ENAME = 'Georgi';");
String sql = "SELECT * FROM employee_view where ename = 'Georgi'";
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

修改视图:使用 ALTER 语句修改视图,让视图只存储 employee 表的 ename 和 age 字段
使用 ALTER 语句修改视图,让视图只存储 employee 表的 ename 和 age 字段:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write modify view of sql
String sql1 ="ALTER VIEW employee_view AS SELECT ename,age FROM employee;";
// Execute sql
stmt.executeUpdate(sql1);
// Write query view of sql
String sql2 = "SELECT * FROM employee_view";
rs = stmt.executeQuery(sql2);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

查看所有视图:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql to check all views
String sql = "SHOW TABLE STATUS WHERE COMMENT='view';";
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
创建一个 INSERT 触发器,当 employee 进行 INSERT 时,添加 ‘Employee added’ 到 @result:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Execute sql to create insert trigger
stmt.executeUpdate("CREATE TRIGGER newemployee AFTER INSERT ON employee FOR EACH ROW SELECT 'Employee added' INTO @result;");
// Execute SQL to insert data
stmt.executeUpdate("INSERT INTO employee VALUES(10007,'Bob',22);");
// Write sql to check whether the trigger takes effect
String sql = "SELECT @result;";
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
创建一个 UPDATE 触发器,当 employee 进行 UPDATE 时,添加 ‘Employee updated’ 到 @result:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Execute sql to create update trigger
stmt.executeUpdate("CREATE TRIGGER updateemployee BEFORE UPDATE ON employee FOR EACH ROW SELECT 'Employee updated' INTO @result;");
// Execute sql to update data
stmt.executeUpdate("UPDATE employee SET ename = 'Chiruis' WHERE empno = 10004;");
// Write sql to check whether the trigger takes effect
String sql = "SELECT @result;";
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
创建一个 DELETE 触发器,当 employee 进行 DELETE 时,添加 ‘Employee deleted’ 到 @result:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql to create delete trigger
stmt.executeUpdate("CREATE TRIGGER deleteemployee BEFORE DELETE ON employee FOR EACH ROW SELECT 'Employee deleted' INTO @result;");
stmt.executeUpdate("DELETE FROM employee WHERE empno = 10002;");
String sql = "SELECT @result;";
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

查看触发器:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "show triggers;";
// Execute sql
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

删除触发器 updateemployee:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Execute the delete trigger of sql
stmt.executeUpdate("DROP TRIGGER updateemployee;");
// Write the view trigger of sql
String sql = "SHOW triggers;";
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

实验 9 存储过程和函数
在这里插入图片描述
创建一个无参存储过程,用来计算 employee 表中 age 的平均值

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write SQL to create a parameterless stored procedure
String sql = "CREATE PROCEDURE avgAge()" +
    "BEGIN\n" +
    "SELECT AVG(age) AS avgAge " +
    "FROM employee;" +
    "END";
stmt.executeUpdate(sql);

在这里插入图片描述
创建有参存储过程,通过传入的 ino,取出 employee 中 empno 字段等于 ino 时的 ename 值:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write SQL to create a stored procedure with parameters
String sql = "CREATE PROCEDURE getName(" +
    "IN ino INT," +
    "OUT oname VARCHAR(32)" +
    ")" +
    "BEGIN\n" +
    "SELECT ename FROM employee WHERE empno = ino INTO oname;" +
    "END";
stmt.executeUpdate(sql);

创建有参存储过程,通过传入的 ino,取出 employee 中 empno 字段等于 ino 时的 ename 值:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write SQL to create a stored procedure with parameters
String sql = "CREATE PROCEDURE getName(" +
    "IN ino INT," +
    "OUT oname VARCHAR(32)" +
    ")" +
    "BEGIN\n" +
    "SELECT ename FROM employee WHERE empno = ino INTO oname;" +
    "END";
stmt.executeUpdate(sql);

调用存储过程 avgAge():

// Call the database stored procedure
CallableStatement clbStmt = conn.prepareCall("{CALL avgAge()}");
// Execute the call
rs = clbStmt.executeQuery();
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

删除存储过程 avgAge:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write the drop procedure of sql
String sql = "DROP PROCEDURE avgAge;";
stmt.executeUpdate(sql);

创建自定义函数 createTable:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql to create a custom function
String sql = "CREATE FUNCTION createTable(name VARCHAR(20)) RETURNS VARCHAR(50)" +
    "BEGIN\n" +
    "DECLARE str VARCHAR(50) DEFAULT '';" +
    "SET @tableName=name;" +
    "SET str=CONCAT('CREATE TABLE ',@tableName,'(id INT,name VARCHAR(20));');" +
    "RETURN str;" +
    "END";
stmt.executeUpdate(sql);

删除自定义函数 createTable:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write the drop function of sql
String sql = "DROP FUNCTION IF EXISTS createTable;";
stmt.executeUpdate(sql);

实验 10 事务和锁
在这里插入图片描述把 id =1 对应的余额减少 500 ,id=2 对应的余额增加500:

//0.Start transaction
conn.setAutoCommit(false);
stmt = conn.createStatement();
//1.Select original data
String sql = "select * from account";
rs = stmt.executeQuery(sql);
System.out.println("original data:");
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}
//2.Simulate the transfer: the user balance with id 1 decreases by 500 and the user balance with id 2 increases by 500
String sql1 = "UPDATE account SET balance = balance - 500 WHERE id = 1";
String sql2 = "UPDATE account SET balance = balance + 500 WHERE id = 2";
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
//3.Commit transaction
conn.commit();
//4.View transfer results
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println("final data:");
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

在这里插入图片描述
查看初始数据:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT * FROM employee;";
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

开启事务执行更新操作,并 rollback:

// Turn off the automatic submission
conn.setAutoCommit(false);
// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
String sql1 = "UPDATE employee SET age = 28 WHERE empno = 10001";
String sql2 = "UPDATE employee SET age = 20 WHERE empno = 10004";
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
conn.rollback();

在这里插入图片描述
查看数据:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql = "SELECT * FROM employee;";
rs = stmt.executeQuery(sql);
while (rs.next()) {
    for (int i = 1; i <= rs.getMetaData().getColumnCount() ; i++) {
        System.out.print(rs.getString(i)+"\t");
    }
    System.out.println();
}

模拟事务B中修改一条记录:

// Create a Statement object to send SQL statements to the database
stmt = conn.createStatement();
// Write sql
String sql1 = "UPDATE employee SET age = 28 WHERE empno = 10001";
stmt.executeUpdate(sql1);

测试事务隔离性:

System.out.println("Initial data for employee in transaction a: ");
// Query the initial data
IsolationTest.query(conn, stmt, rs);
// Start transaction A and transaction B
conn.setAutoCommit(false);
conn2.setAutoCommit(false);
// Update a piece of data in transaction B
IsolationTest.update(conn2,stmt,rs);
System.out.println("When the transaction b is not comitted, the employee data in the transaction a are");
IsolationTest.query(conn, stmt, rs);
// Commit transaction B
conn2.commit();
System.out.println("When the transaction b is submitted, the employee data in the transaction a are");
IsolationTest.query(conn, stmt, rs);

在这里插入图片描述
使用悲观锁来实现:
在这里插入图片描述使用 Java 代码模拟悲观锁:

Connection conn = UtilsC3P0.getConnection();
try {
    Statement stmt = conn.createStatement();
    Statement stmt2 = conn.createStatement();
    Statement stmt3 = conn.createStatement();
    String sql1 = "SELECT * FROM t_goods WHERE id = 1 FOR UPDATE;";

    conn.setAutoCommit(false);
    ResultSet rs = stmt2.executeQuery(sql1);
    while (rs.next()) {
        String goods_id = rs.getString("goods_id");
        int status = rs.getInt("status");
        if (1 == status){
            System.out.println("enough,place an order");
            String sql2 = "INSERT INTO t_orders (id,goods_id) VALUES (null,"+ goods_id+");";
            int rs2 = stmt.executeUpdate(sql2);
            if (rs2 != 0){
                System.out.println("success");
            }

            String sql3 = "UPDATE t_goods SET status = 2 WHERE id = 1;";
            int rs3 = stmt3.executeUpdate(sql3);
            if (rs3 != 0){
                System.out.println("update status to 2");
            }

        }else {
            System.out.println("Shortage,can't place an order");
        }
    }

    conn.commit();

} catch (SQLException e) {
    e.printStackTrace();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值