当前位置: 首页>>代码示例>>C++>>正文


C++ QSqlDatabase::connectionName方法代码示例

本文整理汇总了C++中QSqlDatabase::connectionName方法的典型用法代码示例。如果您正苦于以下问题:C++ QSqlDatabase::connectionName方法的具体用法?C++ QSqlDatabase::connectionName怎么用?C++ QSqlDatabase::connectionName使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QSqlDatabase的用法示例。


在下文中一共展示了QSqlDatabase::connectionName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: begin

bool TSqlTransaction::begin(QSqlDatabase &database)
{
    if (!database.isValid()) {
        tSystemError("Can not begin transaction. Invalid database: %s", qPrintable(database.connectionName()));
        return false;
    }

    if (!enabled)
        return true;
    
    bool ok;
    int id = database.connectionName().left(2).toInt(&ok);
    
    if (!ok || id < 0 || id >= databases.count()) {
        tSystemError("Internal Error  [%s:%d]", __FILE__, __LINE__);
        return false;
    }
    
    if (databases[id].isValid()) {
        tSystemWarn("Has begun transaction already. database:%s", qPrintable(database.connectionName()));
        return true;
    }

    if (database.transaction()) {
        tQueryLog("[BEGIN] [databaseId:%d]", id);
    }

    databases[id] = database;
    return true;
}
开发者ID:deniskin82,项目名称:treefrog-framework,代码行数:30,代码来源:tsqltransaction.cpp

示例2: populateDatabase

bool FrenchZipCodesStep::populateDatabase()
{
    Q_EMIT progressLabelChanged(tr("Reading raw sources..."));
    Q_EMIT progressRangeChanged(0, 1);
    Q_EMIT progress(0);

    // import the raw source in memory
    createDatabase();
    QSqlDatabase db = QSqlDatabase::database(DB_NAME);

    if (!db.tables().contains("ZIPS_IMPORT")) {
        Utils::Database::executeSqlFile(DB_NAME, sqlImportFileAbsPath());
    }

    if (!Utils::Database::importCsvToDatabase(DB_NAME, csvFileAbsPath(), "ZIPS_IMPORT", ";", true))
        return false;

    Q_EMIT progressLabelChanged(tr("Reading raw sources..."));
    Q_EMIT progress(1);

    // create the new database
    QString req;

    // remove alread recorded french codes
    req = "DELETE FROM `ZIPS` WHERE `ZIPS`.`COUNTRY`='fr';";
    Utils::Database::executeSQL(req, db);

    // OLD table: import new french codes
    // 4 chars
//    select * from zips where length(ZIP)>5;
//    select substr('00000' || ZIP, -5, 5) from ZIPS where zip like'14%';
    req = "INSERT INTO `ZIPS` (`ZIP`,`CITY`,`EXTRACODE`, `COUNTRY`) \n"
          "SELECT substr('00000' || ZIP, -5, 5), `COMMUNE`, `CODEINSEE`, 'fr' FROM `ZIPS_IMPORT` WHERE LENGTH(ZIP)=4 ORDER BY `ZIP`;";
    Utils::Database::executeSQL(req, db);
    // 5 chars
    req = "INSERT INTO `ZIPS` (`ZIP`,`CITY`,`EXTRACODE`, `COUNTRY`) \n"
          "SELECT substr(`ZIP`, 1, 5) , `COMMUNE`, `CODEINSEE`, 'fr' FROM `ZIPS_IMPORT` WHERE LENGTH(ZIP)>=5 ORDER BY `ZIP`;";
    Utils::Database::executeSQL(req, db);

    // clean database
    req = "DROP TABLE ZIPS_IMPORT;";
    Utils::Database::executeSQL(req, db);
    Utils::Database::vacuum(db.connectionName());

    // NEW table: import new french codes
    req = "DELETE FROM `IMPORT`";
    Utils::Database::executeSQL(req, db);
    req = "INSERT INTO `IMPORT` (`ZIP`,`CITY`,`ADMIN_CODE1`, `COUNTRY`) \n"
          "SELECT `ZIP`, `CITY`, `EXTRACODE`, 'FR' FROM `ZIPS`;";
    Utils::Database::executeSQL(req, db);

    // Add version
    setDatabaseVersion(db.connectionName(), QString(PACKAGE_VERSION), QDate::currentDate());

    LOG(QString("Database processed"));

    return true;
}
开发者ID:NyFanomezana,项目名称:freemedforms,代码行数:58,代码来源:frenchzipcodespage.cpp

