我目前正在尝试使用C#从SQL Server数据库中获取以下条件的一些行:
RamResults
数据库 Results
表中 Date
列等于当前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
引发错误:
parsing查询时出现错误。 [令牌行号= 1,令牌行偏移= 43,令牌出错= =]
虽然如果我拿出WHERE语句,例如
SELECT Result FROM RamResults
它完美的作品
2件事
使用=
而不是==
因为这是T-SQL
正确的等号运算符。 你的查询应该是这样的
SELECT Result FROM RamResults WHERE Date = @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 = @Date", con)) { com.Parameters.AddWithValue("@Date", Form1.date); SqlCeDataReader reader = com.ExecuteReader(); while (reader.Read()) { int resultsoutput = reader.GetInt32(0); MessageBox.Show(resultsoutput.ToString()); } } }
尝试参数化您的查询,并在您的WHERE
子句中用=
替换==
:
// ... using (SqlCeCommand com = new SqlCeCommand("SELECT Result FROM RamResults WHERE Date = @date", con)) { com.Parameters.Add(new SqlParameter("date", Form1.date)); // ... } // ...
尝试这个:
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())
始终使用SQL参数而不是字符串连接。
不是==
,在SQL中使用=
for方程式:
WHERE Date = @Form1.date
运算符“==”是SQL的无效语法。 在where子句中使用一个等号“=”。
尝试
var query = "SELECT Result FROM RamResults WHERE Date = " + Form1.date; using (SqlCeCommand com = new SqlCeCommand(query, con))
我建议使用MSDN上的这个例子中的参数
将您的SQL查询替换为以下内容:
SELECT Result FROM RamResults WHERE Date like DATEADD(day, DATEDIFF(day, 0, getdate()), 0)
希望这个作品。
这是相当混乱,许多人犯这样的错误。 虽然C#使用==作为相等的操作(好吧,我们也有Equal()),SQL使用它=。
除此之外,你也忘了在这里传递参数
我发现你的代码中有两件事正在造成一个问题
1)将值赋给参数2)==而不是=(只是为了使其适用于SQL)
所以代码应该是这样的:
using (SqlCeConnection con = new SqlCeConnection(DatabaseControl.conString)) { con.Open(); 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()); } } }