【发布时间】:2016-01-05 18:46:09
【问题描述】:
当我尝试在我的行中获取分数的特定数据时,帮助我不断收到此错误。
我的数据库中有这些数据:
PlayerName Score
qwe 20
keith 0
我在 winform 中有这段代码:
using (SqlConnection conn = new SqlConnection("Data Source=Rogue;Initial Catalog=SoftProject;Integrated Security=True"))
{
conn.Open();
try
{
String str1 = "";
using (SqlCommand cmd = new SqlCommand("Select PlayerName,Score from PlayerData where PlayerName = @player", conn))
{
cmd.Parameters.AddWithValue("@player", txtPlayer.Text);
DataTable dataTable= new DataTable();
dataTable.Load(cmd.ExecuteReader());
if(dataTable.Rows.Count>0)
{
// concatenate the two string and get the table score row
str1 = String.Concat(str1, (dataTable.Rows[0]["Score"].ToString()));
}
else
{
//Report error
}
}
conn.Close();
}
catch()
{
MessageBox.Show("No data");
}
}
在此代码中,这会使我的系统出错:
str1 = String.Concat(str1, (dataTable.Rows[0]["Score"].ToString()));
得到'qwe'和'20'的名字和分数就可以了; 但在第二列“基思”和“0”。 我的代码将我标记为错误“位置 0 处没有行”;
string.concat 方法()的问题似乎是什么?
【问题讨论】:
-
是
datatable.Rows[0]的问题,不是string.concat的问题。确保您的查询返回数据表中名称“Keith”的数据 -
这种方法没有问题。您的 SQL 查询没有返回任何数据,因此表中没有任何行。另外,如果你只是从数据库中加载数据,不要使用
DataTable,它是非常低效的。只需使用IDataReader。 -
或使用 .Fill 方法或查看 DataTable.Load Method 的 MSDN 链接
-
所以你已经在 dt 中执行了阅读器和加载,你正试图从 dataTable 而不是 dt 中获取值。
-
@Nikita 是的先生,只是为了在我的表中获取数据“分数”,