示例3: ini

static v8::Handle<v8::Value> qmlsqldatabase_changeVersion(const v8::Arguments& args)
{
    if (args.Length() < 2)
        return v8::Undefined();

    QV8SqlDatabaseResource *r = v8_resource_cast<QV8SqlDatabaseResource>(args.This());
    if (!r || r->type != QV8SqlDatabaseResource::Database)
        V8THROW_REFERENCE("Not a SQLDatabase object");

    QV8Engine *engine = r->engine;

    QSqlDatabase db = r->database;
    QString from_version = engine->toString(args[0]);
    QString to_version = engine->toString(args[1]);
    v8::Handle<v8::Value> callback = args[2];

    if (from_version != r->version)
        V8THROW_SQL(SQLEXCEPTION_VERSION_ERR, QQmlEngine::tr("Version mismatch: expected %1, found %2").arg(from_version).arg(r->version));

    v8::Local<v8::Object> instance = databaseData(engine)->queryConstructor->NewInstance();
    QV8SqlDatabaseResource *r2 = new QV8SqlDatabaseResource(engine);
    r2->type = QV8SqlDatabaseResource::Query;
    r2->database = db;
    r2->version = r->version;
    r2->inTransaction = true;
    instance->SetExternalResource(r2);

    bool ok = true;
    if (callback->IsFunction()) {
        ok = false;
        db.transaction();

        v8::TryCatch tc;
        v8::Handle<v8::Value> callbackArgs[] = { instance };
        v8::Handle<v8::Function>::Cast(callback)->Call(engine->global(), 1, callbackArgs);

        if (tc.HasCaught()) {
            db.rollback();
            tc.ReThrow();
            return v8::Handle<v8::Value>();
        } else if (!db.commit()) {
            db.rollback();
            V8THROW_SQL(SQLEXCEPTION_UNKNOWN_ERR,QQmlEngine::tr("SQL transaction failed"));
        } else {
            ok = true;
        }
    }

    r2->inTransaction = false;

    if (ok) {
        r2->version = to_version;
#ifndef QT_NO_SETTINGS
        QSettings ini(qmlsqldatabase_databaseFile(db.connectionName(),engine) + QLatin1String(".ini"), QSettings::IniFormat);
        ini.setValue(QLatin1String("Version"), to_version);
#endif
    }

    return v8::Undefined();
}
开发者ID:crobertd,项目名称:qtdeclarative,代码行数:60,代码来源:plugin.cpp

示例4: QSqlDatabaseWrapper

    QSqlDatabaseWrapper(const DatabaseInfo &info)
        : m_open(false)
    {
        m_connectionName =
            "kactivities_db_resources_"
            // Adding the thread number to the database name
            + QString::number((quintptr)info.thread)
            // And whether it is read-only or read-write
            + (info.openMode == Database::ReadOnly ? "_readonly" : "_readwrite");

        m_database =
            QSqlDatabase::contains(m_connectionName)
            ? QSqlDatabase::database(m_connectionName)
            : QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), m_connectionName);

        if (info.openMode == Database::ReadOnly) {
            m_database.setConnectOptions(QStringLiteral("QSQLITE_OPEN_READONLY"));
        }

        // We are allowing the database file to be overridden mostly for testing purposes
        m_database.setDatabaseName(ResourcesDatabaseSchema::path());

        m_open = m_database.open();

        if (!m_open) {
            qWarning() << "KActivities: Database is not open: "
                       << m_database.connectionName()
                       << m_database.databaseName()
                       << m_database.lastError();

            if (info.openMode == Database::ReadWrite) {
                qFatal("KActivities: Opening the database in RW mode should always succeed");
            }
        }
    }
