【发布时间】:2016-11-02 15:47:32
【问题描述】:
我有一个处理数据库列元数据的类。类的属性之一是有问题的表。这通过构造函数传递给对象。同样在构造函数中,我应用一些逻辑来分配类中的其他变量。为此,有许多私有方法可以连接到数据库,查询有关表的内容,并将值返回给变量。
我的问题是我有很多不同的方法做几乎相同的事情,但返回不同的数据类型。所以例如我的代码是这样的
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;
}
还有很多其他类似的方法。这对我来说看起来不太好,所以我想知道这样的最佳实践是什么。
我是否应该将返回类型声明为对象并在将返回值分配给我的变量时进行数据类型转换?
【问题讨论】:
-
这个问题更适合codereview.stackexchange.com
-
“我是否应该将返回类型声明为对象”很可能不是。定义一个封装
Name和Length的类并返回它。 -
您应该使用基于参数的查询,以避免sql注入或其他问题。 msdn.microsoft.com/library/bb738521(v=vs.100).aspx
标签: c# methods code-reuse