我已经编写了以下代码来连接到我的数据库。你能不能建议我比这个更好的选择,因为我非常感兴趣的是哪种方式表现更好。以下代码是否实现了Singleton模式?
public static class DbConnect
{
public static DataTable SqlConnection(string query)
{
DataTable dt = null;
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
if (cn.State == ConnectionState.Closed)
{
dt = new DataTable();
cn.Open();
da.Fill(dt);
}
}
return dt;
}
}
}
}
答案 0 :(得分:0)
类似的是,恕我直言,预期:
所以代码看起来像那样:
// I've used KeyValuePair for parameters; probably a specialized class will be better
public static DataTable SqlConnection(string query, params KeyValuePair<String, Object>[] parameters) {
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString)) {
using (SqlCommand cmd = cn.CreateCommand()) {
cmd.CommandText = query;
// Parameters, if they're mentioned
if (!Object.ReferenceEquals(null, parameters))
foreach (var prm in parameters)
cmd.Parameters.AddWithValue(prm.Key, prm.Value);
using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
cn.Open();
DataTable result = new DataTable();
da.Fill(result);
return result;
}
}
}
}
...
DataTable dt1 = SqlConnection("select 123");
DataTable dt2 = SqlConnection(
@"select *
from MyTable
where MyField = @MyParam",
new KeyValuePair<String, Object>("@MyParam", 123));
P.S。代码不是 Singleton 实现,它甚至不是类:只是静态方法。