开发者ID:KDE,项目名称:kactivitymanagerd,代码行数:35,代码来源:Database.cpp

示例5: RefreshableSqlQueryModel

RoomQueryModel::RoomQueryModel(const QVariantMap &columnLabels, QSqlDatabase db,
                               QObject *parent)
    : RefreshableSqlQueryModel(QUERY, db.connectionName(), parent) {
    const auto &rec = record();
    for (auto i = 0; i < rec.count(); i++) {
        setHeaderData(i, Qt::Horizontal, columnLabels[rec.fieldName(i)]);
    }
}
开发者ID:toptan,项目名称:paso,代码行数:8,代码来源:roomquerymodel.cpp

示例6: QString

SqlQuery::SqlQuery(const QString &query /*= QString()*/, const QSqlDatabase& db /*= QSqlDatabase()*/ ) :
    QSqlQuery( db ), m_db( db )
{
    m_connectionName = db.connectionName();

    SqlQueryManager::instance()->registerQuery(this);
    if ( !query.isEmpty() )
        exec( query );
}
开发者ID:02JanDal,项目名称:sqlate,代码行数:9,代码来源:SqlQuery.cpp

示例7: qWarning

/**
 * Inject icd10 downloaded files data into the SQLite database.
 * You must create the database first.
 * \sa createDatabase()
 */
bool Icd10Step::populateDatabaseWithRawSources()
{
    qWarning() << "populate ICD10 database";
    QStringList files;
    files
            << "CHAPTER"
            << "COMMON"
            << "DAGSTAR"
            << "DESCR"
            << "DESCRLIB"
            << "EXCLUDE"
            //            << "FIELDDEF"
            << "GLOSSAIRE"
            //            << "HTML"
            << "INCLUDE"
            << "INDIR"
            << "LIBELLE"
            << "MASTER"
            << "MEMO"
            << "NOTE"
            << "REFER"
            << "SYSTEM"
//            << "TABLE"
            << "VERSION"
            ;
//    if (!m_Progress) {
//        m_Progress = new QProgressDialog(tr("Populating database"), tkTr(Trans::Constants::CANCEL), 0, files.count() +1);
//    } else {
//        m_Progress->setRange(0, files.count() +1);
//    }
//    m_Progress->setValue(1);

    // Check database connection
    QSqlDatabase DB = QSqlDatabase::database(d->_connection);
    if (!DB.isOpen()) {
        if (!DB.open()) {
            LOG_ERROR(tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                 .arg(DB.connectionName()).arg(DB.lastError().text()));
            return false;
        }
    }

    // Convert downloaded files from ISO 8859-1 to UTF-8, then import them to the database
    QString path = d->_tmpPath + "/Exp_text/";
    foreach(const QString &file, files) {
        QString content;
        // Convert file
        content = Utils::readTextFile(path + file + ".txt", "ISO 8859-1", Utils::DontWarnUser);
        Utils::saveStringToFile(content, path + file + "-utf8.txt", Utils::Overwrite, Utils::DontWarnUser);
        // import files
        if (!Utils::Database::importCsvToDatabase(d->_connection, path + file + "-utf8.txt", file.toLower(), "¦", true)) {
            LOG_ERROR("Unable to import CSV data to database");
            continue;
        }
    }
开发者ID:Dinesh-Ramakrishnan,项目名称:freemedforms,代码行数:60,代码来源:icd10step.cpp

示例8: createDB

bool createDB(const QString &path) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(path);
    if (!db.open()) {
        return false;
    }
    bool r;
    QSqlQuery query(db);
    r = query.exec("create table `fx_user` ("
        "`id` integer primary key,"
        "`name` varchar(32) not null unique,"
        "`email` varchar(32),"
        "`true_name` varchar(16),"
        "`department` integer not null,"
        "`icon` text,"
        "`status` int(1) not null default 1,"
        "`gmt_create` datetime not null,"
        "`gmt_modify` datetime not null"
        ");");if (!r)return r;
    r = query.exec("create table `fx_department` ("
        "`id` integer primary key,"
        "`parent_id` integer not null default 0,"
        "`name` varchar(32) not null,"
        "`gmt_create` datetime not null,"
        "`gmt_modify` datetime not null"
        ");");if (!r)return r;
    r = query.exec("create table `fx_chatlog` ("
        "`id` integer primary key,"
        "`sourceid` integer not null,"
        "`targetid` integer not null,"
        "`type` int(1) not null,"
        "`msg` text,"
        "`gmt_create` datetime not null"
        ");");if (!r)return r;
    r = query.exec("create table `fx_recent_contact` ("
        "`userid` integer not null,"
        "`contactid` integer not null,"
        "`last_time` datetime not null,"
        "constraint pk_recent primary key (userid, contactid)"
        ");");if (!r)return r;

    r = query.exec("create table `status` ("
        "`key` varchar(64) not null primary key,"
        "`value` varchar(255) not null default ''"
        ");");if (!r) return r;

    r = query.exec("insert into `status` values"
        "('last_user_update_time', ''),"
        "('last_department_update_time', ''),"
        "('last_user_name', '');");if (!r) return r;

    db.close();
    QSqlDatabase::removeDatabase(db.connectionName());
    return true;
}
开发者ID:abomb4,项目名称:biye,代码行数:55,代码来源:clientdb.cpp

