【发布时间】:2021-11-03 18:11:30
【问题描述】:
我正在构建一个像这样的query string。
string query = "SELECT * FROM " + table + " where DATE(Date) > " + howFarBack.ToString("yyyy-MM-dd");
然而,当它执行时
while (dataReader.Read())
我看到日期早于howFarBack ????
public List<OHLC> Select(string table, System.DateTime howFarBack)
{
string query = "SELECT * FROM " + table + " where DATE(Date) > " + howFarBack.ToString("yyyy-MM-dd");
//Create a list to store the result
var list = new List<OHLC>();
//Open connection
if (OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
var ohlc = new OHLC();
ohlc.Date = (System.DateTime)dataReader[0];
ohlc.Open = Math.Round((double)dataReader[1], 2);
【问题讨论】:
-
请使用参数化查询 - 通过连接等方式构建 SQL 查询是灾难的根源。它不仅是许多难以调试的语法错误的来源,而且还是 SQL Injection attacks 的大门。它很可能还可以解决您的直接问题。
-
另外,您应该不缓存连接对象,而是在使用后创建和处置。所以
OpenConnection() == true而不是你想要using(var connection = new MySqlConnection...。你还需要usingcmd和dataReader