C# 处理 SQL 查询的最佳方式
C# best way to handle SQL query
我想用一个函数读取数据库记录并将结果作为数组传递给另一个函数。我如何使用 .NET4.5 做到这一点?
namespace test
{
class Program
{
static void Main()
{
... data = GetData();
string result = HandleData(data);
}
private static string HandleData(... data)
{
return string result
}
private static ... GetData()
{
... result = new ...;
SqlDataReader reader;
using (SqlConnection conn = new SqlConnection(conf))
{
string query = "SELECT [ID], [Desc], [tID] FROM [table] WHERE [Updated] = 0";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = conn;
reader = cmd.ExecuteReader();
if(reader.HasRows)
{
while (reader.Read())
{
result.Add(reader[0], reader[1], reader[2]);
}
}
reader.Close();
}
catch(Exception e)
{
}
finnaly
{
conn.Close();
conn.Dispose();
}
}
return result;
}
}
}
我应该为 result
变量使用哪种数据类型以及如何正确组织内部数据?
遵循 Whosebug 的规则,我将此文本添加到我的问题中,因为它说问题主要包含代码。
您应该构建 DTO(数据传输对象)以在应用程序周围传递值。
private static void Main(string[] args)
{
var dt = new DataTable();
var col = new DataColumn { DataType = typeof(int), ColumnName = "ID" }; dt.Columns.Add(col);
col = new DataColumn { DataType = typeof(string), ColumnName = "Desc" }; dt.Columns.Add(col);
col = new DataColumn { DataType = typeof(int), ColumnName = "tID" }; dt.Columns.Add(col);
var row = dt.NewRow();
{
row["ID"] = 1;
row["Desc"] = "This is description";
row["tID"] = 2;
}
dt.Rows.Add(row);
var dto = ToDTO<UpdatedDto>(dt);
}
private static List<object> ToDTO<T>(DataTable dt)
{
var reult = (from rw in dt.AsEnumerable()
select new UpdatedDto
{
ID = Convert.ToInt32(rw["ID"]),
Desc = Convert.ToString(rw["Desc"]),
tID = Convert.ToInt32(rw["tID"])
}).ToList();
return reult.ConvertAll<object>(o => (object)o);
}
这是我的方法的代码块,说明我如何提取数据并将其解析为数组。
public int find_data_on_id(string id, out string[] strTxnid)
{
cmd.Parameters.Clear();
cmd.CommandText = @"SELECT name,address FROM [table_name] WHERE id = @id";
cmd.Parameters.AddwithValue("@id",id);
strTxnid = new string[5];
try
{
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
strTxnid[0] = dr["id"].ToString();
strTxnid[1] = dr["name"].ToString();
strTxnid[2] = dr["address"].ToString();
dr.Close();
return 0;
}
catch (Exception ex)
{
console.writeline("db internal error");
return -1;
}
}
调用示例:
public void example_call()
{
string[] info;
int Respond = find_data_on_id(1,out info );
string name = info[1];
string address = info[2];
}
您可以将值从 sql 存储到数据表,然后您可以使用 linq 将数据表转换为数组,这里是代码
Private static ... GetData()
{
try
{
var dt = new DataTable();
var cmd = new SqlCommand();
cmd.CommandText = @"SELECT name,address FROM [table_name] WHERE id = @id";
cmd.Parameters.AddwithValue("@id",id);
var da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
}
finally
{
if (cmd.Connection.State == ConnectionState.Open)
{
cmd.Connection.Close();
}
}
var stringArr = dt.Rows[0].ItemArray.Select(x => x.ToString()).ToArray();
return stringArr;
}
我认为最好的解决方案:
private static DataTable GetData()
{
DataTable result = new DataTable();
using (SqlConnection conn = new SqlConnection(conf))
{
string query = "SELECT [ID], [Desc], [tID] FROM [table] WHERE [Updated] = 0";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
da.Dispose();
}
catch(Exception e)
{
}
finnaly
{
conn.Close();
conn.Dispose();
}
}
return result;
}
我想用一个函数读取数据库记录并将结果作为数组传递给另一个函数。我如何使用 .NET4.5 做到这一点?
namespace test
{
class Program
{
static void Main()
{
... data = GetData();
string result = HandleData(data);
}
private static string HandleData(... data)
{
return string result
}
private static ... GetData()
{
... result = new ...;
SqlDataReader reader;
using (SqlConnection conn = new SqlConnection(conf))
{
string query = "SELECT [ID], [Desc], [tID] FROM [table] WHERE [Updated] = 0";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = conn;
reader = cmd.ExecuteReader();
if(reader.HasRows)
{
while (reader.Read())
{
result.Add(reader[0], reader[1], reader[2]);
}
}
reader.Close();
}
catch(Exception e)
{
}
finnaly
{
conn.Close();
conn.Dispose();
}
}
return result;
}
}
}
我应该为 result
变量使用哪种数据类型以及如何正确组织内部数据?
遵循 Whosebug 的规则,我将此文本添加到我的问题中,因为它说问题主要包含代码。
您应该构建 DTO(数据传输对象)以在应用程序周围传递值。
private static void Main(string[] args)
{
var dt = new DataTable();
var col = new DataColumn { DataType = typeof(int), ColumnName = "ID" }; dt.Columns.Add(col);
col = new DataColumn { DataType = typeof(string), ColumnName = "Desc" }; dt.Columns.Add(col);
col = new DataColumn { DataType = typeof(int), ColumnName = "tID" }; dt.Columns.Add(col);
var row = dt.NewRow();
{
row["ID"] = 1;
row["Desc"] = "This is description";
row["tID"] = 2;
}
dt.Rows.Add(row);
var dto = ToDTO<UpdatedDto>(dt);
}
private static List<object> ToDTO<T>(DataTable dt)
{
var reult = (from rw in dt.AsEnumerable()
select new UpdatedDto
{
ID = Convert.ToInt32(rw["ID"]),
Desc = Convert.ToString(rw["Desc"]),
tID = Convert.ToInt32(rw["tID"])
}).ToList();
return reult.ConvertAll<object>(o => (object)o);
}
这是我的方法的代码块,说明我如何提取数据并将其解析为数组。
public int find_data_on_id(string id, out string[] strTxnid)
{
cmd.Parameters.Clear();
cmd.CommandText = @"SELECT name,address FROM [table_name] WHERE id = @id";
cmd.Parameters.AddwithValue("@id",id);
strTxnid = new string[5];
try
{
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
strTxnid[0] = dr["id"].ToString();
strTxnid[1] = dr["name"].ToString();
strTxnid[2] = dr["address"].ToString();
dr.Close();
return 0;
}
catch (Exception ex)
{
console.writeline("db internal error");
return -1;
}
}
调用示例:
public void example_call()
{
string[] info;
int Respond = find_data_on_id(1,out info );
string name = info[1];
string address = info[2];
}
您可以将值从 sql 存储到数据表,然后您可以使用 linq 将数据表转换为数组,这里是代码
Private static ... GetData()
{
try
{
var dt = new DataTable();
var cmd = new SqlCommand();
cmd.CommandText = @"SELECT name,address FROM [table_name] WHERE id = @id";
cmd.Parameters.AddwithValue("@id",id);
var da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
}
finally
{
if (cmd.Connection.State == ConnectionState.Open)
{
cmd.Connection.Close();
}
}
var stringArr = dt.Rows[0].ItemArray.Select(x => x.ToString()).ToArray();
return stringArr;
}
我认为最好的解决方案:
private static DataTable GetData()
{
DataTable result = new DataTable();
using (SqlConnection conn = new SqlConnection(conf))
{
string query = "SELECT [ID], [Desc], [tID] FROM [table] WHERE [Updated] = 0";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
da.Dispose();
}
catch(Exception e)
{
}
finnaly
{
conn.Close();
conn.Dispose();
}
}
return result;
}