示例9: connectDatabase

static inline bool connectDatabase(QSqlDatabase DB, const int line)
{
    if (!DB.isOpen()) {
        if (!DB.open()) {
            Utils::Log::addError("GuardBase", tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                 .arg(DB.connectionName()).arg(DB.lastError().text()), __FILE__, line);
            return false;
        }
    }
    return true;
}
开发者ID:Dinesh-Ramakrishnan,项目名称:freemedforms,代码行数:11,代码来源:guardbase.cpp

示例10: qDBCaption

static QString qDBCaption(const QSqlDatabase &db)
{
//    QString nm = "DB:";
//    nm.append(db.connectionName());
//    nm.append(QLatin1Char(':'));
//    if (!db.userName().isEmpty())
//        nm.append(db.userName()).append(QLatin1Char('@'));
//    nm.append(db.databaseName());
    QString nm = db.connectionName();
    return nm;
}
开发者ID:Decryptortuning,项目名称:HEXplorer,代码行数:11,代码来源:connectionwidget.cpp

示例11: cache_columns

QStringList cache_columns(const QString& table, const QSqlDatabase& db)
{
	static QMap<QString, QMap<QString, QStringList> > master_cache;

	QMap<QString, QStringList> cache = master_cache.value(
		db.connectionName() );

	if( cache.contains(table) )
		return cache.value(table);

	QString sql;
	if(db.driverName() == "QMYSQL")
		sql = QString("DESCRIBE %1").arg(table);
	else // SQLite
		sql = QString("PRAGMA table_info(%1)").arg(table);

	QSqlQuery query(sql, db);
	if( !query.exec() )
		return QStringList();

	QStringList list;
	if(db.driverName() == "QMYSQL")
	{
		while( query.next() )
			list << query.record().value("Field").toString();
	}
	else // SQLite
	{
		while( query.next() )
			list << query.value(1).toString();
	}


	// Save the column info to the cache
	cache[table] = list;

	// Save the cache to the master cache (map of database connections)
	master_cache[db.connectionName()] = cache;

	return list;
}
开发者ID:erikku,项目名称:frosty,代码行数:41,代码来源:Utils.cpp

示例12: connectDatabase

static inline bool connectDatabase(QSqlDatabase &DB, const QString &file, const int line)
{
    if (!DB.isOpen()) {
        if (!DB.open()) {
            Utils::Log::addError("DrugBaseEssentials", tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                 .arg(DB.connectionName()).arg(DB.lastError().text()),
                                 file, line);
            return false;
        }
    }
    return true;
}
开发者ID:NyFanomezana,项目名称:freemedforms,代码行数:12,代码来源:drugbaseessentials.cpp

