Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to create a FoxPro dbf table in qt



  • I use QODBC to connect as "Free Table directory", connect is OK, and select in the table is OK. But I can't create a new table. I lost something or just permission deny? How can I fixed it ? Here is my code, I really don't konw how to deal with it , I am new here,

        QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
        QString dsn = "Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=D:/test/;Exclusive=No;Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
        db.setDatabaseName(dsn);
    
        if(!db.open()){  // is OK 
           QMessageBox::critical(0, QObject::tr("Database Error"),db.lastError().text());
           return;
        } else {
                QMessageBox::about(0,"a","succeed");
        }
    
        QSqlQuery query(db);
    
        QString sql = QString::fromLocal8Bit("create table person "
                                              "(id integer primary key, "
                                              "firstname varchar(20), "
                                              "lastname varchar(30), "
                                             "age integer)");
    
        //query.prepare(sql);
        if(query.exec(sql)) {   // fail 
            QMessageBox::about(0,"a","create table succeed");
        } else {
            QMessageBox::critical(0, QObject::tr("Database Error"),db.lastError().text());
        }
    
        query.prepare("INSERT INTO person(id, firstname, lastname,age) VALUES (:id, :forename, :surname,:age)");
        query.bindValue(":id", 1001);
        query.bindValue(":firstname", "Bart");
        query.bindValue(":lastname", "Simpson");
        query.bindValue(":age", 24);
    
        query.exec("INSERT INTO person(id,firstname,lastname,age) VALUES(13,\"fang\", \"nan\", 23)");
        query.exec("select * from person");
        while(query.next()) {
            QMessageBox::about(0,"a",query.value(0).toString());
        }
    
        db.close();```


  • Hi, it's not a permissions problem or so, instead it's Visual Foxpro requiring a nonstandard syntax to create a new table, you could try:

    ...
    QSqlQuery query(db);
    
    QString sql = QString::fromLocal8Bit("create table D:/test/person "
                                          "(id I, "
                                          "firstname C(20), "
                                          "lastname C(30), "
                                         "age I)");
    ...
    

    Note 1: To get the .DBF file created in the correct place, you need to specify D:\Test\ also
    Note 2: Creating a primary key index I think is not supported inside C++ code, think you have to create the index in Visual Foxpro's command window, for more see here


Log in to reply