简体   繁体   English

SQL INSERT INTO查询C ++

[英]SQL INSERT INTO query C++

I am attempting to send a variable (From QML ) through a C++ function back into the SQL database, I have gotten the SELECT sql function to work but every time I try Insert I received this 我正在尝试通过C++函数将变量(来自QML )发送回SQL数据库,我已经可以使用SELECT sql函数,但是每次尝试插入时,我都会收到此消息

error: QODBCResult::exec: Unable to execute statement: "[Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert the value NULL into column 'ID', table 'Employees.dbo.Employeetable'; column does not allow nulls. INSERT fails. [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated."

Correct syntax but still, now working if anyone else needs this for help. 正确的语法,但是如果其他任何人需要此帮助,现在仍然可以使用。

Here is my code: 这是我的代码:

QString servername, dbname;
//instatiating qstring variables as value of lineEdit
//declaring new sql database object
QSqlDatabase *db = new QSqlDatabase( QSqlDatabase::addDatabase("QODBC"));
//setting q string variables to name of server and database
servername  = "********";
dbname = "Employees";
db->setConnectOptions();
//connecting to database, passing q string variables as arguments
QString dsn = QString("DRIVER={SQL Server};SERVER=%1;DATABASE=%2;Trusted_Connection=Yes;").arg(servername).arg(dbname);/** Build the connection string **/
//declaring database name
db->setDatabaseName(dsn);
//opening db
if(db->open())
{
    qDebug() << "**Successfully connected to database**";
    QSqlQuery query;
    query.prepare("insert into Employeetable(Firstname) values(:var);");
    query.bindValue(":var", var);
    if(!query.exec())
    {
        qFatal("Failed to add");
    }
    qDebug()<< "Insert Success";
}

Your prepare statement is wrong. 您的准备声明是错误的。 Try this: 尝试这个:

query.prepare("insert into Employeetable(Firstname) value(:var);");

If you want to bind a variable, you should have the syntax :var_to_bind 如果要绑定变量,则应使用以下语法:var_to_bind

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM