Beispiel #1
0
int Server::init(int port)
{
    int ret;

    ret = connectDB();
    if (ret < 0)
        return ret;

    serverTCP = socket(AF_INET, SOCK_STREAM, 0);
    if (serverTCP < -1) {
        perror("Socket Error");
        return -1;
    }
    serverTCPAddress = new sockaddr_in;
    serverTCPAddress->sin_family = AF_INET;
    serverTCPAddress->sin_addr.s_addr = htonl(INADDR_ANY);
    serverTCPAddress->sin_port = htons(port);

    ret = bind(serverTCP, (sockaddr* )serverTCPAddress, sizeof(*serverTCPAddress));
    if (ret < 0) {
        perror("Bind Error");
        return -2;
    }
    listen(serverTCP, 10);
    std::cout << "Inited!" << std::endl;
    return 0;
}
int main(void)
{
	int field;
	int i;
	char recv[100];
	if (connectDB() < 0) {
		return -1;
	}
	//mysql_set_character_set(conn, "utf8");
	
	if (runQuery("select * from fish")) {
		return -2;
	}

	field = mysql_num_fields(res);

	while ((row = mysql_fetch_row(res))) {
		for (i = 0; i < field; i++) {
			printf("%s ", row[i] ? row[i] : "NULL");
		}
		printf("\n");
	}

	printf("MySQL Client Version: %s\n", mysql_get_client_info());

	closeDB();

	return 0;
}
bool DataLayer::retrieveEmployees(vector<Employee*> *emp)
{
    if(connectDB())
    {
        QSqlQuery qry;
        Employee *e;
        qry.prepare("select * from employee");
        if(qry.exec())
        {
            while(qry.next())
            {
                //cout<<qry.value("CNIC").toString().toStdString()<<endl;

                    e=new Employee;

                    QString cnic=qry.value("cnic").toString();
                    QString name=qry.value("name").toString();
                    QString type=qry.value("_Type").toString();
                    int phone_no=qry.value("phone").toInt();
                    float salary=qry.value("salary").toFloat();
                    QString password=qry.value("password").toString();
                    float rate=qry.value("hourlyrate").toInt();
                    float work=qry.value("hoursworked").toFloat();

                    //cout<<name.toStdString()<<endl;
                        e->setAttributes(name,cnic,type,phone_no,salary, password,rate,work);
                        emp->push_back(e);
                    }
                }

            return true;
        }

    return false;
}
bool DataLayer::retrieveWarning(vector<Warning *> *warn)
{
    if(connectDB())
    {
        QSqlQuery qry;
        Warning * w;
        qry.prepare("select * from warning");
        if(qry.exec())
        {
            while(qry.next())
            {
                //cout<<qry.value("CNIC").toString().toStdString()<<endl;

                    w=new Warning;

                    QString cnic=qry.value("cnic").toString();

                    int count=qry.value("cnt").toInt();

                    //cout<<name.toStdString()<<endl;
                        w->set(cnic,count);
                        warn->push_back(w);
                    }
                }

            return true;
        }

    return false;
}
void DataLayer::InitMenu(Menu  * mm) {
if (connectDB()) {
    qDebug()<<"connected";
    QSqlQuery q;
    q.prepare ("select * from [food item] ");
    q.exec();
  //  int count = q.numRowsAffected();

    while(q.next()){
        QString name = q.value(0).toString();
        float price = q.value(1).toFloat();
        QString details = q.value(2).toString();
        QString unit = q.value(3).toString();
        QString type = q.value(4).toString();
        mm->Add(name, price, details, unit, type);
    }
            closeDB();
            //return true;


}
else {qDebug()<<"not connected";
}

}
MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow),
	help_process(0)
{
	ui->setupUi(this);

	db = QSqlDatabase::addDatabase("QMYSQL");

	QCoreApplication::setOrganizationName(DEFAULTS::Organization);
	QCoreApplication::setOrganizationDomain(DEFAULTS::Domain);
	QCoreApplication::setApplicationName(DEFAULTS::Application);
	QCoreApplication::setApplicationVersion(QString().setNum(DEFAULTS::AppVersion));

	if (importSettings()) {
		connectDB();
	}

	PatientFrame *patientFrame = new PatientFrame;
	PrescriptionFrame *prescriptionFrame = new PrescriptionFrame;
	FormularyFrame *formularyFrame = new FormularyFrame;
	InventoryFrame *inventoryFrame = new InventoryFrame;
	PrescriberFrame *prescriberFrame = new PrescriberFrame;
	PharmacistFrame *pharmacistFrame = new PharmacistFrame;

	ui->mainTabs->addTab(patientFrame, QString("Patients"));
	ui->mainTabs->addTab(prescriptionFrame, QString("Prescription log"));
	ui->mainTabs->addTab(formularyFrame, QString("Formulary"));
	ui->mainTabs->addTab(prescriberFrame, QString("Prescribers"));
	ui->mainTabs->addTab(pharmacistFrame, QString("Pharmacists"));
	ui->mainTabs->addTab(inventoryFrame, QString("Inventory"));

	connect(ui->optionsAction, SIGNAL(triggered()), this, SLOT(initiateOptions()));
	connect(ui->helpAction, SIGNAL(triggered()), this, SLOT(initiateHelp()));
}
/** 全てのユーザー取得
 *
 * @param users 取得した値を格納するための配列
 */
