Convert a QString for using in SQL queries

前端 未结 1 1269
一整个雨季
一整个雨季 2021-01-24 13:45

I want to generate SQL queries from user input for inserting some data into a database.

The user may input anything. Is there a way in Qt to convert such user inputs in

相关标签:
1条回答
  • 2021-01-24 14:27

    "The user may input anything."

    That doesn't give us much to go by, but I can give you an example of how I would set up a basic insert query.

    // I assume you already have a QSqlDatabase object called 'db'
    QSqlQuery query(db);
    QString s = "INSERT INTO table (colA, colB) VALUES (:valA, :valB);"
    query.prepare(s);
    // You only need to prepare the query once
    // To actually insert values into colA & colB, do this:
    query.bindValue(":valA", QString("stuff to put in colA"));
    query.bindValue(":valB", QString("other stuff for colB"));
    query.exec();
    query.finish();  // you probably don't even need this
    

    The bindValue method takes a QVariant as its second argument (I used strings in my example, but you could use anything supported by the variant type). You just have to make sure the type of the values makes sense for the relevant columns in your database.

    Also, I'm using the syntax from PostgreSQL for my example. I think it's standard, but you may need to change the parameter binding (the :valA :valB stuff) to match what your db engine expects.

    0 讨论(0)
提交回复
热议问题