我有一个处理数据库列元数据的类。类的属性之一是有问题的表。这是通过构造函数传递给对象的。同样在构造函数中,我应用了一些逻辑来分配类中的其他变量。为此,有许多连接到数据库的私有(private)方法,查询有关表的某些信息,并将值返回给变量。
我的问题是我有很多不同的方法做几乎相同的事情,但返回不同的数据类型。所以例如我的代码是这样的
public Column(string tableName)
{
strTableName = tableName;
pkColumnName = GetPKColumnName(tableName);
pkColumnLenght = GetPKColumnLenght(tableName);
}
private string GetPKColumnName(string tableName)
{
string query = String.Format("SELECT myColName FROM myTable where myTableName = {0}", tableName);
string result = "";
try
{
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(query, con))
{
result = (string)command.ExecuteScalar();
}
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
private int GetPKColumnLenght(string tableName)
{
string query = String.Format("SELECT myColLenght FROM myTable where myTableName = {0}", tableName);
int result = 0;
try
{
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(query, con))
{
result = (int)command.ExecuteScalar();
}
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
类似的方法还有很多。这对我来说看起来不太好,所以我想知道对于这样的事情最好的做法是什么。
我是否应该只将返回类型声明为对象并在将返回值分配给我的变量时进行数据类型转换?
最佳答案
我的回答和另一个假设不同的问题。在我看来,您正在尝试从特定列中查询单个值,并且您必须创建一个新方法,因为类型不同。也就是说,我个人只会使用一个简单的 ORM 解决方案,而另一个答案当然没有错,只是另一种抽象。
您将希望使用泛型并强制转换为泛型。
我没有测试过这段代码,它更像是一个指南。
private T GetValue<T>(string tableName, colName)
{
string query = String.Format("SELECT {0} FROM myTable where myTableName = {1}", colName, tableName);
T result = default(T);
try
{
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(query, con))
{
result = (T)command.ExecuteScalar();
}
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
关于c#减少用于从数据库获取数据的方法的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40384154/