void userFindAll(user_t *users){

  // 変数の初期化
  int i;
  MYSQL_RES *resp = NULL;
  MYSQL_ROW row;

  // MySQLと接続
  MYSQL *conn = connectDB();

  // クエリ実行
  excuteSQL(conn, "select * from users");

  // レスポンスを取り出す
  resp = mysql_use_result(conn);

  // 取り出したレスポンスを構造体Userにマッピング
  for (i=0; (row = mysql_fetch_row(resp)) != NULL; i++) {
    users[i].id = atoi(row[0]);
    strncpy(users[i].name, row[1], sizeof(users[i].name));
    printf( "%d : %s\n" , users[i].id , users[i].name );
  }
  
  // 後片づけ
  mysql_free_result(resp);
  mysql_close(conn);
}
Beispiel #8
0
int main()
{
	char* sqls[] = {"desc userinfo", "drop table if exists ui123"};
	connectDB("transwarp-hs1", "", ""); 
	sql_execute(sqls, 2);
	disconnect();
	return 0;	
}
Beispiel #9
0
void MainWindow::changeDB(const QString & dbf){
    closeDB();
    this->dbf = dbf;
    connectDB();
    initWidget();
    loadMoneyTree();
    loadEventToLog();
}
QSqlQuery DataLayer::retrvdeal()
{
    if(connectDB())
    {
    QSqlQuery query("select*from deals");

    return query;
    }
}
bool DataLayer::addEmployee(QString cnic){
    if(connectDB()){

       closeDB();
       return true;
    }
    else{
        return false;
    }
}
bool ClinicCharge::LoadDate()
{
    if(connectDB())
    {
        UpdateChargeTable();
        return true;
    }
    else
        return false;

}
Beispiel #13
0
void MainWindow::on_actionConnect_Database_2_triggered(){
    QString path = QFileDialog::getOpenFileName(this,"Connect database",".","Database (*.db);;All file (*.*)");
    if(path != ""){
        this->dbf = path;
        closeDB();
        connectDB();
        initWidget();
        loadMoneyTree();
        loadEventToLog();
    }
}
Beispiel #14
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->dbf = "D:/data.db";
    log = new Log(this);
    connectDB();
    initWidget();
    loadMoneyTree();
    loadEventToLog();
}
void DataLayer::removeemp(QString cnic) {
    if (connectDB()) {
        qDebug()<<"connected";
        QSqlQuery q;
        q.prepare ("Delete from employee where cnic='"+cnic+"' ");
        q.exec();
        q.prepare ("Delete from warning where cnic='"+cnic+"' ");
        q.exec();
    }
    else {qDebug()<<"not connected";
}
}
Beispiel #16
0
void DataLoad::on_loadButton_clicked()
{
    qDebug() << QFileInfo(fileLineEdit->text()).fileName();
    connectDB(fileLineEdit->text());
    queryDB();
    writeFile(profileComboBox->currentText(), profileComboBox->currentText());
    progressBar->setValue(30);
    writeFile(componentComboBox->currentText(), componentComboBox->currentText());
    progressBar->setValue(60);
    writeFile(stepComboBox->currentText(), stepComboBox->currentText());
    progressBar->setValue(100);
}
QSqlQuery DataLayer::retrvfooditemfordeal(QString nm)
{
    if(connectDB())
    {
        QSqlQuery query;

        query.prepare("select* from [dealItems] where name='"+nm+"' ");
        //query.bindValue(":nm",nm);
      query.exec();

    return query;
    }
}
void DataLayer::removedeal(QString name) {
    if (connectDB()) {
        qDebug()<<"connected";
        QSqlQuery q;
        q.prepare ("Delete from [deals] where name='"+name+"' ");
        q.exec();
        QSqlQuery qq;
        qq.prepare ("Delete from [dealitems] where name='"+name+"' ");

        qq.exec();
    }
    else {qDebug()<<"not connected";
}
}
void DataLayer::removefood(QString name) {
    if (connectDB()) {
        qDebug()<<"connected";
        QSqlQuery q;
        q.prepare ("Delete from [Food Item] where name='"+name+"' ");
        q.exec();
        q.prepare("Delete from Menu where Name='"+name+"'");
        q.exec();
        q.prepare ("Delete from [dealitems] where fooditems='"+name+"' ");
        q.exec();
    }
    else {qDebug()<<"not connected";
}
}
Beispiel #20
0
void connect(char *nome) {
    int r;
    r = connectDB(nome);
	if (r == SUCCESS) {
        connected.db_name = malloc(sizeof(char)*((strlen(nome)+1)));

        strcpylower(connected.db_name, nome);

        connected.conn_active = 1;
        printf("You are now connected to database \"%s\" as user \"Ibetres\".\n", nome);
    } else {
    	printf("ERROR: Failed to establish connection with database named \"%s\". (Error code: %d)\n", nome, r);
    }
}
// Creates the POST message to be sent to the host server
// takes body which is the Json string
char *createDBentry(char *body){

    char* objID;
    
    // sets the header
	char* header = "PUT /v1/app/" APP KEY "/text HTTP/1.1\r\nHost: www.cloudmine.me\r\nX-CloudMine-ApiKey: 4a1bbce6b8864246a52262fe920dad52\r\nContent-Type: application/json\r\nContent-Length: ";
    
    // find the length of the body arg
    int blen = strlen(body);
    
    //casts a number to a string and appends \r\n\r\n to it
    char c[20];
    sprintf(c, "%d", blen);
    strcat(c, "\r\n\r\n");
    
    // find length of total content message
    int tlen = strlen(header) + strlen(c) + blen + 9;
    
    // allocate memory for the content
    char * content = (char*)malloc( tlen * sizeof(char) );
    char * index = content; // assigns a pointer to content
    
    // copy header to context and increment the index pointer length of header
    strncpy(content, header, strlen(header) );
    index = (index + strlen(header));
    
    // copy c and move the index pointer down length of c
    strncpy(index, c, strlen(c));
    index = (index + strlen(c));
    
    // copy body and move index pointer down length of body
    strncpy(index, body, blen);
    index = (index + blen);
    
    // append the last line
    strncpy(index, "\r\n\r\n", 9);
    
   // printf("header %s \n", content);
    
    // send the object to the server
    objID = connectDB(content, tlen);
   // printf("header %s \n", objID);

    return objID;
}
Beispiel #22
0
int Login::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QWidget::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: gotConnection((*reinterpret_cast< bool(*)>(_a[1]))); break;
        case 1: validate(); break;
        case 2: loadForm((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 3: showForm((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 4: connectDB((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< const QString(*)>(_a[3])),(*reinterpret_cast< const QString(*)>(_a[4])),(*reinterpret_cast< const QString(*)>(_a[5])),(*reinterpret_cast< const QString(*)>(_a[6]))); break;
        default: ;
        }
        _id -= 5;
    }
    return _id;
}
bool DataLayer::addDeal(QString n, double p, QString d) {
    if(connectDB()) {
 qDebug()<<"connected";
 removedeal(n);
        QSqlQuery query;

query.prepare("insert into deals (name, Price,details) values ('"+n+"',:pp,'"+d+"')");

query.bindValue(":pp",p);

query.exec();
return true;
    }
    else {
        qDebug()<<"not connected";
return false;
    }
}
void DataLayer::addDealFood(QString n,  QString fn, int q ) {
    if(connectDB()) {
 qDebug()<<"connected";

 QSqlQuery query;

query.prepare("insert into dealitems (name, fooditem, quantity) values ('"+n+"','"+fn+"',:pp )");
query.bindValue(":pp",q);

query.exec();

    }
    else {
        qDebug()<<"not connected";
}


}
// Creates a DELETE message to send to the server to delete a record
// takes a key of the object in the database
void deleteDBentry(char *key){
    
    // inits the headers with the keys
    char* headerp1 = "DELETE /v1/app/" APP KEY "/data?keys=";
    char* headerp2 = " HTTP/1.1\r\nHost: www.cloudmine.me\r\nX-CloudMine-ApiKey: 4a1bbce6b8864246a52262fe920dad52\r\n\r\n";

    // init a buffer to hold the content
    char reqBuf[256] = "";
    
    // copy all data into reqBuf
    strcat(reqBuf, headerp1);
    strcat(reqBuf, key);
    strcat(reqBuf, headerp2);

    // send content message to the server to be deleted
    connectDB(reqBuf, 256);

    return;
}
bool MainWindow::importSettings()
{
	MTSettings *settings;

	settings = new MTSettings(QCoreApplication::organizationName(), QCoreApplication::applicationName());

	if (!settings->importSettings()) {
		qDebug() << "Failed to read settings";
	}

	db.setHostName(settings->db_host);
	db.setDatabaseName(settings->db_name);
	db.setUserName(settings->db_user);
	db.setPassword(settings->db_password);

	connectDB();

	delete settings;
	return true;
}
void DataLayer::addfoo(QString n, double p, QString d, QString u, QString t)
{
    if(connectDB()) {
 qDebug()<<"connected";
 removefood(n);
        QSqlQuery query;

query.prepare("insert into [Food Item] (name, Price, details, units, type) values ('"+n+"',:pp, '"+d+"', '"+u+"','"+t+"')");

query.bindValue(":pp",p);

query.exec();
query.prepare("insert into Menu(Name,_Description,Price,_type) values('"+n+"','"+d+"',:price,'"+t+"') ");
query.bindValue(":price",p);
query.exec();
    }
    else {
        qDebug()<<"not connected";

    }
}
void DataLayer::addemp(QString n, QString c,int p,float s,QString t,QString pw,float h, float w)
{
    if(connectDB()){
        removeemp(c);
        cout<<"hello"<<endl;
QSqlQuery query;
double d=static_cast<double>(s);
double dd=static_cast<double>(h);
double ddd=static_cast<double>(w);
cout<<"In query func"<<endl;
query.prepare("insert into Employee(Name,CNIC,Phone_no,_Type,Salary) values(:name,:cnic,:phone,:type,:salary)");
query.bindValue(":name",n);
query.bindValue(":cnic",c);
query.bindValue(":phone",p);
query.bindValue(":salary",d);
query.bindValue(":type",t);
query.bindValue(":password",pw);
query.exec();
       closeDB();
       //return true;
    }
}
/** emailからユーザー取得
 *
 * @param email
 *
 * @return 見つかれば1, 見つからないと0
 */
int userFindByEmail(user_t *user, char *email){

  // 変数の初期化
  MYSQL_RES *resp = NULL;
  MYSQL_ROW row;
  char sql[200];

  // MySQLと接続
  MYSQL *conn = connectDB();

  // クエリ生成
  sprintf(sql, "SELECT * FROM users WHERE email = '%s' LIMIT 1", email);
  //printf(sql);

  // クエリ実行
  excuteSQL(conn, sql);

  // レスポンスを取り出す
  resp = mysql_use_result(conn);

  // 見つからなかったらreturn 0
  if ((row = mysql_fetch_row(resp)) == NULL) {
    printf("couldn't find user\n");
    return 0;
  }

  // 取り出したレスポンスを構造体Userにマッピング
  user->id = atoi(row[0]);
  strncpy(user->name, row[1], sizeof(user->name));
  strncpy(user->password, row[2], sizeof(user->password));
  strncpy(user->email, row[3], sizeof(user->email));
  //printf( "%d : %s, pass: %s\n" , user.id , user.name, user.password );
  
  // 後片づけ
  mysql_free_result(resp);
  mysql_close(conn);
  return 1;
}
int SSmain(int    argc, 
		SSchar* argv[])
{
	HDBC	hdbc;
	HENV	henv;
	HSTMT	hstmt;
	SQLRETURN  return_code;


	UTLDbUtlProgStart (argc, argv, SSText("log.txt"), DB_PD_DDL_EXPORT_PROCNAME);

	/*1. Connect to DB*/
	connectDB(&henv, &hdbc);

    /* HSTMT   hstmt_session;
    return_code = SQLAllocStmt ((SQLHDBC)hdbc, (SQLHSTMT *)&hstmt_session);
	if (return_code != SQL_SUCCESS)
	{
		printf("ERROR: The SQL statement did not execute successfully.\n");
		exit(1);
	}

   return_code = SQLExecDirect(hstmt_session, SSText("alter session set NLS_LANGUAGE='SIMPLIFIED CHINESE'"), -3);
   SQLFreeStmt(hstmt_session, SQL_DROP);*/

	/*3. Execute the SQL statement*/
	return_code = SQLAllocStmt ((SQLHDBC)hdbc, (SQLHSTMT *)&hstmt);
	if (return_code != SQL_SUCCESS)
	{  
		printf("ERROR: The SQL statement did not execute successfully.\n");
		exit(1);
	}
	
	SSchar*     pFilterStmt =  SSText("INSERT INTO TEST_CLOB_COL VALUES (?)");
	//SSchar*     pFilterStmt =  SSText("INSERT INTO test(LOG_DATA_1) VALUES (?)");
	return_code = SQLPrepare(hstmt, (SSuchar*)(pFilterStmt), SQL_NTS);   
	SSchar clobcol[] = {0x3042,0x3044,0x3046,0x3048,0x304A, 0x0000};
   /* test 1:
	LONG        cbRowId = 10;
	//return_code= SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_VARCHAR, 4000, 0, clobcol, sizeof(clobcol), &cbRowId); //This is ok!
	return_code= SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_LONGVARCHAR, 40, 0, clobcol, 10, &cbRowId);
    
	return_code = SQLExecute((SQLHSTMT)hstmt); 
   */

   /*test 2*/
   //test a: LONG cbRowId = SQL_DATA_AT_EXEC;
   LONG cbRowId = SQL_LEN_DATA_AT_EXEC(11);
   return_code= SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_LONGVARCHAR, 40, 0, clobcol, 10, &cbRowId);
   return_code = SQLExecute((SQLHSTMT)hstmt);
   SSchar *buf = clobcol;
   return_code = SQLParamData(hstmt, (SQLPOINTER *)&buf);
   return_code = SQLPutData(hstmt, buf, 10);
   return_code = SQLParamData(hstmt, (SQLPOINTER *)&buf);

	if (return_code == SQL_SUCCESS)
	{
		printf("The SQL statement executed successfully.\n");
	}
	else{
		printf("The SQL statement did not execute successfully.\n");
		ODBC_error ((HENV)henv, (HDBC)hdbc, (HSTMT)hstmt) ;
	}

   SSchar*     pSelectStmt =  SSText("select userenv('language') from dual");
	//SSchar*     pFilterStmt =  SSText("INSERT INTO test(LOG_DATA_1) VALUES (?)");
	return_code = SQLPrepare(hstmt, (SSuchar*)(pSelectStmt), SQL_NTS);

	return_code = SQLExecute((SQLHSTMT)hstmt); 
   

	SQLDisconnect ((SQLHDBC)hdbc);
	SQLFreeConnect ((SQLHDBC)hdbc);
	SQLFreeEnv ((SQLHENV)henv);

	return(return_code);
}