首先,让我解释一下当前的情况:我正在从数据库中读取记录并将它们放在一个对象中供以后使用; 今天出现了关于C#类型转换(转换?)的数据库类型的问题.
我们来看一个例子:
namespace Test
{
using System;
using System.Data;
using System.Data.SqlClient;
public enum MyEnum
{
FirstValue = 1,
SecondValue = 2
}
public class MyObject
{
private String field_a;
private Byte field_b;
private MyEnum field_c;
public MyObject(Int32 object_id)
{
using (SqlConnection connection = new SqlConnection("connection_string"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "sql_query";
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow))
{
reader.Read();
this.field_a = reader["field_a"];
this.field_b = reader["field_b"];
this.field_c = reader["field_c"];
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这显然是失败的,因为这三个 …
有没有一种简单的方法将SqlDataReader的当前行的所有列转换为字典?
using (SqlDataReader opReader = command.ExecuteReader())
{
// Convert the current row to a dictionary
}
Run Code Online (Sandbox Code Playgroud)
谢谢
我试图弄清楚如何检查我SqlDataReader是否为空或没有行(意味着保留不存在),然后显示一个消息框.出于某种原因,当我调试一次它遇到While dr.Read())代码时,如果它没有返回结果,它就会退出.
我已经尝试将此代码放在几个不同的位置,但如果没有返回任何记录,似乎都没有触发消息框
if (dr.GetValue(0) == DBNull.Value || !dr.HasRows)
{
MessageBox.Show("Reservation Number Does Not Exist","Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
(read records)
}
Run Code Online (Sandbox Code Playgroud)
我的代码......
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "usp_StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@regnum", regnumber);
using (SqlDataReader dr = cmd.ExecuteReader())
{
//Loop through all the rows, retrieving the columns you need.
while (dr.Read())
{
lblConf.Text = dr.GetValue(0).ToString();
lblName.Text = dr.GetValue(1).ToString() + "," + …Run Code Online (Sandbox Code Playgroud) 我想知道哪一个具有更好的返回性能DataTable.SqlDataReader我在这里使用DataTable.Load(dr)
使用SqlDataReader:
public static DataTable populateUsingDataReader(string myQuery)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(constring))
{
SqlCommand cmd = new SqlCommand(myQuery, con);
con.Open();
SqlDataReader dr = null;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
dt.Load(dr);
}
return dt;
}
}
Run Code Online (Sandbox Code Playgroud)
使用SqlDataAdapter:
public DataTable populateUsingDataAdapter(string myQuery)
{
SqlDataAdapter dap = new SqlDataAdapter(myQuery,cn);
DataSet ds = new DataSet();
dap.Fill(ds);
return ds.Tables[0];
}
Run Code Online (Sandbox Code Playgroud) 我有来自存储过程的一对多关系.我在查询中有几个一对多的关系,我试图将这些字段映射到C#对象.我遇到的问题是由于一对多关系,我得到重复的数据.这是我的代码的简化版本:
这是对象类:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public List<Color> FavoriteColors { get; set; }
public List<Hobby> Hobbies { get; set; }
public Person()
{
FavoriteColors = new List<Color>();
Hobbies = new List<Hobby>();
}
}
public class Color
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Hobby
{
public int Id { get; set; }
public string Name …Run Code Online (Sandbox Code Playgroud) 我有一个SP,我试图返回2个结果集,并在我的.cs文件中我尝试这样的事情:
dr = cmd.ExecuteReader();
while (dr.Read())
{
RegistrationDetails regDetails = new RegistrationDetails()
{
FName = dr["FName"].ToString(),
LName = dr["LName"].ToString(),
MName = dr["MName"].ToString(),
EntityName = dr["EntityName"].ToString(),// in 2nd result set
Percentage = dr["Percentage"].ToString()// in 2nd result set
};
}
Run Code Online (Sandbox Code Playgroud)
但是我得到了:
错误:IndexOutOfRange {"EntityName"}
我有一个SqlDataReader,需要使用SqlDataReader.GetBytes()方法从中读取varbinary(max)列.此方法填充字节数组,因此需要知道要读取的数据长度.
这是我感到困惑的地方.显然,我想读取从这行/列中的数据库返回的所有数据,那么我应该通过什么'length'参数?
据我所知,SqlDataReader没有提供任何方法来发现可用的数据长度,因此这种方法对我来说似乎相当尴尬.
我很想在这里传递int.MaxValue并忘记这个问题,但是有些事情并不适合我.
我知道我可以打电话
byte[] value = (byte[])dataReader["columnName"];
Run Code Online (Sandbox Code Playgroud)
..而这似乎完全在内部处理长度问题.但是,我正在使用一组围绕SqlDataReader.GetXXXX()方法构建的复杂代码生成模板.所以我被绑在使用GetBytes并需要了解它的正确用法.
试着看看if (dr.HasRows)在while (dr.read())函数之前添加一个是否有益.我的意思是,从技术上讲,如果它没有行,它就不会读取,所以如果你先检查它会有关系吗?
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
....do stuff here
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果你只是确保它有值提供,那么这基本上会做同样的事情......
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
....do stuff here
}
}
Run Code Online (Sandbox Code Playgroud) 因此,我们就工作中的DataAccess路径进行了激烈的争论:DataTable或DataReader.
免责声明我在DataReader方面,这些结果震撼了我的世界.
我们最终编写了一些基准来测试速度差异.人们普遍认为DataReader速度更快,但我们想看看速度有多快.
结果让我们感到惊讶.DataTable始终比DataReader更快.有时接近两倍的速度.
所以我转向你,SO的成员.为什么,当大多数文档甚至微软声称DataReader更快时,我们的测试显示不然.
现在代码:
测试工具:
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
DateTime date = DateTime.Parse("01/01/1900");
for (int i = 1; i < 1000; i++)
{
using (DataTable aDataTable = ArtifactBusinessModel.BusinessLogic.ArtifactBL.RetrieveDTModified(date))
{
}
}
sw.Stop();
long dataTableTotalSeconds = sw.ElapsedMilliseconds;
sw.Restart();
for (int i = 1; i < 1000; i++)
{
List<ArtifactBusinessModel.Entities.ArtifactString> aList = ArtifactBusinessModel.BusinessLogic.ArtifactBL.RetrieveModified(date);
}
sw.Stop();
long listTotalSeconds = sw.ElapsedMilliseconds;
MessageBox.Show(String.Format("list:{0}, table:{1}", listTotalSeconds, dataTableTotalSeconds));
}
Run Code Online (Sandbox Code Playgroud)
这是DataReader的DAL:
internal static List<ArtifactString> RetrieveByModifiedDate(DateTime modifiedLast) …Run Code Online (Sandbox Code Playgroud) 使用以下语法从SqlDataReader读取值之间的区别是什么:
Dim reader As SqlClient.SqlDataReader
reader("value").ToString()
Run Code Online (Sandbox Code Playgroud)
要么
Dim reader As SqlClient.SqlDataReader
reader.GetString(reader.GetOrdinal("value"))
Run Code Online (Sandbox Code Playgroud) sqldatareader ×10
c# ×8
.net ×4
ado.net ×2
casting ×1
datatable ×1
linq ×1
methods ×1
performance ×1
sql ×1
sql-server ×1
vb.net ×1