且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从表中选择一个值并将其保存到变量中?

更新时间:2022-12-12 13:02:17

暂时不要担心 - 你有更严重的问题!

永远不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。改为使用参数化查询。



连接字符串时会导致问题,因为SQL会收到如下命令:

Don't worry about that for a moment - you have much more serious problems!
Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'

就SQL而言,用户添加的引号会终止字符串,并且您会遇到问题。但情况可能更糟。如果我来并改为输入:x'; DROP TABLE MyTable; - 然后SQL收到一个非常不同的命令:

The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:

SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'

哪个SQL看作三个单独的命令:

Which SQL sees as three separate commands:

SELECT * FROM MyTable WHERE StreetAddress = 'x';

完全有效的SELECT

A perfectly valid SELECT

DROP TABLE MyTable;

完全有效的删除表格通讯和

A perfectly valid "delete the table" command

--'

其他一切都是评论。

所以它确实:选择任何匹配的行,从数据库中删除表,并忽略其他任何内容。



所以总是使用参数化查询!或者准备好经常从备份中恢复数据库。你定期做备份,不是吗?



在网站上?世界上任何人都可以访问的地方?您必须立即在整个软件中解决这个问题 - 或者您的数据库(以及它所服务的网站)不会持续很长时间......

And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

And in a website? Where anyone in the world can get access? You have to fix this immediately throughout the whole of your software - or your DB (and the site it serves) will not last long...


查看该代码,我很漂亮确定问题出在代码中。



我没有为您提供解决方案,但会提供一些实用的建议,可以帮助您找到解决方案:

•您的代码容易受到SQL注入攻击 - 参数化你的输入&不要依赖它们在你的SQL语句中安全使用。

•切换到使用ORM。

•你的方法太忙 - 每个方法只做一件事。拥有更简单的方法比仅有一些非常复杂的方法更好。

•你的方法GetMax()是无效的 - 而是让它返回值。
Looking at that code, I'm pretty sure the problem is in the code.

I don't have a solution for you but will offer some practical advice which may help you find the solution:
• Your code is vulnerable to SQL injection attack - parameterize your inputs & don't rely on them to be safe to use in your SQL statement.
• Switch to using an ORM.
• Your methods are too "busy" - have each method do one thing only. It's better to have more simplistic methods than only a few really complex ones.
• Your method GetMax() is void - rather let it return the value instead.