Question

So,

Trying to write a very simple method to update a single column in a database. I keep getting a runtime error of "Syntax Error" near the commented line below

public void SaveStatus(string id, string step)
    {
        // assuming that there is only one matching student ID
        connect = new SqlConnection(connectionString);
        connect.Open();
        dataSet = new DataSet();
        string command = "SELECT * FROM tblSubmissions WHERE Id = " + id;
        dataAdapter = new SqlDataAdapter(command, connect);

        dataAdapter.Fill(dataSet, "tblSubmissions");  // syntax error near here

        dataSet.Tables[0].Rows[0]["StatusID"] = step;

        dataAdapter.Update(dataSet, "tblSubmissions");
        dataAdapter.Dispose();
        connect.Close();
        connect.Dispose();

    }

Hoping someone can point out the obvious problem I'm missing

Was it helpful?

Solution

The query should be "SELECT * FROM tblSubmissions WHERE Id = 'id_value' - you're missing the quotes around the id value.

Use a parametrised query instead of string concatenation to fix your problem and get rid of the SQL injection issue:

SqlCommand cmd = new SqlCommand("SELECT * FROM tblSubmissions WHERE Id = @id" , connect);
cmd.Parameters.Add("@id", SqlDbType.UniqueIdentifier);
cmd.Parameters["@id"].Value = id;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top