Selecting specific records in a SQL Server database from C#
Solution 1
Description
2 things
Use
=
instead of==
because this is the right equals operator inT-SQL
. Your Query should be like thisSELECT Result FROM RamResults WHERE Date = @Date
You forget to pass in the parameter.
Sample
// 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());
}
}
}
Solution 2
Try parameterizing your query and replace ==
with =
in your WHERE
clause:
// ...
using (SqlCeCommand com =
new SqlCeCommand("SELECT Result FROM RamResults WHERE Date = @date", con))
{
com.Parameters.Add(new SqlParameter("date", Form1.date));
// ...
}
// ...
Solution 3
Try this:
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())
Always use SQL parameters instead of string concatenation.
Solution 4
Not ==
, use =
for equation in SQL:
WHERE Date = @Form1.date
Solution 5
The operator "==" is invalid syntax for SQL. Use a single equal sign "=" in the where clause.
Mike
Updated on June 13, 2022Comments
-
Mike almost 2 years
I am currently trying to grab some rows from a SQL Server database using C# that are of the following criteria:
- From the
RamResults
database - in the
Results
table - where the
Date
column is equal to the current date
I have the following so far:
// 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()); } } }
Using
SELECT Result FROM RamResults WHERE Date == Form1.date
throws an error:There was an error parsing the query. [ Token line number = 1,Token line offset = 43,Token in error = = ]
Although if I take out the WHERE statement e.g.
SELECT Result FROM RamResults
it works perfectly
- From the