从 C# 在 dbf 中执行查询

execute query in dbf from c#

我正在用 C# 编写一个程序,我正在尝试在 DBF 文件中执行查询,我认为这没问题,但 DataReader 的 HasRows 属性 的值为 false。我认为问题出在日期上。这是我的代码:

 string Con = @"Provider=VFPOLEDB.1;Data Source=\Server\ges_01";
 OleDbConnection ConnectionHandler = new OleDbConnection(Con);
ConnectionHandler.Open();

 string SQL = "SELECT codalb FROM BALBARA WHERE FECALB BETWEEN CTOD('2015/12/07') AND CTOD('2015/12/13') AND CODCLI LIKE '%9' ORDER BY CODALB"
 OleDbCommand Query = new OleDbCommand(SQL, ConnectionHandler);
 OleDbDataReader datareader = Query.ExecuteReader();
while(datareader.Read())
{}

我知道剩下的没问题,因为如果把 string SQL="select codalb from balbara"; 工作正常。

任何人都可以告诉我我做错了什么

这里的问题是 CTOD() 函数不受 OLE DB Provider 支持。

更改您的查询以使用 DTOS() which:

Returns a character-string date in a yyyymmdd format from a specified Date or DateTime expression.

所以结束您的查询可能会变成:

string SQL = String.Format(
    @"SELECT 
        codalb 
    FROM
        balbara 
    WHERE 
        DTOS(fecalb) BETWEEN '{0}' AND '{1}'
        AND codcli LIKE '%9' 
    ORDER BY 
        codalb", 
        dateTimeVariable1.ToString("yyyyMMdd"),
        dateTimeVariable2.ToString("yyyyMMdd"));

注意 1: 查看缩进以帮助您编写可读代码,另外我建议将所有 column/table 名称写成小写,以便您轻松区分你的 "data" 是什么,SQL 是什么。

注意 2: 您可以找到关于 DateTime 类型 here.

的官方格式字符串示例


编辑: 作为@AlanB 评论中的 建议,您应该始终努力使用 parametrized queries instead of a string to prevent SQL Injection 攻击。

关于OLEDB参数的备注:

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.

关于参数的顺序

Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

因此,根据您的查询提供的所有这些信息可能类似于此示例:

OleDbCommand Query = new OleDbCommand();
Query.Connection = ConnectionHandler;
Query.CommandText = 
    @"SELECT 
        codalb 
    FROM
        balbara 
    WHERE 
        DTOS(fecalb) BETWEEN ? AND ?
        AND codcli LIKE '%9' 
    ORDER BY 
        codalb";

Query.Parameters.Add(dateTimeVariable1.ToString("yyyyMMdd"));
Query.Parameters.Add(dateTimeVariable2.ToString("yyyyMMdd"));
OleDbDataReader datareader = Query.ExecuteReader();