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)
它完美地运作
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
尝试参数化查询并替换==与=您的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)