简体   繁体   English

代码无法从C#中的数据库正常运行datareader

[英]Code not working properly datareader from database in C#

Hi I got an InvalidCastException saying that "Specified cast is not valid". 嗨,我收到一个InvalidCastException,说“指定的转换无效”。 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();
        }

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. DbDataReader.Read()返回一个布尔值,该布尔值指示是否需要处理另一行结果。 You're currently treating it as if it returns the next result, returning null if it's reach the end of the stream. 您目前正在将其视为返回下一个结果,如果到达流末尾则返回null That's simply not how DbDataReader works. 这根本不是DbDataReader工作方式。

Once you've moved onto the next result, you then need to call GetString or the indexer to get the data yourself. 移至下一个结果后,您需要调用GetString或索引器以自己获取数据。 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. 您还应该对连接,命令和阅读器使用using语句。

 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. 因为必须选择要读取的列和reader.Read().ToString()将仅返回"True""False"而不是您要读取的值。

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. reader.Read()将返回一个Boolean值。

It will be false when there is no more rows available to read. 当没有更多行可供读取时,它将为false。 else it will be true. 否则它将是真实的。

In your case, you are converting the Boolean value to String by using reader.Read().ToString(); 在您的情况下,您正在使用reader.Read().ToString();将布尔值转换为String reader.Read().ToString(); This will assign either "True" or "False" to str so it will not ba null at all(as your while condition is str != null ) hence the while becomes an infinite loop. 这将为str分配“ True”或“ False”,因此它根本不会为null (因为while条件为str != null ),因此while变成了无限循环。 And also Will throws exception if reader has no rows/null 如果读者没有行/空值,Will也会抛出异常

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);          
    }
while (reader.Read())
{
    string word = reader.GetString(0);
    // Use it
}

how to fix this error "Specified cast is not valid" 如何解决此错误“指定的转换无效”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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