C++ and sql SELECT statement



我有一个快速问题。我是一个尝试将sql和c++结合在一起的新手。我的问题是,当我在数据库中输入要查找的作者时,它会显示未知列"在此处插入作者姓氏"。这是因为输入变量"AuthorLast"在select语句中没有引号。问题是,我不知道如何修复或更改它。

#include<mysql.h>
#include<string>
#include<iostream>
using namespace std;
int main()
{
string AuthorLast;
mysql_library_init(0, NULL, NULL);
MYSQL* con = mysql_init(NULL);
if (con == NULL)
{
cout << mysql_error(con);
exit(1);
}
if (mysql_real_connect(con, "Insert Host here", "Insert ID here", "Password", "DataBase here", 0, NULL, 0) == NULL)
{
cout << mysql_error(con);
exit(1);
}
cout << "Enter in an author from the database: ";
getline(cin, AuthorLast);
string sql;
sql = "SELECT AuthorLast FROM Author WHERE AuthorLast= " + AuthorLast + ";";
const char* C = sql.c_str();
mysql_query(con, C);
MYSQL_RES* result = mysql_store_result(con);
if (result == NULL)
{
cout << mysql_error(con);
exit(1);
}
int field_nums = mysql_num_fields(result);
MYSQL_ROW row;
while (row = mysql_fetch_row(result))
{
for (int i = 0; i < field_nums; i++)
cout << row[i] << endl;
}
mysql_free_result(result);
mysql_close(con);
}

正如其他人所说,只需在SQL文本中添加单引号就可以了,但这会使您容易受到SQL注入的影响。想象一下,有人问一个作者的名字(为了清晰起见,用另一行写(:

SomeAuthor' or ''='

这将导致:

SELECT AuthorLast FROM Author WHERE AuthorLast= 'SomeAuthor' or ''='';

这将导致您的查询返回所有作者的姓氏。尽管这对您来说似乎无关紧要,但如果(例如(您在密码检查查询中使用相同的方法,可能会导致攻击者在不知道用户密码的情况下登录(本质上,您允许用户修改您的查询(。

在将用户的输入包括在查询中之前,您应该彻底清理用户的输入(也就是说,确保它不包含意外字符(,或者(更好的是(使用准备好的语句(对于mysql,我认为您可以查看mysql_stmt_*方法(。

准备好的语句或多或少类似于告诉数据库服务器执行"SELECT AuthorLast FROM Author WHERE AuthorLast=?",并告诉它使用"MyAuthorLast"代替?。因此,如果有人试图在名称中包含引号,服务器会通过添加任何必需的转义符来自动为您清除输入。

最新更新