user1269625
user1269625

Reputation: 3209

C# SQL query not returning anything

I have the public DataTable here and the code looks right, but its not returning anything, the OrderID is correct, the query itself is correct, its not returning anything...can anyone tell me why?

public DataTable get_OrderTransaction_Master_ByOrderID(Int64 orderID)
    {

        cn = new SqlConnection(objCommon.IpcConnectionString);
        cn.Open();

        string query = "select transactionID from dbo.OrderTransaction_Master where orderID = " + orderID;
        SqlCommand queryCommand = new SqlCommand(query, cn);
        SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
        DataTable dataTable = new DataTable();
        dataTable.Load(queryCommandReader);
        cn.Close();
        return dataTable;

    }

Upvotes: 1

Views: 1260

Answers (1)

David
David

Reputation: 73554

Caveat:This is a guess based on incomplete information:

Try this: Change query string and add the line to add the parameter.

    string query = "select transactionID from dbo.OrderTransaction_Master where orderID = @OrderId";
    SqlCommand queryCommand = new SqlCommand(query, cn); 
    queryCommand.Parameters.AddWithValue("@OrderId", orderID);
    SqlDataReader queryCommandReader = queryCommand.ExecuteReader(); 

Explanation: Not only will this prevent SQL Injection, it will automatically assure that the OrderId is handled correctly.

You didn't specify what the data type is for the OrderId in the database. I'm guessing it may be non-numeric. (guid or varchar - I've seen databases that use nun-numeric IDs, so it's not inconceiveable.) If it's non-numeric you may be missing the quotes areound the value.

Example:

Where Id = 1

is NOT the same as

Where Id= '1'

Using a parameterized query will automagically fix this for you.

Upvotes: 2

Related Questions