从C#中选择SQL Server数据库中的特定记录

Mik*_*ike 6 .net c# sql windows sql-server

我目前正在尝试使用具有以下条件的C#从SQL Server数据库中获取一些行:

  • 来自RamResults数据库
  • Results表中
  • 其中Date列等于当前日期

到目前为止,我有以下内容:

// Open the same connection with the same connection string.
using (SqlCeConnection con = new SqlCeConnection(DatabaseControl.conString))
{
   con.Open();
   // Read specific values in the table.
   using (SqlCeCommand com = new SqlCeCommand("SELECT Result FROM RamResults WHERE Date == @Form1.date", con))
   {
      SqlCeDataReader reader = com.ExecuteReader();
      while (reader.Read())
      {
         int resultsoutput = reader.GetInt32(0);
         MessageBox.Show(resultsoutput.ToString());
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

使用SELECT Result FROM RamResults WHERE Date == Form1.date抛出错误:

解析查询时出错.[令牌行号= 1,令牌行偏移= 43,令牌错误= =]

虽然如果我拿出WHERE语句,例如

SELECT Result FROM RamResults
Run Code Online (Sandbox Code Playgroud)

它完美地运作

dkn*_*ack 6

描述

2件事

  1. 使用=而不是==因为这是正确的等于运算符T-SQL.您的查询应该是这样的

    SELECT Result FROM RamResults WHERE Date = @Date

  2. 你忘了传入参数.

样品

// Open the same connection with the same connection string.
using (SqlCeConnection con = new SqlCeConnection(DatabaseControl.conString))
{
    con.Open();
    // Read specific values in the table.
    using (SqlCeCommand com = new SqlCeCommand("SELECT Result FROM RamResults WHERE Date = @Date", con))
    {
        com.Parameters.AddWithValue("@Date", Form1.date);
        SqlCeDataReader reader = com.ExecuteReader();
        while (reader.Read())
        {
            int resultsoutput = reader.GetInt32(0);
            MessageBox.Show(resultsoutput.ToString());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Den*_*aub 5

尝试参数化查询并替换===您的WHERE条款:

// ...
using (SqlCeCommand com = 
    new SqlCeCommand("SELECT Result FROM RamResults WHERE Date = @date", con))
{
    com.Parameters.Add(new SqlParameter("date", Form1.date));
    // ...
}
// ...
Run Code Online (Sandbox Code Playgroud)