General
General

Reputation: 1

Code not working properly datareader from database in C#

Hi I got an InvalidCastException saying that "Specified cast is not valid". I don't know where is the problem. Does my code has an error? Wordlist column is text field.

This is my code:

 public static void Load_Processing_Words()
        {
            OleDbConnection con = new OleDbConnection();
            con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\USDB\USDB.accdb; Persist Security Info=False;";
            con.Open();
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = con;
            string query = "Select Wordlist from Words";
            cmd.CommandText = query;
            OleDbDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            //while (str != null)
            {
                string str = reader.GetString(0);
                char[] chArray;
                string[] strArray;
                string str2;
                if (str.Contains("Postfix_Exception"))
                {
                    str = reader.GetString(0);
                    chArray = new char[] { '\t', '\n', '\r' };
                    while (!str.Contains("Prefix_Exception"))
                    {
                        strArray = str.Split(chArray, StringSplitOptions.RemoveEmptyEntries);
                        if (strArray.Length != 0)
                        {
                            str2 = strArray[0];
                            if (!Postfix_Exception.Contains(str2))
                            {
                                Postfix_Exception.Add(str2, 1);
                            }
                        }
                        str = reader.GetString(0);
                    }
                }
              }
                con.Close();
        }

Upvotes: 0

Views: 638

Answers (4)

General
General

Reputation: 1

while (reader.Read())
{
    string word = reader.GetString(0);
    // Use it
}

how to fix this error "Specified cast is not valid"

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

Basically, you're not using the reader properly. DbDataReader.Read() returns a Boolean value indicating whether or not it's managed to need another row of results. You're currently treating it as if it returns the next result, returning null if it's reach the end of the stream. That's simply not how DbDataReader works.

Once you've moved onto the next result, you then need to call GetString or the indexer to get the data yourself. For example, your loop should probably be something like:

while (reader.Read())
{
    string word = reader.GetString(0);
    // Use it
}

Now, that will read one result at a time - but it sounds like you actually really care about the order in which you read results, as if there's one line followed by a bunch of other related words. That sort of structure should be reflected in your database - you shouldn't just assume that "list of lines in text file == list of rows in database". Aside from anything else, you haven't specified any ordering in your query, so the database is free to return those rows in any order it wants, probably losing your implicit structure. More generally, one row in a table shouldn't depend on "the next row"... if you want relationships between rows, those should be expressed in the data.

You should also use using statements for the connection, command and reader.

Upvotes: 4

sujith karivelil
sujith karivelil

Reputation: 29006

What you are doing Wrong: You are not using the reader in right method, that's why it is not working as you expected. The reader.Read() will returns a Boolean value.

It will be false when there is no more rows available to read. else it will be true.

In your case, you are converting the Boolean value to String by using reader.Read().ToString(); This will assign either "True" or "False" to str so it will not b a null at all(as your while condition is str != null) hence the while becomes an infinite loop. And also Will throws exception if reader has no rows/null

Solution:

You can use the reader in a proper way as like the follows:

while (reader.Read())
    { 
      // Enter this loop only when reader has rows
      // Iterate through each row until their is no rows to read.
      // assign value to string variable like the following
      str = reader.GetString(0);          
    }

Upvotes: 1

fubo
fubo

Reputation: 45947

 string str = reader.Read().ToString();
 while (str != null)
 { 

should be

while (reader.Read())
{ 
    string str = (string)reader["Wordlist"]; // or reader[ColIndex]

because you have to select the column you want to read and reader.Read().ToString() will only return "True" or "False" instead of the value you want to read.

Upvotes: 1

Related Questions