-1

我声明一个字符串,它基本上是一个指示符列表,其中 yy 是字母,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);
}

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

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

4

1 回答 1

2

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

您需要保留引号和括号才能使 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;";
于 2012-08-28T18:09:45.453 回答