1. 程式人生 > >SQL_MySQL having 與 where 的區別 與 執行時機

SQL_MySQL having 與 where 的區別 與 執行時機

package com.test.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;

/**
 * Created by szh on 2017/12/26.
 *
 * @author szh
 * @date 2017/12/26
 */
public class CreateDemoData {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        Boolean result = null;

        try {
            // 載入資料庫驅動
            Class.forName("com.mysql.jdbc.Driver");

            // 通過驅動管理類獲取資料庫連結
            connection = DriverManager
                    .getConnection(
                            "jdbc:mysql://localhost:3306/td_dev?serverTimezone=Asia/Shanghai&characterEncoding=utf-8",
                            "root", "123456");
            // 定義sql語句 ?表示佔位符
            String sql = "INSERT INTO test_having_where (`name`, type, score) VALUES (?, ?, ?)";
            preparedStatement = connection.prepareStatement(sql);

            String[] course = {"english", "chinese", "java", "css", "html"};

            Random random = new Random();


            for (int i = 0; i < 30000; i++) {

                StringBuffer tmpName = new StringBuffer();

                for (int m = 0; m < 8; m++) {
                    int key = random.nextInt() % 26;
                    char s = (char) ('a' + key);
                    tmpName.append(new Character(s));
                }


                preparedStatement.setString(1, tmpName.toString());


                for (int j = 0; j < course.length; j++) {

                    preparedStatement.setString(2, course[j]);
                    preparedStatement.setInt(3, Math.abs(random.nextInt() % 101));

                    // 向資料庫發出sql執行查詢,查詢出結果集
                    result = preparedStatement.execute();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 釋放資源
//            if (resultSet != null) {
//                try {
//                    resultSet.close();
//                } catch (SQLException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}