简体   繁体   English

在Excel中按日期查询SQL引用(单元格)

[英]SQL query by date with reference in excel (cell)

I have Mysql query through VBA and having error when i used date from cell . 我通过VBA进行Mysql查询,并在使用cell中的日期时出错。 I need to use cell value for looping purpose. 我需要使用单元格值进行循环。 I think its due to date format compatibility between excel and Mysql. 我认为这归因于Excel和Mysql之间的日期格式兼容性。 Appreciate your help. 感谢您的帮助。 Thanks! 谢谢!

For R = 6 to lastrow

SQLQuery2 = "SELECT * FROM Mfg.databasemodels_note where typeId = " & Sheets("Sheet1").Range("B" & R) & " AND date < " & Sheets("Sheet1").Range("I" & R) & " order by date asc limit 1;"

Short answer is that your sql string contains a date that's unrecognizable to MySQL. 简短的答案是您的sql字符串包含MySQL无法识别的日期。 Put a breakpoint just after building the string, run the code, then look at the content of the string; 在构建字符串之后立即放置一个断点,运行代码,然后查看字符串的内容; how's MySQL supposed to make sense of it? MySQL应该如何理解呢?

As per MySQL reference material (link below), here's your updated line of code: 根据MySQL参考资料(下面的链接),这是您更新的代码行:

SQLQuery2 = "SELECT * FROM Mfg.databasemodels_note where typeId = " & Sheets("Sheet1").Range("B" & R).Value & " AND date < " & Format(Sheets("Sheet1").Range("I" & R).Value, "'YYYY-MM-DD Hh:NN:SS'") & " order by date asc limit 1;"

Real answer is that you never, ever want to build a SQL string containing user input, from scratch, because of SQL injection risks . 真正的答案是,由于SQL注入的风险 ,您永远都不会从头开始构建包含用户输入的SQL字符串。 Read How To Invoke a Parameterized ADO Query Using VBA/C++/Java for a quick overview of what you should be doing (on top of running your own basic validation). 阅读“ 如何使用VBA / C ++ / Java调用参数化ADO查询 ”以快速了解应做的事情(在运行自己的基本验证之前)。

Reference material: MySQL 5.7: The DATE, DATETIME, and TIMESTAMP Types / Visual Basic for Applications: Format Function 参考资料: MySQL 5.7:DATE,DATETIME和TIMESTAMP类型 / Visual Basic for Applications:格式函数

Further reading: VBA, ADO.Connection and query parameters / ADODB Command failing Execute with parameterised SQL query 进一步阅读: VBA,ADO.Connection和查询参数 / ADODB命令失败使用参数化SQL查询执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM