示例#1
0
spatialite_database_unique_ptr QgsAuxiliaryStorage::open( const QString &filename )
{
  spatialite_database_unique_ptr database;

  if ( filename.isEmpty() )
  {
    if ( ( database = createDB( currentFileName() ) ) )
      mValid = true;
  }
  else if ( QFile::exists( filename ) )
  {
    if ( mCopy )
      QFile::copy( filename, mTmpFileName );

    if ( ( database = openDB( currentFileName() ) ) )
      mValid = true;
  }
  else
  {
    if ( ( database = createDB( currentFileName() ) ) )
      mValid = true;
  }

  return database;
}
示例#2
0
    bool EvalService::doRegEval( const CString& regulation, const AcDbIntArray& clauses )
    {
        // 规程评价没有实现或者尚未注册
        EvalMethod* pEvalMethod = m_pEvalMethodManager->getEvalMethodByName( regulation );
        if( pEvalMethod == 0 ) return false;

        EvalResultGenerator* pEvalResultGenerator = CreateEvalResultGenerator( pEvalMethod );

        // 创建数据库操作对象
        CDaoDatabase* pDB = createDB( m_evalResultDataBasePath, false ); // 每次评价都重建数据库(删除已存在的数据库)
        TableCreator* pTableCreator = new TableCreator( pDB );
        DataWriter* pDataWriter = new DataWriter( pDB );

        int len = clauses.length();
        for( int i = 0; i < len; i++ )
        {
            pEvalResultGenerator->startEval();
            pEvalResultGenerator->setClauseNum( clauses[i] );
            pEvalResultGenerator->initEvalData();
            pEvalResultGenerator->createTable( pTableCreator );
            pEvalResultGenerator->initEvalObject();
            pEvalResultGenerator->writeToTable( pDataWriter );
            pEvalResultGenerator->endEval();
        }

        delete pTableCreator;
        delete pDataWriter;

        pDB->Close();
        delete pDB;

        delete pEvalResultGenerator;

        return true;
    }
OCStackResult PDMInit(const char *path)
{
    int rc;
    const char *dbPath = NULL;
    if (SQLITE_OK !=  sqlite3_config(SQLITE_CONFIG_LOG, errLogCallback, NULL))
    {
        OC_LOG(INFO, TAG, "Unable to enable debug log of sqlite");
    }

    if (NULL == path || !*path)
    {
        dbPath = DB_FILE;
    }
    else
    {
        dbPath = path;
    }
    rc = sqlite3_open_v2(dbPath, &g_db, SQLITE_OPEN_READWRITE, NULL);
    if (SQLITE_OK != rc)
    {
        OC_LOG_V(INFO, TAG, "ERROR: Can't open database: %s", sqlite3_errmsg(g_db));
        return createDB(dbPath);
    }
    gInit = true;
    return OC_STACK_OK;
}
示例#4
0
文件: sql.cpp 项目: LazyT/obpm
sqlDialog::sqlDialog(QWidget *parent) : QDialog(parent)
{
	if(!(success = createDB()))
	{
		return;
	}

	setupUi(this);

	setWindowFlags(Qt::Tool);

	tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
	tableWidget->setMinimumHeight(5 * tableWidget->rowHeight(0) + tableWidget->horizontalHeader()->height() + 4);

	lineEdit_unixtime->setValidator(new QRegExpValidator(QRegExp("[0-9]*")));
	lineEdit_datetime->setValidator(new QRegExpValidator(QRegExp("(0[1-9]|[12][0-9]|3[01])\\.(0[1-9]|1[012])\\.(19[7-9][0-9]|20[0-9][0-9]) ([0-1][0-9]|2[0-3]):([0-5][0-9])")));

	comboBox->addItem(QString("select * from U%1 where SYS > %2").arg(1 + ((MainWindow*)parent)->user).arg(((MainWindow*)parent)->cfg.sys));
	comboBox->addItem(QString("select * from U%1 where DIA > %2").arg(1 + ((MainWindow*)parent)->user).arg(((MainWindow*)parent)->cfg.dia));
	comboBox->addItem(QString("select * from U%1 where BPM > %2").arg(1 + ((MainWindow*)parent)->user).arg(((MainWindow*)parent)->cfg.bpm));

	if(((MainWindow*)parent)->filter->isChecked())
	{
		comboBox->addItem(QString("select * from U%1 where UTS >= %2 and UTS <= %3").arg(1 + ((MainWindow*)parent)->user).arg(((MainWindow*)parent)->rangeStart->dateTime().toTime_t()).arg(((MainWindow*)parent)->rangeStop->dateTime().toTime_t()));
	}
	else
	{
		comboBox->addItem(QString("select * from U%1 where UTS > %2").arg(1 + ((MainWindow*)parent)->user).arg(QDateTime::currentDateTime().addDays(-7).toTime_t()));
	}

	connect(lineEdit_unixtime, SIGNAL(returnPressed()), this, SLOT(on_toolButton_ut2dt_clicked()));
	connect(lineEdit_datetime, SIGNAL(returnPressed()), this, SLOT(on_toolButton_dt2ut_clicked()));

	move(parent->mapToGlobal(parent->rect().center()) - rect().center());
}
示例#5
0
文件: clientdb.cpp 项目: abomb4/biye
void ClientDB::initdb() {
    QString dbpath = QStandardPaths::locate(QStandardPaths::AppDataLocation, DB_FILE_NAME);
    if (dbpath.isEmpty()) { // create
        QDir dir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
        if (!dir.exists()){
            if (!dir.mkpath(".")) {
                QMessageBox::critical(0, "Cannot create dir",
                       "Cannot create" + dir.path(), QMessageBox::Cancel);
                exit(2);
            }
        }
        dbpath = dir.absoluteFilePath(DB_FILE_NAME);
        if (!createDB(dbpath)) {
            QMessageBox::critical(0, "Cannot open database",
                   "Create SQLite database fail.", QMessageBox::Cancel);
            exit(1);
            return;
        }
    }
    QSqlDatabase db(QSqlDatabase::addDatabase("QSQLITE"));
    db.setDatabaseName(dbpath);
    if (!db.open()) {
        QMessageBox::critical(0, "Cannot open database",
               "Open SQLite database fail.", QMessageBox::Cancel);
        exit(1);
        return;
    }
}
void DatabaseManager::setUpDB()
{
    if (openDB()) {
        
        // check whether db is empty, if it is, create db
        if (m_db.tables().size() == 0) {
            
            createDB();
            
        } else {
            
            QSqlQuery query(m_db);
            query.exec("SELECT name, version FROM information;");
            if (query.isSelect()) {
                while (query.next()) {
                    QString name = query.value(0).toString();
                    double version = query.value(1).toDouble();
                    qDebug() << "App name: " << name;
                    qDebug() << "Database version : " << version;
                    
                    if (version == 1.0) {
                        qDebug() << "Needs first update. Add the Banner table to db";
                        if (createBannerTable()) {
                            updateInfoTable(2.0);
                        }
                    }
                }
            }
        }
    }
}
void process_choice(int choice){
	BufferManager *bu = BufferManager::getBufferManager();
	float hr = -1;
	switch(choice){
		case 1: 
			initCache(bu);
			break;
		case 2:
			createDB(bu);
			break;
		case 3:
			openDB(bu);
			break;
		case 4:
			readDB(bu);
			break;
		case 5:
			writeDB(bu);
			break;
		case 6:
			expandDB(bu);
			break;
		case 7:
			commitDB(bu);
			break;
		case 8:
			closeDB(bu);
			break;
		case 9: 
			commitCache(bu);
			break;
		case 10:
			releaseCache(bu);
			break;
		case 11:
			dropDB(bu);
			break;
		case 12:
			cout<<endl<<"Enter Cache id: ";
			cin>>choice;
			(*bu).printHex(choice, (*bu).getPageSize());
			break;
		case 13:
			(*bu).printCacheHeaders();
			break;
		case 14:
			hr = (*bu).getHitRate();
			if(hr!=-1)
				cout<<endl<<"\tHit rate is: "<<hr*100.0<<" %"<<endl;
			else {
				cout<<endl<<"\tHit rate cannot be calculated because cache";
				cout<<" is either not initialized, or no operation";
				cout<<"	has been performed on cache yet."<<endl;
			}
			break;			
		case 15:
		//	releaseCache(bu);
			break;
	}
}
bool DatabaseManager::openDB(QString filePath)
{
    if (!QSqlDatabase::contains())
    {
        // Find QSLite driver
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", DB_CONNECTION_NAME);

        if (filePath.isEmpty())
        {
            // Set database file name and path
            filePath = QDesktopServices::storageLocation(QDesktopServices::DataLocation);

            if (!QDir(filePath).exists())
            {
                // It doesn't exist, we have to create it.
                if (!QDir().mkpath(filePath))
                {
                    // Can't create directory, try to use application one (this may work in windows)
                    filePath = QCoreApplication::applicationFilePath();
                }
            }

            filePath.append(QDir::separator()).append("personal-qt.sqlite3");
        }

        filePath = QDir::toNativeSeparators(filePath);
        db.setDatabaseName(filePath);

        qDebug() << QString("Database file : %1").arg(filePath);

        QFile dbFile(db.databaseName());

        if (!dbFile.exists() || dbFile.size() <= 0)
        {
            qDebug() << "database does not exist or is corrputed. I'll try to create it.";

            if (!createDB())
            {
                qDebug() << "ERROR: Can't create a new database!";
                return false;
            }
        }
        else
        {
            qDebug() << "OK, database already exists.";
        }

        // Open databasee

        if (!db.open())
        {
            qDebug() << "ERROR: Can't open database!";
            qDebug() << db.lastError().text();
            return false;
        }
    }

    return true;
}
示例#9
0
Local::Local(QObject *parent) : QObject(parent) {
  db = QSqlDatabase::addDatabase("QSQLITE");
  db.setDatabaseName(qApp->applicationDirPath() + "/user.db");

  if (!db.open()) {
    qCritical() << tr("Could not open database connection");
    qDebug() << db.lastError().text();
  }

  createDB();
}
示例#10
0
 Private( const QString &identifier )
 {
   m_database = QSqlDatabase::addDatabase( "QSQLITE" );
   const QString filename = KStandardDirs::locateLocal( "data",
                                                        identifier + QLatin1String( "/flags.db" ) );
   m_database.setDatabaseName( filename );
   if ( !QFile::exists( filename ) ) {
     createDB();
   } else {
     m_database.open(); //TODO error
   }
 }
示例#11
0
Organizer::Organizer()
{
    if (!createDB())
    {
        perror("Open DB");
        exit(errno);
    }

    createTable("CREATE TABLE fic(size integer,path varchar(1000) UNIQUE, md5 varchar(16));");

    createTable("CREATE TABLE dir(empty bool,path varchar(1000) UNIQUE, modif datetime);");
}
示例#12
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("GSM管理人员登录");
    createDB();

//    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(toDataIn()));
    connect(ui->registing,SIGNAL(clicked()),this,SLOT(goRegist()));
    connect(ui->signin,SIGNAL(clicked()),this,SLOT(goSignin()));
}
示例#13
0
void SQLHelper::resetDB()
{
    CCLOG("RESET DB");
    
    //Drop Tables
    sqlite3_exec(_db, "DROP TABLE IF EXISTS Kategoria", NULL, 0, NULL);
    sqlite3_exec(_db, "DROP TABLE IF EXISTS Multzoa", NULL, 0, NULL);
    sqlite3_exec(_db, "DROP TABLE IF EXISTS Galdera", NULL, 0, NULL);
    
    
    //Create tables
    createDB();
}
示例#14
0
int main()
{
    int choice;
    init_mass_struct();
    for(;;)
    {
        printf("Hello, user. What do you want?\n\n");
        printf("1. Create new DB.\n");
        printf("2. Add record.\n");
        printf("3. Delete record.\n");
        printf("4. Sort DB.\n");
        printf("5. Save DB.\n");
        printf("6. Load DB.\n");
        printf("0. Exit.\n");
        scanf("%d", &choice);

        switch (choice)
        {
        case 1:
            createDB();
            break;
        case 2:
            addRecord();
            break;
        case 3:
            deleteRecord();
            break;
        case 4:
            sortDB();
            break;
        case 5:
            saveDB();
            break;
      case 6:
           loadDB();
            break;
        case 0:
            system("cls");
            printf("Bye-bye, user.");
            return 0;
            break;
        default:
            system("cls");
            printf("Error! Please, enter correct menu number, or 0 to exit.\n\n");
            break;
        }
    }
    return 0;
}
示例#15
0
void mainmenufirst2(int i)
{
    char key;
    //Detect key UP and DOWN until ENTER is pressed
    do
    {
        key = getch();  //Get the input
        switch(key)
        {
        case 72 :
            create(--cursor2); //Select upper menu
            break;
        case 80 :
            create(++cursor2); //Select lower menu
            break;
        }

    }
    while(key!=13);

    switch(cursor2)
    {
    case 1 :
        createDB();
        break;
    case 2 :
        createTable("","");
        cursor2 = 1;
        mainmenu(cursor2);
        break;
    case 3:
        deleteDB();
        cursor2=7;

        Sleep(400);
        create(cursor2);
        cursor2=1;
        break;
    case 4:
        deleteTable();
        create(cursor2);
        cursor2=1;
        break;
    case 5 :
        cursor2 = 1;
        mainmenu(cursor2);
        break;
    }
}
示例#16
0
void cDatabase::init()
{
	QDir		d;
	QString		szDB;
	QSettings	settings;

	m_DB	= QSqlDatabase::addDatabase("QSQLITE");
	szDB	= settings.value("application/data").toString()+QDir::separator()+settings.value("database/database").toString();
	m_DB.setDatabaseName(szDB);
	m_DB.open();

	QSqlQuery	version("select version from version", m_DB);
	if(!version.exec())
		m_iVersion	= createDB();
	else
	{
		version.first();
		m_iVersion = version.value(0).toInt();
	}
}
示例#17
0
sqlite3* createTestDB() {
  sqlite3* db = createDB();
  char* err = nullptr;
  std::vector<std::string> queries = {
      "CREATE TABLE test_table ("
      "username varchar(30) primary key, "
      "age int"
      ")",
      "INSERT INTO test_table VALUES (\"mike\", 23)",
      "INSERT INTO test_table VALUES (\"matt\", 24)"};
  for (auto q : queries) {
    sqlite3_exec(db, q.c_str(), nullptr, nullptr, &err);
    if (err != nullptr) {
      LOG(ERROR) << "Error creating test database: " << err;
      return nullptr;
    }
  }

  return db;
}
示例#18
0
void MainWindow::openDB(void)
{
    // Проверка наличия БД
    if (!checkDB("shvsm.db"))
        if (!createDB("shvsm.db"))
            return;

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("shvsm.db");

    setCursor(Qt::WaitCursor);
    if (!db.open())
    {
        setCursor(Qt::ArrowCursor);
        QMessageBox::critical(this, tr("Error"),tr("Error opening database!"), QMessageBox::Ok);
        return;
    }
    changeLangDB();
    setCursor(Qt::ArrowCursor);
}
示例#19
0
void QCatDataModuleClass::openDb(const QString fileName)
{
    delete im;
    delete cat;
    delete rpt;
    delete dbn;
	
	if (!dbConnName.isEmpty())
		QSqlDatabase::removeDatabase(dbConnName);

    dbConnName = fileName;
	//db = QSqlDatabase::addDatabase(DBTYPE, dbConnName);
	db = QSqlDatabase::addDatabase(DBTYPE);
	
	bool createNewDB = false;
	if (!QFileInfo(fileName).exists())
	{
        createDB(fileName, true);
		createNewDB = true;
	}
    db.setDatabaseName(fileName);
    if (!db.open())
    {
        errorCode = 1; // DB can not be opened
        errMsg = QObject::tr("DB %1 can not be opened.").arg(fileName);
        return;
    }
    dbn = new dbNodeClass(db);
    cat = new CatalogClass(db);
    rpt = new CatalogReports(db);
    im = new IconManager(db);
	if (createNewDB)
    {
		im->fillDefaultIcons();
        delete im;
        // Re-read global icons
        im = new IconManager(db);
    }
        

}
示例#20
0
MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow)
{
	ui->setupUi(this);
	ui->txt_pkt_data->setFont(QFont("Monospace"));
	ui->txt_unpackinfo->setFont(QFont("Monospace"));

	m_unpackStatus = UNPACK_START;
	m_pUnpackThread = NULL;

	initStatusBar();
	createDB();
	avInit();

	m_timer = new QTimer(this);
	//connect(m_timer,SIGNAL(timeout()),this,SLOT(slot_bind_tableview()));
	ui->tvw_unpack->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(ui->tvw_unpack, SIGNAL(customContextMenuRequested(const QPoint&)),
            this, SLOT(slot_show_unpack_menu()));//this是datatable所在窗口
}
/**
 * (re)connect to database
 */
int IpfixDbWriter::connectToDB()
{
    dbError = true;

    // close (in the case that it was already connected)
    mysql_close(conn);

    /** get the mysl init handle*/
    conn = mysql_init(0);
    if(conn == 0) {
	msg(MSG_FATAL,"IpfixDbWriter: Get MySQL connect handle failed. Error: %s",
		mysql_error(conn));
	return -1;
    } else {
	msg(MSG_DEBUG,"IpfixDbWriter got MySQL init handler");
    }

    /**Connect to Database*/
    if (!mysql_real_connect(conn,
		hostName, userName,
		password, 0, portNum,
		socketName, flags)) {
	msg(MSG_FATAL,"IpfixDbWriter: Connection to database failed. Error: %s",
		mysql_error(conn));
	return -1;
    } else {
	msg(MSG_DEBUG,"IpfixDbWriter succesfully connected to database");
    }
    /** create Database*/
    if(createDB() !=0)
	return -1;
    /**create table exporter*/
    if(createExporterTable() !=0)
	return -1;

    dbError = false;
    return 0;
}
示例#22
0
void SQLHelper::init()
{
    int result;
    //Check database if exist
    CCFileUtils *fileUtils = CCFileUtils::sharedFileUtils();
    _dbPath = fileUtils->getWritablePath();
    _dbPath.append("TrivialJokoa.db");
    std::ifstream f(_dbPath.c_str());
    
    if(!f)
    {
        //Database not exist
        result = sqlite3_open(_dbPath.c_str(),&_db);
        createDB();
    } else {
        CCLOG("DB EXIST");
        result = sqlite3_open(_dbPath.c_str(),&_db);
    }
    
    if (result != SQLITE_OK)
        CCLOG("OPENING WRONG, %d", result);

}
示例#23
0
文件: main.c 项目: jamorton/kerneldb
int main(int argc, char * argv[]){
        dataBase *db;
        createDB(&db, "myDB");
        int temp = 0;
        while(temp != -1){
                char line[50];
                char data[100];
		char *key = (char*)inderectMalloc((size_t)(sizeof(char)*50));
		char *stringData;
                size_t size;
                printf("0 to Add key and data, 1 to get data, 2 to remove data, 3 for size, 4 for save, 5 for load, -1 for quit\n");
                if(fgets(line, sizeof(line), stdin)) {
                        if(1 == sscanf(line, "%d", &temp)){
                                switch(temp){
                                        case 0:
                                                printf("Enter key\n");
                                                fgets(line, sizeof(line), stdin);
                                                sscanf(line, "%s", key);
						printf("Enter data\n");
                                                fgets(data, sizeof(data), stdin);
                                                put(db, key, data, sizeof(data));
                                                break;
                                        case 1:
                                                printf("Enter key\n");
                                                fgets(line, sizeof(line), stdin);
                                                sscanf(line, "%s", key);
						get(db, key, (void**)&stringData);
                                                printf("Data is: %s \n", stringData);
                                                break;
                                        case 2:
                                                printf("Enter key\n");
                                                fgets(line, sizeof(line), stdin);
                                                sscanf(line, "%s", key);
						delete(db, key);
                                                break;
                                        case 3:
                                                printf("Enter key\n");
						fgets(line, sizeof(line), stdin);
						sscanf(line, "%s", key);
                                                size = value_size(db, key);
                                                printf("Size is: %d\n", (int)size);
                                                break;
					case 4:
						printf("Enter path\n");
						fgets(line, sizeof(line), stdin);
						sscanf(line, "%s", key);
						if(-1 == saveHT(db, key))
							printf("Failed saved\n");
						break;
					case 5:
						printf("Enter path\n");
						fgets(line, sizeof(line), stdin);
						sscanf(line, "%s", key);
						if(-1 == loadHT(db, key))
							printf("Failed load\n");
						break;
				}
			}
		}
	}
}
/**
 * Creates a new ipfixDbWriter. Do not forget to call @c startipfixDbWriter() to begin writing to Database
 * @return handle to use when calling @c destroyipfixDbWriter()
 */
