简体   繁体   中英

MySql Exception by Selecting Auto_Increment Values C#

I want to get the username and userid, but when i executing the command I get the Exception:

Index was out of range. Must be non-negative and less than the size of the collection.\\r\\nParameter name: startIndex"

The Database has the Items: UserID(AutoIncrement Int(9)(PK)) and UserName(Varchar(20))

Code:

using (MySqlConnection connection = new MySqlConnection(DBConnection.ConnectionString))
{
connection.Open();
MySqlCommand getUser = new MySqlCommand("SELECT * FROM User Where UserID = '42'", connection);
MySqlDataReader reader = getUser.ExecuteReader();
if (reader.HasRows){

The Exception is thrown at "ExecuteReader".

Queue

"Select* From User Where UserID ='42'" is Executing without any trouble on the Server.

My Question is:

Why did I get an Index out of Range Exception ?

Edit:

I also tried only the query

SELECT * FROM User Where User

But I get the same exception.

I can insert into the Table and I can get the Last insert ID but when I try to every Database with Select * From XY I get the same Exception. All the Tables are with innobDB and the all have at least 1 primary or foreign key.

Edit2:

If I only select the UserName the Query is working:

Select UserName From User

But when I try to get the UserID

Select UserID From User

I get the Exception:

{"Destination array is not long enough to copy all the items in the collection. Check array index and length."} System.Exception {System.ArgumentException}

尝试42不加引号

"SELECT * FROM User Where UserID = 42"

Maybe this edit of your code can help you.

using (MySqlConnection connection = new MySqlConnection(DBConnection.ConnectionString))
{
    connection.Open();
    MySqlCommand getUser = new MySqlCommand("SELECT * FROM `User` WHERE `User`.`UserID` = 42", connection);
    MySqlDataReader reader = getUser.ExecuteReader();

    //rest of your code
}

I hope you get the idea.

As a wise error spotting procedure I suggest to check if the error is located at sql level.

Try to get rid of the where clause simply executing a plain query

SELECT * FROM `User`

Do you notice some change?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM