recDb::CreateReturn recDb::CreateDbFile( const wxString& fname, DatabaseType type ) { wxFileName dbfile( fname ); dbfile.SetExt( "tfpd" ); if ( dbfile.FileExists() ) { return CR_FileExists; } wxString dbfname = dbfile.GetFullPath(); wxSQLite3Database db; db.Open( dbfname ); if ( !db.IsOpen() ) { return CR_CannotOpen; } switch ( type ) { case DT_Full: db.ExecuteUpdate( createCommonDb ); db.ExecuteUpdate( createMediaDb ); db.ExecuteUpdate( createFullDb ); break; case DT_MediaOnly: db.ExecuteUpdate( createCommonDb ); db.ExecuteUpdate( createMediaDb ); break; default: db.Close(); return CR_UnknownType; } db.Close(); return CR_OK; }
bool OcDbManager::openDB() { db = QSqlDatabase::addDatabase("QSQLITE"); QString path(QDir::homePath()); path.append(BASE_PATH).append("/database.sqlite"); path = QDir::toNativeSeparators(path); QLOG_DEBUG() << "Database file path: " << path; // check if database file exists before database will be opened QFile dbfile(path); while(!dbfile.exists()) { QLOG_WARN() << "Database file does not exist. Waiting for it's creation by the engine..."; QEventLoop loop; QTimer::singleShot(1000, &loop, SLOT(quit())); loop.exec(); } db.setDatabaseName(path); db.setConnectOptions("QSQLITE_OPEN_READONLY"); bool dbOpen = db.open(); if (!dbOpen) { QLOG_FATAL() << "Can not open sqlite database"; } else { QLOG_INFO() << "Opened sqlite database"; } return dbOpen; }
bool DataManager::InitFile() { #ifdef WIN32 filename = QObject::tr("E:/SEGY_Data/dynp_dq.sgy"); dbname = QObject::tr("C:/Users/Tang/test.db"); #else filename = QObject::tr("/media/Backup/SEGY_Data/dynp_dq.sgy"); dbname = QObject::tr("/home/tommy/test.db"); #endif QFile dbfile(dbname); if(dbfile.size() < 10) { db_loadSEGYHead(filename); qDebug()<<"The database is not exits!Create a new one!"; } QByteArray bt = filename.toLatin1(); char* fname = bt.data(); if ((filesegy = fopen(fname,"rb")) == NULL ) { printf("open segy file error!"); return false; } return true; }
void searchhandler::OpenDB_indexChanged(const int& idx) { if (idx < 0) return; sqlquery::en_filereadstatus sqstatus; if (m_autocompBusy) { m_autocompBusy = false; m_autocompFutureWatcher.waitForFinished(); } sq->close_dbfile(); QFileInfo dbfile(m_comboBoxDB->itemText(idx)); sqstatus = sq->open_dbfile(qt2str(m_comboBoxDB->itemText(idx))); if (sqstatus != sqlquery::sqlfileOK) { QMessageBox msgBox((QWidget*)mw); msgBox.setText(sqlerrormsg(sqstatus)); msgBox.exec(); m_comboBoxDB->removeItem(idx); } else { QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); m_comboBoxSearch->clear(); m_comboBoxSearch->lineEdit()->clear(); m_searchMemoryList.clear(); m_iter = m_searchMemoryList.begin(); m_pushButtonSearchPrev->setEnabled(false); m_pushButtonSearchNext->setEnabled(false); emit sendDBtimestamp(dbfile.lastModified()); emit DBreset(); QApplication::restoreOverrideCursor(); } }
bool DBBrowserDB::open ( const QString & db) { bool ok=false; int err; if (isOpen()) close(); //try to verify the SQLite version 3 file header QFile dbfile(db); if ( dbfile.open( QIODevice::ReadOnly ) ) { char buffer[16+1]; dbfile.readLine(buffer, 16); QString contents = QString(buffer); dbfile.close(); if (!contents.startsWith("SQLite format 3")) { lastErrorMessage = QObject::tr("File is not a SQLite 3 database"); return false; } } else { lastErrorMessage = QObject::tr("File could not be read"); return false; } lastErrorMessage = QObject::tr("no error"); err = sqlite3_open_v2(db.toUtf8(), &_db, SQLITE_OPEN_READWRITE, NULL); if ( err ) { lastErrorMessage = QString::fromUtf8((const char*)sqlite3_errmsg(_db)); sqlite3_close(_db); _db = 0; return false; } if (_db){ // set preference defaults QSettings settings(QApplication::organizationName(), QApplication::organizationName()); settings.sync(); bool foreignkeys = settings.value( "/db/foreignkeys", false ).toBool(); setPragma("foreign_keys", foreignkeys ? "1" : "0"); if (SQLITE_OK==sqlite3_exec(_db,"PRAGMA empty_result_callbacks = ON;", NULL,NULL,NULL)){ if (SQLITE_OK==sqlite3_exec(_db,"PRAGMA show_datatypes = ON;", NULL,NULL,NULL)){ ok=true; } curDBFilename = db; } // Enable extension loading sqlite3_enable_load_extension(_db, 1); } return ok; }
bool recDb::AttachDb( const wxString& fname, const wxString& dbname ) { wxFileName dbfile( fname ); dbfile.SetExt( "tfpd" ); if ( !dbfile.FileExists() ) { return false; } wxString dbfname = dbfile.GetFullPath(); wxSQLite3StatementBuffer sql; sql.Format( "ATTACH DATABASE '%q' AS '%q';", UTF8_( dbfname ), UTF8_( dbname ) ); s_db->ExecuteUpdate( sql ); return true; }
void MainWindow::setXSliceNum(int sliceNum ) { QFile dbfile(filename+tr("_Xdb")); dbfile.open(QIODevice::ReadOnly); QDataStream DBin(&dbfile); sliceNum -= (Min_XLine-1); int fpCount,traceNum,LineNum; if( CubeType == tr("二维数据体")) { DBin>>fpCount>>fpCount>>traceNum>>LineNum; fpCount += 3840; wgl->setInLine(fpCount,traceNum,LineNum); }
CDatabaseManager::CDatabaseManager(QObject *parent) : QObject(parent) { // Save pointer of CMainWindow (as QObject) m_parent = parent; /* Define & open db * if the file doesn't exist, it will be created and * populated with the table definitions */ m_db = QSqlDatabase::addDatabase("QSQLITE"); QString dbname = QGuiApplication::applicationDirPath(); dbname.append("/cb.sqlite"); m_db.setDatabaseName(dbname); // Let's check if the file exists QFile dbfile(dbname); bool dbmiss = false; if (!dbfile.open(QFile::ReadOnly)) { // file isn't there; set a flag to create it dbmiss = true; } if (!m_db.open()) { QMessageBox* msg = new QMessageBox(); msg->setText("Fehler beim Öffnen der Datenbank!"); msg->setInformativeText("Datenbank lässt sich nicht öffnen!"); msg->setIcon(QMessageBox::Critical); QSqlError lError; lError = m_db.lastError(); msg->setDetailedText(lError.text()); msg->exec(); } if (dbmiss) { // opening the db created a plain file; now let's create the tables QString crc; crc = "CREATE TABLE \"Charts\" (\"ID\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , \"FID\" INTEGER NOT NULL , \"CName\" TEXT, \"CPath\" TEXT, \"Date\" DATETIME)"; QSqlQuery* crcharts = new QSqlQuery(crc, m_db); crcharts->exec(); QString crf; crf = "CREATE TABLE \"Fields\" (\"ID\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , \"ICAO\" TEXT, \"Name\" TEXT, \"Path\" TEXT)"; QSqlQuery* crfields = new QSqlQuery(crf, m_db); crfields->exec(); } }
bool DBBrowserDB::open ( const QString & db) { bool ok=false; int err; if (isOpen()) close(); //try to verify the SQLite version 3 file header QFile dbfile(db); if ( dbfile.open( QIODevice::ReadOnly ) ) { char buffer[16+1]; dbfile.readLine(buffer, 16); QString contents = QString(buffer); dbfile.close(); if (!contents.startsWith("SQLite format 3")) { lastErrorMessage = QString("File is not a SQLite 3 database"); return false; } } else { lastErrorMessage = QString("File could not be read"); return false; } lastErrorMessage = QString("no error"); err = sqlite3_open(GetEncodedQString(db), &_db); if ( err ) { lastErrorMessage = sqlite3_errmsg(_db); sqlite3_close(_db); _db = 0; return false; } if (_db) { if (SQLITE_OK==sqlite3_exec(_db,"PRAGMA empty_result_callbacks = ON;", NULL,NULL,NULL)) { if (SQLITE_OK==sqlite3_exec(_db,"PRAGMA show_datatypes = ON;", NULL,NULL,NULL)) { ok=true; setDirty(false); } curDBFilename = db; } } return ok; }
bool SqliteDB::open(const QString &db){ bool ok=false; int rc; if (isOpen()) close(); //try to verify the SQLite version 3 file header //yINFO((const char *)QString::fromLocal8Bit("验证 SQLite 数据库文件头: %1").arg(db).toLocal8Bit()); QFile dbfile(db); if ( dbfile.open( QIODevice::ReadOnly ) ) { char buffer[16+1]; dbfile.readLine(buffer, 16); QString contents = QString(buffer); dbfile.close(); if (!contents.startsWith("SQLite format 3")) { m_lastErrMsg = QString("File is not a SQLite 3 database"); return false; } } else { m_lastErrMsg = QString("File could not be read"); return false; } m_lastErrMsg = QString("no error"); rc = sqlite3_open( (const char *)db.toUtf8(), &m_db ); if( rc ) { m_lastErrMsg = sqlite3_errmsg(m_db); sqlite3_close(m_db); m_db = 0; return false; } if( m_db ){ rc = sqlite3_exec(m_db,"PRAGMA empty_result_callbacks = ON;",NULL,NULL,NULL); if (SQLITE_OK==rc){ rc = sqlite3_exec(m_db,"PRAGMA show_datatypes = ON;",NULL,NULL,NULL); if (SQLITE_OK==rc){ ok=true; } m_curDBFilename = db; } } return ok; }
void CompilationDatabase::Open() { // Close the old database if(m_db) { Close(); } // Create new one try { m_db = new wxSQLite3Database(); wxFileName dbfile(clCxxWorkspaceST::Get()->GetPrivateFolder(), "compilation.db"); m_db->Open(dbfile.GetFullPath()); CreateDatabase(); } catch(wxSQLite3Exception& e) { delete m_db; m_db = NULL; } }
// -------------------------------------------------------------------------- // // Function // Name: BackupStoreRefCountDatabase::Load(int32_t AccountID, // BackupStoreAccountDatabase& rAccountDatabase, // bool ReadOnly); // Purpose: Loads the info from disc, given the root // information. Can be marked as read only. // Created: 2003/08/28 // // -------------------------------------------------------------------------- std::auto_ptr<BackupStoreRefCountDatabase> BackupStoreRefCountDatabase::Load( const BackupStoreAccountDatabase::Entry& rAccount, bool ReadOnly) { // Generate the filename. Cannot open a temporary database, so it must // be a permanent one. std::string Filename = GetFilename(rAccount, false); int flags = ReadOnly ? O_RDONLY : O_RDWR; // Open the file for read/write std::auto_ptr<FileStream> dbfile(new FileStream(Filename, flags | O_BINARY)); // Read in a header refcount_StreamFormat hdr; if(!dbfile->ReadFullBuffer(&hdr, sizeof(hdr), 0 /* not interested in bytes read if this fails */)) { THROW_FILE_ERROR("Failed to read refcount database: " "short read", Filename, BackupStoreException, CouldNotLoadStoreInfo); } // Check it if(ntohl(hdr.mMagicValue) != REFCOUNT_MAGIC_VALUE || (int32_t)ntohl(hdr.mAccountID) != rAccount.GetID()) { THROW_FILE_ERROR("Failed to read refcount database: " "bad magic number", Filename, BackupStoreException, BadStoreInfoOnLoad); } // Make new object std::auto_ptr<BackupStoreRefCountDatabase> refcount( new BackupStoreRefCountDatabase(rAccount, ReadOnly, false, dbfile)); // return it to caller return refcount; }
bool recDb::CreateDb( const wxString& fname, unsigned flags ) { wxFileName dbfile( fname ); if( flags & CREATE_DB_STD_EXT ) { dbfile.SetExt( "tfpd" ); } if( flags & CREATE_DB_ENUM_FN ) { wxString fn = dbfile.GetName(); wxString nfn; for( int i = 2 ; dbfile.FileExists() == true ; i++ ) { nfn.Printf( "%s(%d)", fn.c_str(), i ); dbfile.SetName( nfn ); } } else { if( dbfile.FileExists() == true ) { recMessage( _("File already exists"), _("Create Database") ); // TODO: replace existing file return false; } } if( s_db->IsOpen() ) { recMessage( _("Database already open"), _("Create Database") ); return false; } wxString dbfname = dbfile.GetFullPath(); CreateReturn ret = CreateDbFile( dbfname, DT_Full ); if ( ret == CR_OK ) { s_db->Open( dbfname ); return true; } return false; }
int main(void) { acl::string dbfile("测试.db"); acl::db_sqlite db(dbfile); int max = 100; if (db.open() == false) { printf("open dbfile: %s error\r\n", dbfile.c_str()); getchar(); return 1; } printf("open dbfile %s ok\r\n", dbfile.c_str()); if (tbl_create(db) == false) { printf("create table error\r\n"); getchar(); return 1; } // 配置数据库引擎 db.set_conf("PRAGMA synchronous = off"); db.set_conf("PRAGMA encoding = \"UTF-8\""); acl::string buf; if ((db.get_conf("PRAGMA encoding", buf))) printf(">>PRAGMA encoding: %s\r\n", buf.c_str()); db.show_conf(); acl::meter_time(__FILE__, __LINE__, "---begin insert---"); for (int i = 0; i < max; i++) { bool ret = tbl_insert(db, i); if (ret) printf(">>insert ok: i=%d, affected: %d\r", i, db.affect_count()); else printf(">>insert error: i = %d\r\n", i); } printf("\r\n"); printf(">>insert total affect: %d\n", db.affect_total_count()); acl::meter_time(__FILE__, __LINE__, "---end insert---"); acl::meter_time(__FILE__, __LINE__, "---begin select---"); int n = 0; for (int i = 0; i < max; i++) { int ret = tbl_select(db, i); if (ret >= 0) { n += ret; printf(">>select ok: i=%d, ret=%d\r", i, ret); } else printf(">>select error: i = %d\r\n", i); } printf("\r\n"); printf(">>select total: %d\r\n", n); acl::meter_time(__FILE__, __LINE__, "---end select---"); acl::meter_time(__FILE__, __LINE__, "---begin delete---"); for (int i = 0; i < max; i++) { bool ret = tbl_delete(db, i); if (ret) printf(">>delete ok: %d, affected: %d\r", i, (int) db.affect_count()); else printf(">>delete error: i = %d\r\n", i); } printf("\r\n"); printf(">>delete total affected: %d\n", db.affect_total_count()); acl::meter_time(__FILE__, __LINE__, "---end delete---"); printf("Enter any key to exit.\r\n"); getchar(); return 0; }
bool RepoModel::dbexists(Database *db) { ifstream dbfile(db->dbFilename.c_str()); return dbfile; //Casts to true if file exists. }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QCoreApplication::setApplicationName("FeWo"); //checks whether dir for db exists and if so, if file in it exists bool db_exists=true; QString dataPath = QDesktopServices::storageLocation(QDesktopServices::DataLocation); DataBase::dbPath=dataPath+QDir::separator()+"FeWo.db"; QDir dataDir(dataPath); qDebug()<<dataPath; if(!dataDir.exists()) { if(!dataDir.mkpath(dataPath)){ QMessageBox::critical(0,QObject::tr("Error"),QObject::tr("Could not create path for database.")); app.quit(); } db_exists=false; }else{ QFile dbfile(DataBase::dbPath); if(!dbfile.exists()){ db_exists=false; } } //instantiate the new database DataBase * db=DataBase::getInstance(0); Error * errobj=new Error(); if(db->getError(errobj)){//if there was an error setting up the database, quit here QMessageBox::critical(0,QObject::tr("Database error"),errobj->getErrorMessage()); if(errobj->getSeverity()==FATAL){ app.exit(); } } MainWindow w; //create the main window //if no db exists yet, call the first run wizard if(! db_exists){ FirstRunWizard * wizard=new FirstRunWizard(&w,db); wizard->setModal(true); wizard->show(); } w.show(); //show the main window return app.exec(); }
bool DisassemblerDatabase::exists(const QString &filename) { QFile dbfile(DisassemblerDatabase::adjustFile(filename)); return dbfile.exists() && (dbfile.size() > 0); }
void Setup::enter() { QDir dir; dir.mkdir(QDir::homePath() + "/.booker"); QByteArray pwOffice = this->pwOffice->text().toLatin1(); QByteArray pwMaster = this->pwMaster->text().toLatin1(); QByteArray pwEncryption = this->pwEncryption->text().toLatin1(); Cryptor cryptor(pwOffice+pwOffice); QString dbHost = this->dbHost->text(); QString dbDatabase = this->dbDatabase->text(); QString dbUsername = this->dbUsername->text(); QString dbPassword = this->dbPassword->text(); QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL","test"); db.setHostName(dbHost); db.setDatabaseName(dbDatabase); db.setUserName(dbUsername); db.setPassword(dbPassword); db.open(); if(pwMasterCheck->isChecked()) { QSqlQuery query(db); QString sql = ""; sql += "INSERT INTO connectiontest (`passwordfor`,`password`) VALUES ('master',:master);"; query.prepare(sql); query.bindValue(":master",pwMaster); query.exec(); query.clear(); } else { QSqlQuery query(db); query.prepare("SELECT * FROM connectiontest WHERE passwordfor LIKE 'encryption' OR passwordfor LIKE 'master'"); query.exec(); while(query.next()) if(query.value(query.record().indexOf("passwordfor")).toByteArray() == "master") pwMaster = cryptor.decrypt(query.value(query.record().indexOf("password")).toByteArray()).data(); query.clear(); } QFile cryptPwFile(QDir::homePath() + "/.booker/cryptPassword"); if(!cryptPwFile.open(QIODevice::WriteOnly)) { QMessageBox::critical(this,"Failed file saving","ERROR! Can't save encryption password! Quitting..."); this->reject(); return; } QTextStream outPw(&cryptPwFile); outPw << cryptor.encrypt(pwEncryption).join("\n"); cryptPwFile.close(); QFile dbfile(QDir::homePath() + "/.booker/db"); if(!dbfile.open(QIODevice::WriteOnly)) { QMessageBox::critical(this,"Failed file saving","ERROR! Can't save database connection details! Quitting..."); this->reject(); return; } QTextStream outDb(&dbfile); outDb << cryptor.encrypt(QString("host=%1\ndb=%2\nuname=%3\npw=%4") .arg(dbHost) .arg(dbDatabase) .arg(dbUsername) .arg(dbPassword).toLatin1()).join("\n"); dbfile.close(); QFile cryptCredentials(QDir::homePath() + "/.booker/officePassword"); if(!cryptCredentials.open(QIODevice::WriteOnly)) { QMessageBox::critical(this,"Failed file saving","ERROR! Can't save office password! Quitting..."); this->reject(); return; } QTextStream outCred(&cryptCredentials); outCred << cryptor.encrypt(pwOffice).join("\n"); cryptCredentials.close(); this->accept(); }