IpfixDbWriter::IpfixDbWriter(const char* host, const char* db,
                             const char* user, const char* pw,
                             unsigned int port, uint16_t observationDomainId,
                             int maxStatements)
{
    conn = mysql_init(0); /** get the mysl init handle*/
    if(conn == 0) {
        msg(MSG_FATAL,"IpfixDbWriter: Get MySQL connect handle failed. Error: %s",
            mysql_error(conn));
        goto out;
    }
    else {
        msg(MSG_DEBUG,"IpfixDbWriter got MySQL init handler");
    }
    /**Initialize structure members IpfixDbWriter*/
    hostName = host;
    dbName = db;
    userName = user;
    password = pw;
    portNum = port;
    socketName = 0;
    flags = 0;
    srcId.observationDomainId = observationDomainId;

    /**Initialize table cache*/
    cache.countBuffTable = 0;
    cache.countExpTable = 0;
    int i;
    for(i = 0; i < MAX_TABLE; i++) {
        cache.tableBuffer[i].startTableTime = 0;
        cache.tableBuffer[i].endTableTime = 0;
        cache.tableBuffer[i].TableName[0] = '\0';
    }
    for(i = 0; i < MAX_EXP_TABLE; i++) {
        cache.exporterBuffer[i].Id = 0;
        cache.exporterBuffer[i].observationDomainId = 0;
        cache.exporterBuffer[i].expIp = 0;
    }

    /**count columns*/
    numberOfColumns = 0;
    for(i=0; identify[i].cname!=0; i++)
        numberOfColumns++;

    /**Initialize structure members Statement*/
    statements.statemBuffer = (char**)malloc(sizeof(char**)*maxStatements);
    statements.maxStatements = maxStatements;
    statements.statemReceived = 0;
    for( i = 0; i != statements.maxStatements; i++) {
        statements.statemBuffer[i] = (char*) malloc((STARTLEN+(numberOfColumns * INS_WIDTH)) * sizeof(char));
        statements.statemBuffer[i][0] = '\0';
    }
    statements.lockTables = (char**)malloc(sizeof(char**)*maxStatements);
    statements.maxLocks = maxStatements; // worst case: every entry in another table
    for( i = 0; i != statements.maxLocks; i++) {
        statements.lockTables[i] = (char*) malloc(TABLE_WIDTH * sizeof(char));
        statements.lockTables[i][0] = '\0';
    }

    /**Connect to Database*/
    if (!mysql_real_connect(conn, hostName, userName,
                            password, 0, portNum, socketName, flags)) {
        msg(MSG_FATAL,"IpfixDbWriter: Connection to database failed. Error: %s",
            mysql_error(conn));
        goto out;
    }
    else {
        msg(MSG_DEBUG,"IpfixDbWriter succesfully connected to database");
    }
    /** create Database*/
    if (createDB()!=0)
        goto out;
    /**create table exporter*/
    if (createExporterTable()!=0)
        goto out;

    return;

out:
    THROWEXCEPTION("IpfixDbWriter creation failed");
    return;
}
/**
 * Creates a new ipfixDbWriter. Do not forget to call @c startipfixDbWriter() to begin writing to Database
 * @return handle to use when calling @c destroyipfixDbWriter()
 */
