我构建了一个从数据库表加载单词的系统,但我需要将这些单词添加到“选择”类型的列表(语法构建所需的类型)。
这是我请求从数据库检索单词的代码:
List<string> newWords = new List<string>();
newWords = LexicalOperations.WordLibrary().ToList();
Choices dbList = new Choices(); //Adding them to a Choice List
if (newWords.Count != 0)
{
foreach (string word in newWords)
{
dbList.Add(word.ToString());
}
}
else dbList.Add("Default");
这是我从表中检索数据的代码:
public class LexicalOperations
{
public static List<string> WordLibrary()
{
List<string> WordLibrary = new List<string>();
string conString = "Data Source=.;Initial Catalog=QABase;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(conString))
{
connection.Open();
string sqlIns = "select WordList from NewWords";
SqlCommand cmd = new SqlCommand(sqlIns, connection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
WordLibrary.Add(dr[0].ToString());
}
}
return WordLibrary;
}
}
但是,这会引发异常:System.FormatException,它还声明了消息:
FormatException was unhandled
Double-quoted string not valid.
当我在语音语法生成器中构建选择列表时抛出此错误:
GrammarBuilder graBui = new GrammarBuilder(dbList);
Grammar Gra = new Grammar(graBui);
我做错了什么?为了正确地从数据库中检索单词并将它们添加到选择列表中,应该做什么?
最佳答案
问题似乎是您的 Grammar 类无法处理带双引号的字符串。
因此,解决该问题的最简单方法是删除输入中的双引号。
public class LexicalOperations
{
public static List<string> WordLibrary()
{
List<string> WordLibrary = new List<string>();
string conString = "Data Source=.;Initial Catalog=QABase;Integrated Security=True";
string sqlIns = "select WordList from NewWords";
using (SqlConnection connection = new SqlConnection(conString))
using (SqlCommand cmd = new SqlCommand(sqlIns, connection))
{
connection.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
string noQuotes = reader.GetString(0).Replace("\"", "");
WordLibrary.Add(noQuotes);
// In alternative you could also opt to not add a string with double quotes
// string noQuotes = reader.GetString(0);
// if(noQuotes.IndexOf("\"") < 0)
// WordLibrary.Add(noQuotes);
}
}
}
return WordLibrary;
}
}
请注意,我还删除了 SqlDataAdapter
并填充 DataSet
。在这种情况下,这是无用的,并且显然会阻碍性能,因为您正在执行两个循环。第一个由框架执行以填充数据集,第二个由您的代码执行以将单词添加到 List<string>
变量
关于C# 从数据库加载单词并将其添加到类型 "Choices"的列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26181706/