更改字符串声明时出现奇怪错误

时间:2012-08-28 17:43:35

标签: c# .net debugging

我声明一个基本上是指示符列表的字符串,其中yy是alpha而xxxx是数字。

string sMyString = "('yy-xxxx','yy-xxxx','yy-xxxx','yy-xxxx','yy-xxxx','yy-xxxx')";

if(File.Exists(sFileLocation + sFileName))
{
    txtRunning.Text = "Starting db copy";
    File.Copy(sFileLocation + sFileName, sFileName, true);
    File.Copy(sDbLocation + "clipper.dbf", "clipper.dbf", true);
    File.Copy(sDbLocation + "clipper.dbt", "clipper.dbt", true);

    txtRunning.Text = "Starting datatable population";
    string connString = @"Provider=VFPOLEDB;Data source=.\clipper.dbf";
    string mySelectQuery = "SELECT UPPER(TRIM(field1))," +
        " UPPER(TRIM(field2)), UPPER(TRIM(field3)), UPPER(TRIM(field4))" +
        " FROM `clipper` WHERE condition1 AND field1 IN " + sMyString +
        " ORDER BY field2;";

    DataTable dtClipper = new DataTable();
    DataTable dtNotFound = new DataTable();
    DataTable dTable = new DataTable();

    OleDbConnection conn = new OleDbConnection(connString);
    OleDbDataAdapter adapter = new OleDbDataAdapter();
    adapter.SelectCommand = new OleDbCommand(mySelectQuery, conn);
    adapter.Fill(dtClipper);
}

如果我取出parens,我在dataadapter.fill命令中收到错误,说该函数不存在。如果我将其更改为字符串文字,无论是否有parens,我都会得到相同的错误。如果我按照原样和单引号保留它,它运行得很好。

我需要它只是列表,没有单引号,因为我将它们添加到字典中以用作发生率计数器。我错过了什么?

1 个答案:

答案 0 :(得分:2)

该错误是因为您正在使用该字符串来运行SQL查询,并且没有引号和parens,它是无效的sql。

您需要保留引号和parens以使SQL查询起作用。如果需要以纯字符串的形式访问列表,则将其存储为列表。

List<string> myStrings = new List<String> {
    "yy-xxxx",
    "yy-xxxx",
    "yy-xxxx",
    "yy-xxxx",
    "yy-xxxx",
    "yy-xxxx"
};
string myStringsForSQL = string.Join(myStrings, "','");

string mySelectQuery = "SELECT UPPER(TRIM(field1)), " +
    "UPPER(TRIM(field2)), UPPER(TRIM(field3)), UPPER(TRIM(field4)) " +
    "FROM `clipper` WHERE condition1 AND field1 IN ('" + myStringsForSQL + "') " +
    "ORDER BY field2;";