Create database



  • hello,I create an app that use for save data,but i have an problom!I want when my app execute on other computer for the frist time,automatically create databse on that comuter if not exist! please help me!!



  • Hi snaderi.
    Which database are you using?
    Maybe you can verify if database file exists ( or connection it's possible) at startup and if not, call a function to create database.
    Regards.



  • I use MySQL,when I execute my app other computer thats return this Error:
    UnKnown database 'mydb' QMYSQL:Unable to connect.

    please help me.



  • Did you verify if other computer can accest to mysql server?
    How do you are connecting to mysql server? Can you put a little part of your code here?
    Regards



  • thank you
    my connecting file cantains this code:
    @bool createConnection()
    {
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("sa2");
    db.setUserName("root");
    db.setPassword("");

    if (!db.open()) {
        QMessageBox::critical(0,QObject::tr("Database Error"),
                              db.lastError().text());
        return false;
    }
    
        return true;
    

    }@

    I have only one problem and thats is I forced to create db manually.I want my db create automatically!



  • Well, you must to use sql commands to do this, and some modifications on your code.
    Try this
    @ QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setUserName("root");
    db.setPassword("sdg2101zmv");

    if (!db.isValid()){
        qDebug() << db.lastError().text();
        return;
    }
    
    db.open();
    QString query = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'sa2'";
    QSqlQuery q = db.exec&#40;query&#41;;
    
    if (q.size() == 0){
        db.exec&#40;"CREATE DATABASE IF NOT EXISTS sa2;"&#41;;
        qDebug() << db.lastError().text();
        db.setDatabaseName("sa2");
        bool yourApp::createTables();
    }
    

    @

    Where
    @
    bool yourApp::createTables();
    @

    is necesary if you need create tables to your new database.
    First quere count all databases named "sa2".
    Regars.



  • thanks very much!but this Error occured on line 8:
    return-statement with no value, in function returning 'bool' [-fpermissive]



  • Sure. You must to ajust my example to your code.
    In this case replace line 8 to
    @return false;
    @

    Or don't return and put some message to app user.
    Regards.



  • thanks very much!its work very well!!!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.