我从类开始,现在我正在一个项目中,该项目涉及将多个类放置在根目录的不同文件夹上,并且每个类都连接到同一数据库。
有没有一种方法可以将连接变量存储在某个地方并在每个类上获取它们?(如包含选项)。
一直在阅读有关类Customer(这是我的示例)的内容,它扩展了myvariables,但我不知道这是否是最佳实践。
你能给我一个提示吗?
您可以创建一个静态类来为您完成所有数据库工作,并公开所需的方法。
public static class DatabaseUtils
{
private const string ConnectionString = "...";
public static int GetCustomerId(string firstName, string lastName)
{
try
{
using (var connection = new SqlConnection(ConnectionString))
using (var command = new SqlCommand("sql stuff"))
{
var result = command.ExecuteScalar();
if (result == DBNull.Value)
return -1;
return (int) result;
}
}
catch (Exception ex)
{
// Log errors + ex
}
}
// Other methods to interact with the database
}
然后,您可以调用类似以下的方法:
int id = DatabaseUtils.GetCustomerId("My", "Name");
如果这最终将成为已部署的应用程序,则可能需要查看将连接字符串存储在中,app.config
以便可以在不重新编译应用程序的情况下更改连接字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句