雖然 PHP+MySQL 是黃金搭檔,但在 Windows 舊系統上 ASP 連接 MySQL 仍有需求。本文記錄 ODBC 驅動安裝、系統 DSN 建立與 DSN-less 連線兩種方式的完整步驟。
myodbc-<版本>-win32.msi (官網 MySQL Connector/ODBC)MySQL ODBC <版本> DriverMySQL ODBC Driver| 欄位 | 範例值 |
|---|---|
| Data Source Name | my_mysql_dsn |
| Description | MySQL for ASP |
| Server | localhost (或 IP) |
| User | root |
| Password | your_password |
| Database | test_db |
| Port | 3306 |
<%
Dim conn, rs, connStr, sql
connStr = "DSN=my_mysql_dsn;UID=root;PWD=your_password;DATABASE=test_db"
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open connStr
sql = "SELECT username, email FROM users WHERE active = 1"
Set rs = conn.Execute(sql)
If Not rs.EOF Then
Response.Write "<table border='1'><tr><th>Username</th><th>Email</th></tr>"
Do While Not rs.EOF
Response.Write "<tr><td>" & Server.HTMLEncode(rs("username")) & "</td>"
Response.Write "<td>" & Server.HTMLEncode(rs("email")) & "</td></tr>"
rs.MoveNext
Loop
Response.Write "</table>"
Else
Response.Write "No data found."
End If
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
%>
<%
Dim conn, connStr
connStr = "Driver={MySQL ODBC 8.0 Driver};" & _
"Server=localhost;" & _
"Database=test_db;" & _
"UID=root;" & _
"PWD=your_password;" & _
"Option=3;" & _
"Charset=utf8mb4;"
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open connStr
' ... 後續查詢邏輯相同
%>
注意: DSN-less 需在連線字串明確指定 Driver 名稱 (需與 ODBC 管理員中驅動程式名稱完全一致),且建議加上 Charset=utf8mb4 避免中文亂碼。
| 錯誤 | 原因 | 解決 |
|---|---|---|
| Driver not found | 驅動未安裝或 32/64 位元不匹配 | IIS 應用程式集區啟用 32 位元應用程式、安裝對應位元驅動 |
| Access denied | 帳號/密碼/主機不匹配 | GRANT ...@'%'、FLUSH PRIVILEGES、確認防火牆 |
| Character set mismatch | 中文亂碼 | 連線字串加 Charset=utf8mb4、資料表 CHARSET=utf8mb4 |
| Table not found | 大小寫敏感 (Linux 主機) | 確認表名大小寫、lower_case_table_names=1 |
Server.MapPath 讀取網站根目錄外的設定檔GRANT SELECT, INSERT, UPDATE, DELETE ON db.* TO 'asp_user'@'localhost' IDENTIFIED BY 'strong_pass';ASP 連接 MySQL 技術雖屬經典,但在維護舊系統時仍具參考價值。新專案建議採用 .NET Core / Node.js / PHP 等現代技術棧。