如何在sql参数中使用字符串?

8aqjt8rx  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(383)

如何将字符串插入到sql参数中?
像这样:

string clas = "Computer Science";

sql = "SELECT * from STUDENTS where CLASS='clas'";
20jt8wwn

20jt8wwn1#

有两种方法:
这是首选且更安全的方法。你可以用这种事先准备好的陈述

string clas = "Computer Science";
sql = "SELECT * FROM Students WHERE Class=?";

// Prepare the request right here

preparedStatement.setString(1, clas);

// Execute the request down here

更简单但更不安全的选项(易受sql注入攻击)

string clas = "Computer Science";
sql = "SELECT * FROM Students WHERE Class='" + clas + "'";
e4yzc0pl

e4yzc0pl2#

简单回答:
您只需执行以下操作:

string clas = "Computer Science";
sql = "SELECT * FROM Students WHERE Class='" + clas + "'";

好答案:
但是,我们可以做得更好。如果需要多值替换,那怎么办?请参阅下面的代码,它可以替换多个字符串。而且,如果需要,还可以编写sql注入检查。最棒的是,你只要打电话给 prepare() 你就完成了。
使用说明:
使用?在那里你需要放一根绳子。如果需要替换多个字符串,请在调用prepare函数时将所有字符串按顺序排列(作为参数)。另外,请注意准备函数调用 prepare(sql, {param_1, param_2, param_3, ..., param_n}) .
[注:它将与c11及更高版本一起使用。它不适用于c11之前的版本。因此,在编译时,使用-std=c11标志和g]


# include <iostream>

# include <string>

# include <initializer_list>

using namespace std;

// write code for sql injection if you think
// it necessary for your program
// is_safe checks for sql injection
bool is_safe(string str) {
    // check if str is sql safe or not
    // for sql injection
    return true; // or false if not sql injection safe
}

void prepare(string &sql, initializer_list<string> list_buf) {
    int idx = 0;
    int list_size = (int)list_buf.size();

    int i = 0;
    for(string it: list_buf) {
        // check for sql injection
        // if you think it's necessary
        if(!is_safe(it)) {
            // throw error
            // cause, sql injection risk
        }

        if(i >= list_size) {
            // throw error
            // cause not enough params are given in list_buf
        }

        idx = sql.find("?", idx);
        if (idx == std::string::npos) {
            if(i < list_size - 1) {
                // throw error
                // cause not all params given in list_buf are used
            }
        }
        sql.replace(idx, 1, it);

        idx += 1; // cause "?" is 1 char
        i++;
    }
}

// now test it
int main() {
    string sql = "SELECT * from STUDENTS where CLASS=?";
    string clas = "clas";

    prepare(sql, {clas});

    cout << sql << endl;

    string sql2 = "select name from class where marks > ? or attendence > ?";
    string marks = "80";
    string attendence = "40";

    prepare(sql2, {marks, attendence});

    cout << sql2 << endl;

    return 0;
}

[p.s.]:如果有任何不清楚的地方,请随时询问。

相关问题