示例13: qmlsqldatabase_change_version

static QScriptValue qmlsqldatabase_change_version(QScriptContext *context, QScriptEngine *engine)
{
    if (context->argumentCount() < 2)
        return engine->undefinedValue();

    QSqlDatabase db = qscriptvalue_cast<QSqlDatabase>(context->thisObject());
    QString from_version = context->argument(0).toString();
    QString to_version = context->argument(1).toString();
    QScriptValue callback = context->argument(2);

    QScriptValue instance = engine->newObject();
    instance.setProperty(QLatin1String("executeSql"), engine->newFunction(qmlsqldatabase_executeSql,1));
    QScriptValue tx = engine->newVariant(instance,QVariant::fromValue(db));

    QString foundvers = context->thisObject().property(QLatin1String("version")).toString();
    if (from_version!=foundvers) {
        THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("Version mismatch: expected %1, found %2").arg(from_version).arg(foundvers));
        return engine->undefinedValue();
    }

    bool ok = true;
    if (callback.isFunction()) {
        ok = false;
        db.transaction();
        callback.call(QScriptValue(), QScriptValueList() << tx);
        if (engine->hasUncaughtException()) {
            db.rollback();
        } else {
            if (!db.commit()) {
                db.rollback();
                THROW_SQL(UNKNOWN_ERR,QDeclarativeEngine::tr("SQL transaction failed"));
            } else {
                ok = true;
            }
        }
    }

    if (ok) {
        context->thisObject().setProperty(QLatin1String("version"), to_version, QScriptValue::ReadOnly);
#ifndef QT_NO_SETTINGS
        QSettings ini(qmlsqldatabase_databaseFile(db.connectionName(),engine) + QLatin1String(".ini"), QSettings::IniFormat);
        ini.setValue(QLatin1String("Version"), to_version);
#endif
    }

    return engine->undefinedValue();
}
开发者ID:wpbest,项目名称:copperspice,代码行数:47,代码来源:qdeclarativesqldatabase.cpp

示例14: disConnectDatabase

bool MusicUserWindow::disConnectDatabase()
{
    QString connectionName;
    {
        QSqlDatabase data = QSqlDatabase::database("user-data");
        connectionName = data.connectionName();
        if( data.isValid() )
        {
            data.close();
        }
        else
        {
            return false;
        }
    }
    QSqlDatabase::removeDatabase( connectionName );
    return true;
}
开发者ID:azureidea,项目名称:TTKMusicplayer,代码行数:18,代码来源:musicuserwindow.cpp

示例15: ConnectToDB

void DBConnector::ConnectToDB()
{
    if (!CanConnectToDB())
        return;

    ProgSettings sett;


    if (QSqlDatabase::database().isValid() && QSqlDatabase::database().isOpen())
    {
        QSqlDatabase::database().close();
        QSqlDatabase::removeDatabase(QSqlDatabase::database().connectionName());
    }

    QSqlDatabase db = QSqlDatabase::addDatabase(sett.DBType());

    db.setDatabaseName(sett.DBName());

    if (sett.DBType() != "QSQLITE")
    {
        db.setHostName(sett.DBHostName());
        db.setUserName(sett.DBUserName());
        db.setPassword(sett.DBPassword());
        db.setPort(sett.DBPort());
    }

    if (db.open())
        qDebug() << QString("Open connection '%1'").arg(db.connectionName());

        if (db.lastError().isValid())
        {
            qDebug() << db.lastError().text();

            QMessageBox::critical(0,tr(""),tr("ќшибка соединени¤ с базой данных: %1").arg(db.lastError().text()),QMessageBox::Ok);

        }
}
开发者ID:wulff007,项目名称:FastStorage,代码行数:37,代码来源:DBConnector.cpp


注:本文中的QSqlDatabase::connectionName方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。