股市行情系統需求:1000+ 支股票、每分鐘更新、大量並發查詢。初期採用 Windows NT + SQL Server 6.5 + ODBC + VC++,經大量調優仍難達標。後改用 SQL Server DB-Library 繞過 ODBC,達到 30 次/秒更新、20-30 並發,但成本高、擴展受限。
參考網易 FreeBSD + MySQL 架構,評估 MySQL 具備:
| 操作 | MySQL | MySQL_ODBC | DB2_ODBC | Informix_ODBC | MS-SQL_ODBC | Oracle_ODBC |
|---|---|---|---|---|---|---|
| 索引讀取 200 萬行 | 367s | 464s | 1206s | 121126s | 1634s | 20800s |
| 插入 35 萬行 | 381s | 619s | 3460s | 2692s | 4012s | 11291s |
※ 測試環境與數據集可能針對 MySQL 優化,但足證其高效潛力。
MySQL-shareware-3.22.32-win.zip,執行 Setup 安裝my-example.cnf 為 c:\my.cnf,按需調整c:\mysql\bin\mysqld-shareware --standalonec:\mysql\bin\mysql
DELETE FROM user WHERE Host='localhost' AND User='';
mysqladmin reload
mysqladmin -u root password 'your_password'
my.cnf [client] 區段加 user=root、password=...)c:\mysql\include(專案選項 /I"c:\mysql\include")c:\mysql\lib\opt\libmysql.liblibmysql.dll 複製至 c:\winnt\system32
#include
#include
#include
int main() {
MYSQL *conn = mysql_init(NULL);
if (!conn) { fprintf(stderr, "mysql_init failed\n"); return 1; }
// 連線
if (!mysql_real_connect(conn, "localhost", "root", "password", "testdb", 3306, NULL, 0)) {
fprintf(stderr, "Connect failed: %s\n", mysql_error(conn));
mysql_close(conn);
return 1;
}
// 建表
if (mysql_query(conn, "CREATE TABLE mytable (dt DATETIME, s1 CHAR(6), s2 CHAR(11), i1 INT, i2 INT)")) {
fprintf(stderr, "Create table failed: %s\n", mysql_error(conn));
mysql_close(conn);
return 1;
}
// 插入
if (mysql_query(conn, "INSERT INTO mytable VALUES ('2000-03-10 21:01:30', 'Test', 'MySQLTest', 2000, 3)")) {
fprintf(stderr, "Insert failed: %s\n", mysql_error(conn));
mysql_close(conn);
return 1;
}
// 查詢
if (mysql_query(conn, "SELECT * FROM mytable")) {
fprintf(stderr, "Select failed: %s\n", mysql_error(conn));
mysql_close(conn);
return 1;
}
MYSQL_RES *res = mysql_store_result(conn);
int rows = mysql_num_rows(res);
printf("Query returned %d rows\n", rows);
MYSQL_FIELD *field;
char *col_names[25];
int i = 0;
while ((field = mysql_fetch_field(res))) {
col_names[i++] = field->name;
}
MYSQL_ROW row;
while ((row = mysql_fetch_row(res))) {
for (int k = 0; k < i; k++) {
printf("%s: %s ", col_names[k], row[k] ? row[k] : "NULL");
}
printf("\n");
}
mysql_free_result(res);
mysql_close(conn);
return 0;
}
| 函式 | 用途 |
|---|---|
mysql_init() | 初始化 MYSQL 結構體,傳 NULL 自動分配 |
mysql_real_connect() | 建立 TCP 連線,參數:host、user、passwd、db、port、unix_socket、client_flag |
mysql_query() | 執行 SQL(以 \0 結尾),成功返回 0 |
mysql_store_result() | 取得完整結果集(SELECT/SHOW/DESCRIBE/EXPLAIN),需配合 mysql_free_result() |
mysql_fetch_row() | 逐行取得記錄,返回字串陣列,NULL 表示結束 |
mysql_close() | 關閉連線並釋放資源 |
my.cnf 調優(key_buffer、innodb_buffer_pool、query_cache)、索引設計、分表分庫SHOW STATUS、SHOW PROCESSLIST、慢查詢日誌、Percona Monitoringmysqldump --single-transaction --master-data=2 + Binlog 增量 + 定期驗證還原