Insert Strings that contain “ ` ” or “ ' ” to the database table - Qt

纵然是瞬间 提交于 2019-12-11 19:29:20

问题


I have to insert some strings to MySQL database. The problem is that every time I use " ` " or " ' " it causes errors in the QSqlquery execution. How can I prevent this?


回答1:


Always use bind variables when running your query and you will never have problems with special characters in SQL queries. Here is an example from the documentation:

QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
              "VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");
query.exec();



回答2:


` and ' are comment in SQL, you have to "protect" them with a backslash \ like so

Select bla
From blo
where name = "some \`test\`"



回答3:


You should add escape sequence to add such type of special characters like ', `, \, "

Please add them by adding \ before them.

e.g.

For ' use \'

For " use \"

For \ use \\

For ` use \`




回答4:


// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));

in php, You can use mysql_real_escape_string function: http://php.net/manual/en/function.mysql-real-escape-string.php

Hope will help you!



来源:https://stackoverflow.com/questions/19045281/insert-strings-that-contain-or-to-the-database-table-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!