cDatabase 测试指南
📖 简介
Demo_Database.bas 是 cDatabase 类的完整测试用例模块,提供了从基础连接到高级功能的全面测试。
📁 文件位置
src/Demos/database/Demo_Database.bas⚙️ 配置说明
在运行测试前,需要修改模块顶部的数据库配置参数:
vb
'数据库配置 - 请根据实际环境修改
Private Const TEST_DB_TYPE As Long = enumDbType.Mysql '1:Access, 2:Mysql, 3:MsSql, 4:Csv
Private Const TEST_DB_ADDRESS As String = "172.18.131.71,3306"
Private Const TEST_DB_USERNAME As String = "root"
Private Const TEST_DB_PASSWORD As String = "root"
Private Const TEST_DB_DATABASE As String = "testdb"数据库类型支持
| 值 | 常量 | 说明 |
|---|---|---|
| 1 | enumDbType.Mysql | MySQL 数据库 |
| 2 | enumDbType.Mysql | MySQL 数据库 |
| 3 | enumDbType.MsSql | SQL Server 数据库 |
| 4 | enumDbType.Csv | CSV 文件数据源 |
连接字符串示例
MySQL 标准连接:
vb
TEST_DB_ADDRESS = "172.18.131.71,3306"MySQL ODBC 自定义 DSN:
vb
TEST_DB_ADDRESS = "DRIVER=VBMAN Mysql ODBC Driver;MULTI_HOST=1;SERVER=10.0.0.252,3306;DATABASE=mysql;UID=root;PWD=root"🚀 运行测试
运行所有测试
vb
'在立即窗口中执行
Demo_Database.RunAllTests运行后将依次执行以下测试:
| 序号 | 测试名称 | 说明 |
|---|---|---|
| 0 | CreateDatabase | 创建测试数据库 |
| 1 | ConnectDisconnect | 连接和断开数据库 |
| 2 | CreateTestTable | 创建测试表 |
| 3 | InsertData | 插入数据测试 |
| 4 | QueryData | 查询数据测试 |
| 5 | UpdateData | 更新数据测试 |
| 6 | DeleteData | 删除数据测试 |
| 7 | Transaction | 事务处理测试 |
| 8 | ParameterizedQuery | 参数化查询测试 |
| 9 | Pagination | 分页查询测试 |
| 10 | LastInsertId | 获取最后插入ID测试 |
| 11 | Count | 统计记录数测试 |
| 12 | TableExists | 检查表是否存在测试 |
| 13 | GetTableFields | 获取表字段列表测试 |
| 14 | BatchInsert | 批量插入数据测试 |
| 15 | GetDatabases | 获取数据库列表测试 |
| 16 | GetTables | 获取表列表测试 |
| 17 | Escape | SQL转义测试 |
| 18 | CheckConnection | 检查连接状态测试 |
| 19 | GetVersion | 获取版本信息测试 |
| 20 | ConnectionPool | 连接池功能测试 |
| 21 | AsyncExecute | 异步执行测试 |
运行单个测试
vb
'运行特定测试用例
Demo_Database.TestSpecificCase "connect"
Demo_Database.TestSpecificCase "query"
Demo_Database.TestSpecificCase "transaction"支持的测试用例名称:
| 名称 | 测试内容 |
|---|---|
database | 创建数据库 |
connect | 连接测试 |
insert | 插入测试 |
query | 查询测试 |
transaction | 事务测试 |
pagination | 分页测试 |
显示帮助信息
vb
Demo_Database.ShowTestHelp📋 测试内容详解
基础连接测试
vb
'测试连接和断开
Private Sub Test_ConnectDisconnect()
Dim bConnect As Boolean
bConnect = TestDB.Connect(TEST_DB_TYPE, TEST_DB_ADDRESS, _
TEST_DB_USERNAME, TEST_DB_PASSWORD, TEST_DB_DATABASE)
If bConnect Then
Debug.Print "数据库连接成功"
Debug.Print "连接状态: " & TestDB.IsConnect
Debug.Print "连接版本: " & TestDB.GetVersion()
End If
End SubCRUD 操作测试
插入数据:
vb
'单条插入
sqlInsert = "INSERT INTO test_users (username, email, age, score) " & _
"VALUES ('张三', 'zhangsan@test.com', 25, 95.5)"
bInsert = TestDB.Sql(sqlInsert).Exec(lAffected)
'批量插入
For i = 1 To 10
sqlInsert = "INSERT INTO test_users (...) VALUES (...)"
bInsert = TestDB.Sql(sqlInsert).Exec(lAffected)
Next i查询数据:
vb
'使用 Recordset 查询
sqlSelect = "SELECT * FROM test_users"
bQuery = TestDB.Sql(sqlSelect).Query()
If bQuery Then
Debug.Print "记录总数: " & TestDB.Rs.RecordCount
End If
'使用 Rows 集合查询
bQuery = TestDB.Sql(sqlSelect).Fetch()
If bQuery Then
Debug.Print "Rows集合数量: " & TestDB.Rows.count
End If事务测试
vb
'测试事务提交
TestDB.TransBegin()
TestDB.Sql("INSERT INTO ...").Exec
TestDB.Sql("INSERT INTO ...").Exec
TestDB.TransCommit()
'测试事务回滚
TestDB.TransBegin()
TestDB.Sql("INSERT INTO ...").Exec
TestDB.TransRollback()参数化查询测试
vb
'参数化插入
sqlInsert = "INSERT INTO test_users (username, email, age, score) VALUES (?, ?, ?, ?)"
bExec = TestDB.Sql(sqlInsert) _
.Param("username", "参数用户1", adVarChar) _
.Param("email", "param1@test.com", adVarChar) _
.Param("age", 35, adInteger) _
.Param("score", 92.5, adDouble) _
.ExecParam()
'参数化查询
sqlSelect = "SELECT * FROM test_users WHERE username = ? AND age > ?"
bQuery = TestDB.Sql(sqlSelect) _
.Param("username", "参数用户1", adVarChar) _
.Param("age", 30, adInteger) _
.QueryParam()分页查询测试
vb
'查询第1页,每页3条
sqlSelect = "SELECT * FROM test_users ORDER BY id"
bQuery = TestDB.Sql(sqlSelect).Page(1, 3).Query()
'查询第2页,使用 Fetch
bQuery = TestDB.Sql(sqlSelect).Page(2, 3).Fetch()
Debug.Print "Rows集合数量: " & TestDB.Rows.count批量插入测试
vb
'准备批量数据
Dim Data As New Collection
Dim Row As Scripting.Dictionary
For i = 1 To 5
Set Row = New Scripting.Dictionary
Row.Add "username", "批量用户" & i
Row.Add "email", "batch" & i & "@test.com"
Row.Add "age", 50 + i
Row.Add "score", 90 + i
Data.Add Row
Next
'执行批量插入
bBatch = TestDB.BatchInsert("test_users", Data)连接池测试
vb
'创建连接池实例
Set dbPool1 = TestDB.ConnInst("Pool1")
Set dbPool2 = TestDB.ConnInst("Pool2")
'使用连接池实例查询
bQuery = dbPool1.Sql("SELECT COUNT(*) AS cnt FROM test_users").Query()
'移除连接池实例
TestDB.ConnInstRemove "Pool1"
TestDB.ConnInstRemove "Pool2"异步执行测试
vb
'异步执行SQL
sqlInsert = "INSERT INTO test_users (...) VALUES (...)"
bExec = TestDB.Sql(sqlInsert).Async().Exec()📊 测试输出示例
======================================================
开始执行 cDatabase 类完整测试
======================================================
>>> 测试0: 创建测试数据库
[OK] 已连接到数据库服务器
数据库 'testdb' 已存在,跳过创建
>>> 测试1: 连接和断开数据库
[OK] 数据库连接成功
连接状态: True
连接版本: ADO 6.1
连接状态检查: 正常
>>> 测试2: 创建测试表
[OK] 测试表创建成功
表存在检查: 存在
>>> 测试3: 插入数据
[OK] 插入单条记录成功
影响行数: 1
插入ID: 1
开始批量插入记录...
[OK] 批量插入完成
>>> 测试4: 查询数据
[OK] 查询成功
记录总数: 11
前3条记录:
ID: 1, 用户名: 张三, 年龄: 25
ID: 2, 用户名: 用户1, 年龄: 21
ID: 3, 用户名: 用户2, 年龄: 22
[OK] Fetch 查询成功
Rows集合数量: 11
第一行数据:
id: 1
username: 张三
email: zhangsan@test.com
...
======================================================
所有测试完成!耗时: 2.35 秒
======================================================⚠️ 注意事项
- 自动创建数据库:测试会自动创建
TEST_DB_DATABASE指定的数据库(如果不存在) - 测试表管理:测试会创建
test_users表,测试结束后自动删除 - 连接配置:确保数据库服务器可访问,用户名密码正确
- 权限要求:需要具有创建数据库、创建表、插入、更新、删除等权限
- ODBC 驱动:使用 MySQL 时需要安装 MySQL ODBC 驱动
🔧 故障排除
连接失败
[FAIL] 数据库连接失败
错误信息: [08001] [Microsoft][ODBC 驱动程序管理器] 未发现数据源名称...解决方案:
- 检查
TEST_DB_ADDRESS是否正确 - 确认 MySQL ODBC 驱动已安装
- 尝试使用自定义 DSN 连接字符串
创建数据库失败
[FAIL] 创建数据库失败
错误信息: Access denied for user...解决方案:
- 确认用户具有创建数据库权限
- 检查用户名密码是否正确
📎 完整源码
以下为 Demo_Database.bas 完整源码:
vb
'===============================================================
' cDatabase 类完整测试用例模块
' 作者:邓伟,215879458@qq.com
' 日期:2026-02-26
' 说明:测试 cDatabase 类的所有功能,包括连接、查询、事务、分页等
'===============================================================
Option Explicit
'数据库配置 - 请根据实际环境修改
Private Const TEST_DB_TYPE As Long = enumDbType.Mysql '1:Access, 2:Mysql, 3:MsSql, 4:Csv
Private Const TEST_DB_ADDRESS As String = "172.18.131.71,3306" '如果使用CUSTOM,这里参数2填写完整DSN,后面参数3+不用填写
Private Const TEST_DB_USERNAME As String = "root"
Private Const TEST_DB_PASSWORD As String = "root"
Private Const TEST_DB_DATABASE As String = "testdb"
'测试数据库对象
Private TestDB As cDataBase
Private TestResult As String
'数据库配置 - 用于创建数据库的连接(不指定数据库)
Private Const ADMIN_DB_DATABASE As String = "" ' 连接时不指定数据库,用于创建新数据库
'===============================================================
' 主测试入口
'===============================================================
Public Sub RunAllTests()
Dim StartTime As Double
StartTime = Timer
Debug.Print "======================================================"
Debug.Print "开始执行 cDatabase 类完整测试"
Debug.Print "======================================================"
Debug.Print ""
'初始化测试数据库
Set TestDB = New cDataBase
'执行所有测试
Call Test_CreateDatabase
Call Test_ConnectDisconnect
Call Test_CreateTestTable
Call Test_InsertData
Call Test_QueryData
Call Test_UpdateData
Call Test_DeleteData
Call Test_Transaction
Call Test_ParameterizedQuery
Call Test_Pagination
Call Test_LastInsertId
Call Test_Count
Call Test_TableExists
Call Test_GetTableFields
Call Test_BatchInsert
Call Test_GetDatabases
Call Test_GetTables
Call Test_Escape
Call Test_CheckConnection
Call Test_GetVersion
Call Test_ConnectionPool
Call Test_AsyncExecute
'清理
Call Test_Cleanup
Call Test_Disconnect
Dim EndTime As Double
EndTime = Timer
Debug.Print ""
Debug.Print "======================================================"
Debug.Print "所有测试完成!耗时: " & Format(EndTime - StartTime, "0.00") & " 秒"
Debug.Print "======================================================"
End Sub
'===============================================================
' 测试0: 创建测试数据库
'===============================================================
Private Sub Test_CreateDatabase()
Debug.Print ">>> 测试0: 创建测试数据库"
On Error GoTo ErrHandler
'先连接到服务器(不指定数据库)
Dim AdminDB As New cDataBase
Dim bConnect As Boolean
bConnect = AdminDB.Connect(TEST_DB_TYPE, TEST_DB_ADDRESS, TEST_DB_USERNAME, TEST_DB_PASSWORD, ADMIN_DB_DATABASE)
If bConnect Then
Debug.Print " [OK] 已连接到数据库服务器"
Else
Debug.Print " [FAIL] 连接数据库服务器失败"
Debug.Print " 错误信息: " & AdminDB.LastErr
Exit Sub
End If
'检查数据库是否已存在
Dim bExists As Boolean
bExists = DatabaseExists(AdminDB, TEST_DB_DATABASE)
If bExists Then
Debug.Print " 数据库 '" & TEST_DB_DATABASE & "' 已存在,跳过创建"
Else
'创建数据库
Dim sqlCreate As String
sqlCreate = "CREATE DATABASE `" & TEST_DB_DATABASE & "` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
Dim bCreate As Boolean
bCreate = AdminDB.Sql(sqlCreate).Exec()
If bCreate Then
Debug.Print " [OK] 数据库 '" & TEST_DB_DATABASE & "' 创建成功"
Else
Debug.Print " [FAIL] 创建数据库失败"
Debug.Print " 错误信息: " & AdminDB.LastErr
End If
End If
'断开管理连接
Call AdminDB.DisConnect
Set AdminDB = Nothing
Debug.Print ""
Exit Sub
ErrHandler:
Debug.Print " [FAIL] 创建数据库时发生错误: " & ERR.Description
Debug.Print ""
End Sub
'辅助函数:检查数据库是否存在
Private Function DatabaseExists(ByVal Db As cDataBase, ByVal DBName As String) As Boolean
On Error GoTo ErrHandler
Dim sqlCheck As String
sqlCheck = "SELECT COUNT(*) AS cnt FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" & DBName & "'"
Call Db.Sql(sqlCheck).Query
If Db.Rs.RecordCount > 0 Then
DatabaseExists = (Db.Rs("cnt") > 0)
Else
DatabaseExists = False
End If
Exit Function
ErrHandler:
DatabaseExists = False
End Function
'===============================================================
' 测试1: 连接和断开数据库
'===============================================================
Private Sub Test_ConnectDisconnect()
Debug.Print ">>> 测试1: 连接和断开数据库"
On Error GoTo ErrHandler
'测试连接
Dim bConnect As Boolean
bConnect = TestDB.Connect(TEST_DB_TYPE, TEST_DB_ADDRESS, TEST_DB_USERNAME, TEST_DB_PASSWORD, TEST_DB_DATABASE)
If bConnect Then
Debug.Print " [OK] 数据库连接成功"
Debug.Print " 连接状态: " & IIf(TestDB.IsConnect, "已连接", "未连接")
Debug.Print " 连接版本: " & TestDB.GetVersion()
Else
Debug.Print " [FAIL] 数据库连接失败"
Debug.Print " 错误信息: " & TestDB.LastErr
End If
'测试连接状态检查
Dim bCheck As Boolean
bCheck = TestDB.CheckConnection()
Debug.Print " 连接状态检查: " & IIf(bCheck, "正常", "异常")
Debug.Print ""
Exit Sub
ErrHandler:
Debug.Print " [FAIL] 测试连接时发生错误: " & ERR.Description
Debug.Print ""
End Sub
'===============================================================
' 测试2: 创建测试表
'===============================================================
Private Sub Test_CreateTestTable()
Debug.Print ">>> 测试2: 创建测试表"
On Error GoTo ErrHandler
'先删除表(如果存在)
Dim sqlDrop As String
sqlDrop = "DROP TABLE IF EXISTS test_users"
Call TestDB.Sql(sqlDrop).Exec
'创建测试表
Dim sqlCreate As String
sqlCreate = "CREATE TABLE test_users (" & _
"id INT PRIMARY KEY AUTO_INCREMENT," & _
"username VARCHAR(50) NOT NULL," & _
"email VARCHAR(100)," & _
"age INT," & _
"score DECIMAL(10,2)," & _
"is_active BOOLEAN DEFAULT TRUE," & _
"create_time DATETIME DEFAULT CURRENT_TIMESTAMP" & _
")"
Dim bCreate As Boolean
bCreate = TestDB.Sql(sqlCreate).Exec()
If bCreate Then
Debug.Print " [OK] 测试表创建成功"
Else
Debug.Print " [FAIL] 测试表创建失败"
Debug.Print " 错误信息: " & TestDB.LastErr
End If
'验证表是否存在
Dim bExists As Boolean
bExists = TestDB.TableExists("test_users")
Debug.Print " 表存在检查: " & IIf(bExists, "存在", "不存在")
Debug.Print ""
Exit Sub
ErrHandler:
Debug.Print " [FAIL] 创建测试表时发生错误: " & ERR.Description
Debug.Print ""
End Sub
'===============================================================
' 测试3: 插入数据
'===============================================================
Private Sub Test_InsertData()
Debug.Print ">>> 测试3: 插入数据"
On Error GoTo ErrHandler
Dim i As Long
Dim sqlInsert As String
Dim bInsert As Boolean
Dim lAffected As Long
'插入单条记录
sqlInsert = "INSERT INTO test_users (username, email, age, score) VALUES ('张三', 'zhangsan@test.com', 25, 95.5)"
bInsert = TestDB.Sql(sqlInsert).Exec(lAffected)
If bInsert Then
Debug.Print " [OK] 插入单条记录成功"
Debug.Print " 影响行数: " & lAffected
Debug.Print " 插入ID: " & TestDB.LastInsertId()
Else
Debug.Print " [FAIL] 插入单条记录失败"
Debug.Print " 错误信息: " & TestDB.LastErr
End If
'批量插入记录
Debug.Print ""
Debug.Print " 开始批量插入记录..."
For i = 1 To 10
sqlInsert = "INSERT INTO test_users (username, email, age, score) VALUES " & _
"('用户" & i & "', 'user" & i & "@test.com', " & (20 + i) & ", " & (80 + i) & ".5)"
bInsert = TestDB.Sql(sqlInsert).Exec(lAffected)
If Not bInsert Then
Debug.Print " [FAIL] 批量插入第 " & i & " 条记录失败: " & TestDB.LastErr
Exit For
End If
Next i
Debug.Print " [OK] 批量插入完成"
Debug.Print ""
Exit Sub
ErrHandler:
Debug.Print " [FAIL] 插入数据时发生错误: " & ERR.Description
Debug.Print ""
End Sub
'===============================================================
' 测试4: 查询数据
'===============================================================
Private Sub Test_QueryData()
Debug.Print ">>> 测试4: 查询数据"
On Error GoTo ErrHandler
'查询所有记录
Dim sqlSelect As String
sqlSelect = "SELECT * FROM test_users"
Dim bQuery As Boolean
bQuery = TestDB.Sql(sqlSelect).Query()
If bQuery Then
Debug.Print " [OK] 查询成功"
Debug.Print " 记录总数: " & TestDB.Rs.RecordCount
'遍历记录
Dim i As Long
If TestDB.Rs.RecordCount > 0 Then
TestDB.Rs.MoveFirst
Debug.Print ""
Debug.Print " 前3条记录:"
For i = 1 To 3
If TestDB.Rs.EOF Then Exit For
Debug.Print " ID: " & TestDB.Rs("id") & ", 用户名: " & TestDB.Rs("username") & ", 年龄: " & TestDB.Rs("age")
TestDB.Rs.MoveNext
Next i
End If
'关闭记录集
If TestDB.Rs.State <> adStateClosed Then
TestDB.Rs.Close
End If
Else
Debug.Print " [FAIL] 查询失败"
Debug.Print " 错误信息: " & TestDB.LastErr
End If
'使用 Fetch 方法查询
Debug.Print ""
bQuery = TestDB.Sql(sqlSelect).Fetch()
If bQuery Then
Debug.Print " [OK] Fetch 查询成功"
Debug.Print " Rows集合数量: " & TestDB.Rows.count
If TestDB.Rows.count > 0 Then
Debug.Print " 第一行数据:"
Dim key As Variant
Dim Row As Scripting.Dictionary
Set Row = TestDB.Rows(1)
For Each key In Row.Keys
Debug.Print " " & key & ": " & Row(key)
Next
End If
Else
Debug.Print " [FAIL] Fetch 查询失败"
End If
Debug.Print ""
Exit Sub
ErrHandler:
Debug.Print " [FAIL] 查询数据时发生错误: " & ERR.Description
Debug.Print ""
End Sub
'===============================================================
' 测试5: 更新数据
'===============================================================
Private Sub Test_UpdateData()
Debug.Print ">>> 测试5: 更新数据"
On Error GoTo ErrHandler
'更新单条记录
Dim sqlUpdate As String
sqlUpdate = "UPDATE test_users SET score = 99.9 WHERE username = '张三'"
Dim bUpdate As Boolean
Dim lAffected As Long
bUpdate = TestDB.Sql(sqlUpdate).Exec(lAffected)
If bUpdate Then
Debug.Print " [OK] 更新成功"
Debug.Print " 影响行数: " & lAffected
'验证更新
Dim sqlCheck As String
sqlCheck = "SELECT score FROM test_users WHERE username = '张三'"
Call TestDB.Sql(sqlCheck).Fetch
If TestDB.Rows.count > 0 Then
Debug.Print " 更新后的分数: " & TestDB.Rows(1)("score")
End If
Else
Debug.Print " [FAIL] 更新失败"
Debug.Print " 错误信息: " & TestDB.LastErr
End If
Debug.Print ""
Exit Sub
ErrHandler:
Debug.Print " [FAIL] 更新数据时发生错误: " & ERR.Description
Debug.Print ""
End Sub
'===============================================================
' 测试6: 删除数据
'===============================================================
Private Sub Test_DeleteData()
Debug.Print ">>> 测试6: 删除数据"
On Error GoTo ErrHandler
'先查询总记录数
Dim lCountBefore As Long
lCountBefore = TestDB.count("test_users")
Debug.Print " 删除前记录数: " & lCountBefore
'删除指定记录
Dim sqlDelete As String
sqlDelete = "DELETE FROM test_users WHERE username = '张三'"
Dim bDelete As Boolean
Dim lAffected As Long
bDelete = TestDB.Sql(sqlDelete).Exec(lAffected)
If bDelete Then
Debug.Print " [OK] 删除成功"
Debug.Print " 影响行数: " & lAffected
'验证删除
Dim lCountAfter As Long
lCountAfter = TestDB.count("test_users")
Debug.Print " 删除后记录数: " & lCountAfter
Else
Debug.Print " [FAIL] 删除失败"
Debug.Print " 错误信息: " & TestDB.LastErr
End If
Debug.Print ""
Exit Sub
ErrHandler:
Debug.Print " [FAIL] 删除数据时发生错误: " & ERR.Description
Debug.Print ""
End Sub
'===============================================================
' 测试7: 事务处理
'===============================================================
Private Sub Test_Transaction()
Debug.Print ">>> 测试7: 事务处理"
On Error GoTo ErrHandler
'测试事务提交
Debug.Print " 测试事务提交:"
Dim bBegin As Boolean
bBegin = TestDB.TransBegin()
Debug.Print " 开始事务: " & IIf(bBegin, "成功", "失败")
If bBegin Then
Dim sqlInsert As String
sqlInsert = "INSERT INTO test_users (username, email, age, score) VALUES ('事务用户1', 'trans1@test.com', 30, 88)"
Call TestDB.Sql(sqlInsert).Exec
sqlInsert = "INSERT INTO test_users (username, email, age, score) VALUES ('事务用户2', 'trans2@test.com', 31, 89)"
Call TestDB.Sql(sqlInsert).Exec
Dim bCommit As Boolean
bCommit = TestDB.TransCommit()
Debug.Print " 提交事务: " & IIf(bCommit, "成功", "失败")
If bCommit Then
Dim lCount As Long
lCount = TestDB.count("test_users")
Debug.Print " 当前记录数: " & lCount
End If
End If
'测试事务回滚
Debug.Print ""
Debug.Print " 测试事务回滚:"
bBegin = TestDB.TransBegin()
Debug.Print " 开始事务: " & IIf(bBegin, "成功", "失败")
If bBegin Then
lCount = TestDB.count("test_users")
sqlInsert = "INSERT INTO test_users (username, email, age, score) VALUES ('回滚用户', 'rollback@test.com', 32, 90)"
Call TestDB.Sql(sqlInsert).Exec
Dim bRollback As Boolean
bRollback = TestDB.TransRollback()
Debug.Print " 回滚事务: " & IIf(bRollback, "成功", "失败")
Dim lCount2 As Long
lCount2 = TestDB.count("test_users")
Debug.Print " 记录数变化: " & lCount & " -> " & lCount2 & " (应保持不变)"
End If
Debug.Print ""
Exit Sub
ErrHandler:
Debug.Print " [FAIL] 事务处理时发生错误: " & ERR.Description
Debug.Print ""
End Sub
'===============================================================
' 测试8: 参数化查询
'===============================================================
Private Sub Test_ParameterizedQuery()
Debug.Print ">>> 测试8: 参数化查询"
On Error GoTo ErrHandler
'测试参数化插入
Dim sqlInsert As String
sqlInsert = "INSERT INTO test_users (username, email, age, score) VALUES (?, ?, ?, ?)"
Dim bExec As Boolean
bExec = TestDB.Sql(sqlInsert) _
.Param("username", "参数用户1", adVarChar) _
.Param("email", "param1@test.com", adVarChar) _
.Param("age", 35, adInteger) _
.Param("score", 92.5, adDouble) _
.ExecParam()
If bExec Then
Debug.Print " [OK] 参数化插入成功"
Debug.Print " 插入ID: " & TestDB.LastInsertId()
Else
Debug.Print " [FAIL] 参数化插入失败"
Debug.Print " 错误信息: " & TestDB.LastErr
End If
'测试参数化查询
Dim sqlSelect As String
sqlSelect = "SELECT * FROM test_users WHERE username = ? AND age > ?"
Dim bQuery As Boolean
bQuery = TestDB.Sql(sqlSelect) _
.Param("username", "参数用户1", adVarChar) _
.Param("age", 30, adInteger) _
.QueryParam()
If bQuery Then
Debug.Print " [OK] 参数化查询成功"
Debug.Print " 查询结果数量: " & TestDB.Rs.RecordCount
Else
Debug.Print " [FAIL] 参数化查询失败"
Debug.Print " 错误信息: " & TestDB.LastErr
End If
Debug.Print ""
Exit Sub
ErrHandler:
Debug.Print " [FAIL] 参数化查询时发生错误: " & ERR.Description
Debug.Print ""
End Sub
'===============================================================
' 测试9: 分页查询
'===============================================================
Private Sub Test_Pagination()
Debug.Print ">>> 测试9: 分页查询"
'获取总记录数
Dim lTotalCount As Long
lTotalCount = TestDB.count("test_users")
Debug.Print " 总记录数: " & lTotalCount
'查询第1页,每页3条
Dim lPageSize As Long
lPageSize = 3
Dim sqlSelect As String
sqlSelect = "SELECT * FROM test_users ORDER BY id"
Dim bQuery As Boolean
bQuery = TestDB.Sql(sqlSelect).Page(1, lPageSize).Query()
If bQuery Then
Debug.Print " [OK] 第1页查询成功"
Debug.Print " 记录数: " & TestDB.Rs.RecordCount
'显示第1页数据
If TestDB.Rs.RecordCount > 0 Then
TestDB.Rs.MoveFirst
Debug.Print " 第1页数据:"
Do While Not TestDB.Rs.EOF
Debug.Print " ID: " & TestDB.Rs("id") & ", 用户名: " & TestDB.Rs("username")
TestDB.Rs.MoveNext
Loop
End If
'关闭记录集以释放资源
If TestDB.Rs.State <> adStateClosed Then
TestDB.Rs.Close
End If
Else
Debug.Print " [FAIL] 第1页查询失败"
Debug.Print " 错误信息: " & TestDB.LastErr
End If
'查询第2页
bQuery = TestDB.Sql(sqlSelect).Page(2, lPageSize).Fetch()
If bQuery Then
Debug.Print ""
Debug.Print " [OK] 第2页查询成功"
Debug.Print " 记录数: " & TestDB.Rows.count
'显示第2页数据
If TestDB.Rows.count > 0 Then
Debug.Print " 第2页数据:"
Dim i As Long
For i = 1 To TestDB.Rows.count
Dim Row As Scripting.Dictionary
Set Row = TestDB.Rows(i)
Debug.Print " ID: " & Row("id") & ", 用户名: " & Row("username")
Next
End If
Else
Debug.Print ""
Debug.Print " [FAIL] 第2页查询失败"
End If
Debug.Print ""
Exit Sub
ErrHandler:
Debug.Print " [FAIL] 分页查询时发生错误: " & ERR.Description
Debug.Print ""
End Sub
'===============================================================
' 单独测试函数
'===============================================================
Public Sub TestSpecificCase(ByVal TestCase As String)
Select Case LCase(TestCase)
Case "database"
Set TestDB = New cDataBase
Call Test_CreateDatabase
Call Test_ConnectDisconnect
Call Test_Disconnect
Case "connect"
Set TestDB = New cDataBase
Call Test_CreateDatabase
Call Test_ConnectDisconnect
Call Test_Disconnect
Case "insert"
Set TestDB = New cDataBase
Call Test_CreateDatabase
Call Test_ConnectDisconnect
Call Test_CreateTestTable
Call Test_InsertData
Call Test_Cleanup
Call Test_Disconnect
Case "query"
Set TestDB = New cDataBase
Call Test_CreateDatabase
Call Test_ConnectDisconnect
Call Test_CreateTestTable
Call Test_InsertData
Call Test_QueryData
Call Test_Cleanup
Call Test_Disconnect
Case "transaction"
Set TestDB = New cDataBase
Call Test_CreateDatabase
Call Test_ConnectDisconnect
Call Test_CreateTestTable
Call Test_Transaction
Call Test_Cleanup
Call Test_Disconnect
Case "pagination"
Set TestDB = New cDataBase
Call Test_CreateDatabase
Call Test_ConnectDisconnect
Call Test_CreateTestTable
Call Test_InsertData
Call Test_Pagination
Call Test_Cleanup
Call Test_Disconnect
Case Else
Debug.Print "未知测试用例: " & TestCase
Debug.Print "可用测试用例: database, connect, insert, query, transaction, pagination"
End Select
End Sub
'===============================================================
' 测试说明文档
'===============================================================
Public Sub ShowTestHelp()
Debug.Print "======================================================"
Debug.Print "cDatabase 类测试用例说明"
Debug.Print "======================================================"
Debug.Print ""
Debug.Print "使用方法:"
Debug.Print "1. 运行所有测试: RunAllTests"
Debug.Print "2. 运行单个测试: TestSpecificCase ""测试名称"""
Debug.Print ""
Debug.Print "可用测试名称:"
Debug.Print " - database : 测试创建数据库"
Debug.Print " - connect : 测试连接"
Debug.Print " - insert : 测试插入"
Debug.Print " - query : 测试查询"
Debug.Print " - transaction: 测试事务"
Debug.Print " - pagination : 测试分页"
Debug.Print ""
Debug.Print "注意: 详细测试代码请参考 src/Demos/database/Demo_Database.bas 源文件"
Debug.Print "======================================================"
End Sub注意: 以上为简化版核心代码展示,完整代码请参考源码文件 src/Demos/database/Demo_Database.bas
最后更新: 2026-05-17