选择和检索不同行中的多个单元格

时间:2018-01-26 17:03:58

标签: c# sql

我正在尝试检索存在正确所有者的不同行中的多个单元格,但我只能检索第一个匹配并且它停在那里,我已经尝试将其用于for,但我不知道不要想.ExecuteScalar()就是这样做的。也许我只是愚蠢而且完全错了。

代码:

checkPlayerName = API.getPlayerName(player);
string checkOwnedCars = "SELECT COUNT(*) FROM [carOwners] WHERE Owner='" + checkPlayerName + "'";
            con.Open();
            SqlCommand checkCarsCount = new SqlCommand(checkOwnedCars, con);
            int carsCountToVar = Convert.ToInt32(checkCarsCount.ExecuteScalar());
            con.Close();
            for (int i = 0; i < carsCountToVar; i++)
            {
                string displayCars = "SELECT LP FROM [carOwners] WHERE Owner='" + checkPlayerName + "'";
                con.Open();
                SqlCommand displayCarsCMD = new SqlCommand(displayCars, con);
                string displayCarsToVar = displayCarsCMD.ExecuteReader().ToString();
                API.sendChatMessageToPlayer(player, "Owned Vehicle: " + displayCarsToVar.ToString());
                con.Close();
            }

Table

例如,第2行和第3行的LP是我想要存储的,因为两者都属于同一所有者,但只显示第一个单元格数据(1337)。

1 个答案:

答案 0 :(得分:2)

您没有迭代从查询中获得的结果。

  

另外,总是使用参数化查询来防止SQL注入攻击

SqlCommand command = new SqlCommand("SELECT LP FROM [carOwners] WHERE Owner=@checkPlayerName", con);
command.Parameters.AddWithValue("@checkPlayerName",checkPlayerName);

using (SqlDataReader reader = command.ExecuteReader())
{
  while (reader.Read())
  {
     Console.WriteLine(String.Format("{0}",reader["id"]));
     //API.sendChatMessageToPlayer(player, "Owned Vehicle: " + reader["id"].ToString());
   }
}

conn.Close();