如何使用qt将数据插入sqlite

时间:2014-07-04 05:46:38

标签: c++ sqlite qt4 qml

如何使用sqlite将数据插入qt

query = QSqlQuery("INSERT INTO customer_details (rationcard_num, aadharcard_num, name) 
    values('"+rationcard_num+"','"+aadharcard_num+"','"+name+"')");

3 个答案:

答案 0 :(得分:4)

您可以修改代码并使查询看起来像这样,我认为这将澄清您的疑虑:

准备查询语句

QSqlQuery query;
query.prepare("INSERT INTO customer_details(rationcard_num, aadharcard_num, name) values(:rationcard_num,:aadharcard_num,name)");

绑定值

query.bindValue(":rationcard_num",your_value);
query.bindValue(":aadharcard_num",your_value);
query.bindValue(":name",your_value);

调试

您可以使用qDebug()查找您的查询是否可执行:

qDebug()<<query.exec()<<endl;

如果插入数据,则返回true,否则返回false

答案 1 :(得分:1)

您可以在查询中致电exec()或直接使用exec(const QString& query)进行调用。例如,您可以这样做:

QSqlQuery query;
query.exec("INSERT INTO customer_details (rationcard_num, aadharcard_num, name)" 
            + "values('" + rationcard_num + "','" + aadharcard_num + "','" 
            + name + "')");

如果您想使用预准备语句,则需要使用QSqlDatabase构造查询,在其上调用prepare(statement)并绑定值。例如:

QSqlQuery query;
query.prepare("INSERT INTO person (rationcard_num, aadharcard_num, name) "
               "VALUES (:rationcard_num, :aadharcard_num, :name)");
query.bindValue(":rationcard_num", rationcard_num);
query.bindValue(":aadharcard_num", aadharcard_num);
query.bindValue(":name", name);
query.exec();

答案 2 :(得分:-1)

QSqlQuery query;
query.exec("INSERT INTO customer_details (rationcard_num,aadharcard_num,name)VALUES('"+rationcard_num+"','"+aadharcard_num+"','"+name+")");