IpfixDbWriter* createIpfixDbWriter(const char* hostName, const char* dbName,
                                   const char* userName, const char* password,
                                   unsigned int port, uint16_t observationDomainId,
                                   int maxStatements)
{	
	IpfixDbWriter* ipfixDbWriter = (IpfixDbWriter*)malloc(sizeof(IpfixDbWriter));
	Table* tabl = (Table*)malloc(sizeof(Table));
	Statement* statemen = (Statement*)malloc(sizeof(Statement));
	statemen->statemBuffer = (char**)malloc(sizeof(char**)*maxStatements);
	statemen->maxStatements = maxStatements;
	
	ipfixDbWriter->conn = mysql_init(0);  /** get the mysl init handle*/
	if(ipfixDbWriter->conn == 0) {
		msg(MSG_FATAL,"IpfixDbWriter: Get MySQL connect handle failed. Error: %s",
		    mysql_error(ipfixDbWriter->conn));
		goto out;
	} else {
		msg(MSG_DEBUG,"IpfixDbWriter got MySQL init handler");
	}
	/**Initialize structure members IpfixDbWriter*/
	ipfixDbWriter->hostName = hostName;
	ipfixDbWriter->dbName = dbName;
	ipfixDbWriter->userName = userName;    		
	ipfixDbWriter->password = password;		
	ipfixDbWriter->portNum = port;
	ipfixDbWriter->socketName = 0;
	ipfixDbWriter->flags = 0;
	ipfixDbWriter->srcId.observationDomainId = observationDomainId;
	/**Initialize structure members Table*/	  
	ipfixDbWriter->table = tabl ;
	tabl->countBuffTable = 0;
	tabl->countExpTable = 0;
	
	/**Init tableBuffer start- , endTime and name of the tables*/
	int i ;
	for(i = 0; i < MAX_TABLE; i++) {
		tabl->tableBuffer[i].startTableTime = 0;
		tabl->tableBuffer[i].endTableTime  = 0;
		strcpy(tabl->tableBuffer[i].TableName, "NULL");
	}
	/**count columns*/
	tabl->countCol = 0;
	for(i=0; columnsNames[i] !=0; i++)
		tabl->countCol++;
	
	/**Initialize structure members Statement*/	   	 	
	tabl->statement= statemen;
	statemen->statemReceived = 0;
	for( i = 0; i != statemen->maxStatements; i++) {
		statemen->statemBuffer[i] = NULL;
	}
	
	/**Init struct expTable*/
	for(i = 0; i < MAX_EXP_TABLE; i++) {
		tabl->exporterBuffer[i].Id = 0;
		tabl->exporterBuffer[i].observationDomainId = 0;
		tabl->exporterBuffer[i].expIp = 0;
	}				
	
	/**Connect to Database*/
	if (!mysql_real_connect(ipfixDbWriter->conn,
				ipfixDbWriter->hostName, ipfixDbWriter->userName,
				ipfixDbWriter->password, 0, ipfixDbWriter->portNum,
				ipfixDbWriter->socketName, ipfixDbWriter->flags)) {
		msg(MSG_FATAL,"IpfixDbWriter: Connection to database failed. Error: %s",
		    mysql_error(ipfixDbWriter->conn));
		goto out;
	} else {
		msg(MSG_DEBUG,"IpfixDbWriter succesfully connected to database");
	}
	/** create Database*/
	if(createDB(ipfixDbWriter) !=0)
		goto out;
	/**create table exporter*/
	if(createExporterTable(ipfixDbWriter) !=0)
		goto out;
	
	return ipfixDbWriter;
	
out: 
	destroyIpfixDbWriter(ipfixDbWriter);
		
	return NULL;	
}
ofxTwitterStreamSQLiteListener::ofxTwitterStreamSQLiteListener(
	std::string sDBName
):sqlite(sDBName)
{
	createDB();
}
示例#27
0
void DatabaseConfigDialog::doAccept() {
    qDebug("...doAccept....");

    // validar que los campos no esten vacios
    if (!validateFields())
        return;

    // verificar si se desea crear la base de datos local de pruebas
    if (ui->checkBoxDBLocal->checkState () == Qt::Checked ){

        if (createDB()){
            MainWindow::mymainwindow->setEnableCompletingButtons(true);
            SafetYAWL::streamlog <<  SafetLog::Debug <<
                    tr("Creada la base de datos local para propositos de prueba.");

        }
        else{
            QMessageBox::warning(this, "SAFET - InFLow", trUtf8("No se pudo crear la base de datos local. Verifique nombre de usuario y contraseña."));
            SafetYAWL::streamlog << SafetLog::Warning << tr("No se pudo crear la base de datos local.");
            return;
        }

    }

    bool connection = false;
    //connection = testDataSources();
    connection = testNewDataSources();
    if (!connection){
        qDebug("... La conexion fallo");
        //QMessageBox::warning(this, "SAFET - InFLow", trUtf8("La conexión falló"));

        return;
    }
    else // en este punto los datos colocados son correctos y se debe cifrar
    {
        qDebug("Se va a cifrar");

        QStringList results = configValues();

        QStringList keys;
        keys << "database.sourcename.1"
                << "database.driver.1"
                << "database.host.1"
                << "database.db.1"
                << "database.port.1"
                << "database.user.1"
                << "database.password.1";

        QString fileconf = SafetYAWL::pathconf+ "/" + "auth.conf";
        QString replacetext;
        if (QFile::exists(fileconf)) {
            QString firstkeyfield, secondkeyfield, searchtext;
            int i=0;
            foreach(QString s, results) {
                firstkeyfield = keys.at(i).toLocal8Bit().constData();
                //qDebug("...firstkeyfield: %s", qPrintable(firstkeyfield));
                secondkeyfield = s;
                //qDebug("...secondkeyfield: %s",qPrintable(secondkeyfield));
/*
                searchtext = tr("\\s*(%1)\\s*\\=\\s*([áéíóúñÑa-zA-Z0-9\\$\\#/\\-\\._/:!\\?\\^\\$,;\\x3c\\x3e\\x2f]"
                        "[áéíóúñÑa-zA-Z0-9\\$\\#/\\-\\._/:!\\?\\^\\$\\s,;\\x3c\\x3e\\x2f]*"
                        "[áéíóúñÑa-zA-Z0-9\\$\\#/\\-\\._/:!\\?\\^\\$,;\\x3c\\x3e\\x2f])").arg(firstkeyfield);
*/
                searchtext = tr("\\s*(%1)\\s*\\=((\\s*([áéíóúñÑa-zA-Z0-9\\$\\#/\\-\\._/:!\\?\\^\\$,;\\x3c\\x3e\\x2f]"
                                "[áéíóúñÑa-zA-Z0-9\\$\\#/\\-\\._/:!\\?\\^\\$\\s,;\\x3c\\x3e\\x2f]*"
                                "[áéíóúñÑa-zA-Z0-9\\$\\#/\\-\\._/:!\\?\\^\\$,;\\x3c\\x3e\\x2f]))||(\\s*))").arg(firstkeyfield);

                replacetext  = tr("%1 = %2").arg(firstkeyfield).arg(secondkeyfield);

                //qDebug("...DatabaseConfigDialog::doAccept()...replacetext:|%s|",qPrintable(replacetext));
                if (SafetYAWL::replaceTextInFile(fileconf,
                                     searchtext,
                                     replacetext))
                i++;
            }

            MainWindow::mymainwindow->doCipherFile(true);

            SafetYAWL::readAuthConfFile();

            //limpiar el archivo auth.conf
            cleanConfigurationFile();

            //QMessageBox::information(this, "SAFET - InFlow", "Configuración de fuente de datos almacenada exitosamente.");

        }
        else
        {
示例#28
0
文件: parser.c 项目: edurox/uffsdb
int interface() {
    pthread_t pth;

    pthread_create(&pth, NULL, (void*)clearGlobalStructs, NULL);
    pthread_join(pth, NULL);

    connect("ibetres"); // conecta automaticamente no banco padrão

    while(1){
        if (!connected.conn_active) {
            printf(">");
        } else {
            printf("%s=# ", connected.db_name);
        }

        pthread_create(&pth, NULL, (void*)yyparse, &GLOBAL_PARSER);
        pthread_join(pth, NULL);

        if (GLOBAL_PARSER.noerror) {
            if (GLOBAL_PARSER.mode != 0) {
                if (!connected.conn_active) {
                    notConnected();
                } else {
                    switch(GLOBAL_PARSER.mode) {
                        case OP_INSERT:
                            if (GLOBAL_DATA.N > 0) {
                                insert(&GLOBAL_DATA);
                            }
                            else
                                printf("WARNING: Nothing to be inserted. Command ignored.\n");
                            break;
                        case OP_SELECT_ALL:

			

			    if (GLOBAL_DATA.imprimeTudo == 1 && GLOBAL_WHERE.where == 1) {

				
				 whereSemProj(&GLOBAL_DATA, &GLOBAL_WHERE, GLOBAL_DATA.objName);

				 GLOBAL_WHERE.where = 0;
				 GLOBAL_DATA.imprimeTudo = 0;
				 

			    }
			    else if (GLOBAL_DATA.imprimeTudo == 1 && GLOBAL_WHERE.where == 0) {

				
				 imprimeAll(GLOBAL_DATA.objName);
				 GLOBAL_DATA.imprimeTudo = 0;
				 				
			
			    }
			    else if (GLOBAL_DATA.imprimeTudo == 0 && GLOBAL_WHERE.where == 1) {

				
				 whereComProj(&GLOBAL_DATA, &GLOBAL_WHERE, GLOBAL_DATA.objName, GLOBAL_PARSER.col_count);
				 GLOBAL_DATA.imprimeTudo = 0;
				 GLOBAL_WHERE.where = 0;
				 				
			
			    }
			    else {

				 
			    	 selecionar(&GLOBAL_DATA, GLOBAL_PARSER.col_count);
				

			    }
                           
                            break;
                        case OP_CREATE_TABLE:
                            createTable(&GLOBAL_DATA);
                            break;
                        case OP_CREATE_DATABASE:
                            createDB(GLOBAL_DATA.objName);
                            break;
                        case OP_DROP_TABLE:
                            excluirTabela(GLOBAL_DATA.objName);
                            break;
                        case OP_DROP_DATABASE:
                            dropDatabase(GLOBAL_DATA.objName);
		 	    break;
                        default: break;
                    }

                }
            }
        } else {
            GLOBAL_PARSER.consoleFlag = 1;
            switch(GLOBAL_PARSER.mode) {
                case OP_CREATE_DATABASE:
                case OP_DROP_DATABASE:
                case OP_CREATE_TABLE:
                case OP_DROP_TABLE:
                case OP_SELECT_ALL:
                case OP_INSERT:
                    if (GLOBAL_PARSER.step == 1) {
                        GLOBAL_PARSER.consoleFlag = 0;
                        printf("Expected object name.\n");
                    }
                break;

                default: break;
            }

            if (GLOBAL_PARSER.mode == OP_CREATE_TABLE) {
                if (GLOBAL_PARSER.step == 2) {
                    printf("Column not specified correctly.\n");
                    GLOBAL_PARSER.consoleFlag = 0;
                }
            } else if (GLOBAL_PARSER.mode == OP_INSERT) {
                if (GLOBAL_PARSER.step == 2) {
                    printf("Expected token \"VALUES\" after object name.\n");
                    GLOBAL_PARSER.consoleFlag = 0;
                }
            }

            printf("ERROR: syntax error.\n");
            GLOBAL_PARSER.noerror = 1;
        }

        if (GLOBAL_PARSER.mode != 0) {
            pthread_create(&pth, NULL, (void*)clearGlobalStructs, NULL);
            pthread_join(pth, NULL);
        }
    }
    return 0;
}
示例#29
0
QueryData query(const std::string& q, int& error_return) {
  sqlite3* db = createDB();
  QueryData results = query(q, error_return, db);
  sqlite3_close(db);
  return results;
}
示例#30
0
int interface() {
    pthread_t pth;

    pthread_create(&pth, NULL, (void*)clearGlobalStructs, NULL);
    pthread_join(pth, NULL);

    connect("uffsdb"); // conecta automaticamente no banco padrão

    while(1){
        if (!connected.conn_active) {
            printf(">");
        } else {
            printf("%s=# ", connected.db_name);
        }

        pthread_create(&pth, NULL, (void*)yyparse, &GLOBAL_PARSER);
        pthread_join(pth, NULL);

        if (GLOBAL_PARSER.noerror) {
            if (GLOBAL_PARSER.mode != 0) {
                if (!connected.conn_active) {
                    notConnected();
                } else {
                    switch(GLOBAL_PARSER.mode) {
                        case OP_INSERT:
                            if (GLOBAL_DATA.N > 0) {
                                insert(&GLOBAL_DATA);
                            }
                            else
                                printf("WARNING: Nothing to be inserted. Command ignored.\n");
                            break;
                        case OP_SELECT_ALL:
                            pulpfic(select_attributes, GLOBAL_DATA.objName, token_list);
                            /*w_token *jujuba;
                            for(jujuba=token_list;jujuba;jujuba=jujuba->next){
                                printf("jujuba = %s\n",(char*)jujuba->valor);
                            }*/
                            break;
                        case OP_CREATE_TABLE:
                            createTable(&GLOBAL_DATA);
                            break;
                        case OP_CREATE_DATABASE:
                            createDB(GLOBAL_DATA.objName);
                            break;
                        case OP_DROP_TABLE:
                            excluirTabela(GLOBAL_DATA.objName);
                            break;
                        case OP_DROP_DATABASE:
                            dropDatabase(GLOBAL_DATA.objName);
                            break;
                        default: break;
                    }

                }
            }
        } else {
            GLOBAL_PARSER.consoleFlag = 1;
            switch(GLOBAL_PARSER.mode) {
                case OP_CREATE_DATABASE:
                case OP_DROP_DATABASE:
                case OP_CREATE_TABLE:
                case OP_DROP_TABLE:
                case OP_SELECT_ALL:
                case OP_INSERT:
                    if (GLOBAL_PARSER.step == 1) {
                        GLOBAL_PARSER.consoleFlag = 0;
                        printf("Expected object name.\n");
                    }
                break;

                default: break;
            }

            if (GLOBAL_PARSER.mode == OP_CREATE_TABLE) {
                if (GLOBAL_PARSER.step == 2) {
                    printf("Column not specified correctly.\n");
                    GLOBAL_PARSER.consoleFlag = 0;
                }
            } else if (GLOBAL_PARSER.mode == OP_INSERT) {
                if (GLOBAL_PARSER.step == 2) {
                    printf("Expected token \"VALUES\" after object name.\n");
                    GLOBAL_PARSER.consoleFlag = 0;
                }
            }

            printf("ERROR: syntax error.\n");
            GLOBAL_PARSER.noerror = 1;
        }

        if (GLOBAL_PARSER.mode != 0) {
            pthread_create(&pth, NULL, (void*)clearGlobalStructs, NULL);
            pthread_join(pth, NULL);
        }
    }
    return 0;
}