【C#实战】如何用哈希表高效构建数据库关联表系统?
·
摘要:通过超市价格管理系统案例,揭秘C#中哈希表在数据库表设计中的妙用(文末附完整代码示例)
一、需求场景:超市商品价格管理系统
我们需要构建一个包含三类核心数据的系统:
- Stores表:存储唯一商店名称
- Foods表:存储唯一商品名称
- Prices表:关联商店与商品,记录价格信息
技术挑战:如何确保名称唯一性?如何高效建立多表关联?
二、核心实现方案
1. 基类设计(DBTable)
public class DBTable {
protected Hashtable names = new Hashtable();
protected int index = 0;
// 确保名称唯一的哈希表添加方法
public void addTableValue(string name) {
try {
names.Add(name, index++); // 关键点:利用哈希表自动去重
} catch(ArgumentException) {
// 重复名称自动忽略
}
}
// 抽象方法留给子类实现
public virtual void makeTable(string colName) { ... }
}
2. 派生类实现
(1)Stores表(商店管理)
public class Stores : DBTable {
public void makeTable() {
base.makeTable("Storename"); // 调用基类方法创建表
}
}
(2)Foods表(商品管理)
public class Foods : DBTable {
public string getValue() {
return base.getValue("FoodName"); // 复用基类数据获取逻辑
}
}
三、关键技术:哈希表的妙用
1. 自动去重机制
- 当尝试添加重复键时,
Hashtable.Add()会抛出ArgumentException - 通过try-catch实现静默处理,确保数据唯一性
2. 高效枚举
IEnumerator ienum = names.Keys.GetEnumerator();
while(ienum.MoveNext()) {
string name = (string)ienum.Current;
// 构建数据行...
}
3. 相比传统方案的优点
- 比手动遍历List.Contains()效率更高(O(1)时间复杂度)
- 比数据库UNIQUE约束更早拦截重复数据
四、关联表设计:Prices表的特殊处理
1. 中间对象存储
public class StoreFoodPrice {
public int StoreKey { get; }
public int FoodKey { get; }
public float Price { get; }
// 构造函数...
}
2. 批量插入优化
public class Prices : DBTable {
private ArrayList priceList = new ArrayList();
public void addRow(int storeKey, int foodKey, float price) {
priceList.Add(new StoreFoodPrice(storeKey, foodKey, price));
}
public void makeTable() {
// 批量处理所有价格记录
foreach (StoreFoodPrice sfp in priceList) {
DataRow row = dtable.NewRow();
row["foodKey"] = sfp.FoodKey;
row["storeKey"] = sfp.StoreKey;
row["price"] = sfp.Price;
dtable.Rows.Add(row);
}
}
}
3. 复杂查询示例
SELECT Stores.StoreName, Foods.Foodname, Prices.Price
FROM (Prices INNER JOIN Foods ON Prices.FoodKey=Foods.FoodKey)
INNER JOIN Stores ON Prices.StoreKey=Stores.StoreKey
WHERE Foods.Foodname='牛奶'
ORDER BY Prices.Price
五、性能优化建议
1. 改用泛型集合
可将Hashtable替换为Dictionary<string, int>,获得类型安全和更好性能
2. 批量提交策略
// 在makeTable方法中
using(var transaction = conn.BeginTransaction()) {
try {
adapter.Update(dset);
transaction.Commit();
} catch {
transaction.Rollback();
}
}
3. 索引优化
确保数据库表中建立外键索引:
CREATE INDEX IDX_Prices_FoodKey ON Prices(FoodKey)
更多推荐



所有评论(0)