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

标签 c# .net sql sql-server windows

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

  • 来自 RamResults 数据库
  • 结果表中
  • 其中 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());
      }
   }
}

使用 SELECT Result FROM RamResults WHERE Date == Form1.date 会引发错误:

There was an error parsing the query. [ Token line number = 1,Token line offset = 43,Token in error = = ]

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

SELECT Result FROM RamResults

完美运行

最佳答案

描述

2 件事

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

    从 RamResults 中选择结果,其中 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());
        }
    }
}

关于c# - 从 C# 中选择 SQL Server 数据库中的特定记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8703352/

相关文章:

SQL Server - 具有 2 个组变量和 2 个聚合计算的动态透视

MySQL - 返回当前日期介于开始日期和结束日期之间的行

c# - 在当前线程执行任务

c# - 当并非所有实例都被使用时,依赖注入(inject)是个好主意吗?

c# - 关于动态文本框的一般概念

python - 我应该在数据库中进行数值计算吗?

c# - TextBox.Clear() 或 TextBox.Text = string.Empty

c# - 具有 ProjectReference 依赖项的 NuGet 版本控制

c# - 我可以使用 Protobuf-net 控制生成类的可见性吗?

c# - 多线程增量并在没有锁的情况下跳过0?