2

I'm designing a website using asp.net (webforms) and C#. I have a table which has 23 columns.

In the code below, reader is a SqlDataReader and command is a SqlCommand object. I'm using the following code to output query result from it:

command.CommandText = "SELECT * FROM devices WHERE device_level='" + ACCESS_LVL + "'" + "ORDER BY device_name";
reader = command.ExecuteReader();

and then I loop through it using

while(reader.Read());

to output the results.

However accessing some columns causes an index out of range exception (indexes above 17). My table has 23 columns but reader.FieldCount returns only 18.

This issue is not happening on my local machine when debugging the code. It only happens when I upload the project to my web server.

Using mylittleadmin database management panel (installed on the remote server) I can see all of the 23 columns.

12
  • 5
    Please learn to parametrise your SQL. "WHERE device_level='" + ACCESS_LVL + "'" is wide open to injection and needs to be changed ASAP. Commented Nov 28, 2018 at 15:36
  • 4
    You should also not use SELECT *, instead list the columns that you expect explicitly Commented Nov 28, 2018 at 15:37
  • 1
    Well that is a pretty clear indication that your two databases do not have the same columns in those tables. Commented Nov 28, 2018 at 15:44
  • 1
    You can't possibly query the same table on the same database using the same query and get different columns. Commented Nov 28, 2018 at 15:47
  • 1
    @SeanLange you can if you query it as two different logins, and there are login-specific objects (meaning: objects in two different schemas - maybe abolfa.devices and dbo.devices) Commented Nov 28, 2018 at 15:51

1 Answer 1

7

The SQL server is going to be correct here. If SELECT * FROM devices ... returns 18 columns, then: the devices object on the database being connected to: has 18 columns. It sounds like you've let your schemas diverge between different environments / databases. Alternatively: it is possible that you have multiple logins, and login-specific objects (i.e. objects in two different database schemas in the same database), so: when you query it as you you see one object as devices - and when you query it as the application account you see a different object. Typically, this would be dbo.devices vs abolfa.devices (for example).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.