void CDataBase::Connect() { ADDTOCALLSTACK("CDataBase::Connect"); SimpleThreadLock lock(m_connectionMutex); if ( m_connected ) return; if ( mysql_get_client_version() < LIBMYSQL_VERSION_ID ) { #ifdef _WIN32 g_Log.EventWarn("Your MySQL client library %s is outdated. For better compatibility, update your 'libmysql.dll' file to version %s\n", mysql_get_client_info(), LIBMYSQL_VERSION); #else g_Log.EventWarn("Your MySQL client library %s is outdated. For better compatibility, update your 'libmysqlclient' package to version %s\n", mysql_get_client_info(), LIBMYSQL_VERSION); #endif } m_socket = mysql_init(NULL); if ( !m_socket ) { g_Log.EventError("Insufficient memory to initialize MySQL client socket\n"); return; } const char *user = g_Cfg.m_sMySqlUser; const char *password = g_Cfg.m_sMySqlPass; const char *db = g_Cfg.m_sMySqlDB; const char *host = g_Cfg.m_sMySqlHost; unsigned int port = MYSQL_PORT; // If user define server port using hostname:port format, split values into different variables const char *pszArgs = strchr(host, ':'); if ( pszArgs != NULL ) { char *pszTemp = Str_GetTemp(); strcpy(pszTemp, host); *(strchr(pszTemp, ':')) = 0; port = ATOI(pszArgs + 1); host = pszTemp; } if ( mysql_real_connect(m_socket, host, user, password, db, port, NULL, CLIENT_MULTI_STATEMENTS) ) { m_connected = true; if ( mysql_get_server_version(m_socket) < MYSQL_VERSION_ID ) g_Log.EventWarn("Your MySQL server %s is outdated. For better compatibility, update your MySQL server to version %s\n", mysql_get_server_info(m_socket), MYSQL_SERVER_VERSION); } else { g_Log.EventError("MySQL error #%u: %s\n", mysql_errno(m_socket), mysql_error(m_socket)); mysql_close(m_socket); m_socket = NULL; } }
bool MySQLConnection::Open() { MYSQL *mysqlInit; mysqlInit = mysql_init(NULL); if (!mysqlInit) { sLog->outError("Could not initialize Mysql connection to database `%s`", m_connectionInfo.database.c_str()); return false; } int port; char const* unix_socket; mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8"); #ifdef _WIN32 if (m_connectionInfo.host == ".") // named pipe use option (Windows) { unsigned int opt = MYSQL_PROTOCOL_PIPE; mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); port = 0; unix_socket = 0; } else // generic case { port = atoi(m_connectionInfo.port_or_socket.c_str()); unix_socket = 0; } #else if (m_connectionInfo.host == ".") // socket use option (Unix/Linux) { unsigned int opt = MYSQL_PROTOCOL_SOCKET; mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*) &opt); m_connectionInfo.host = "localhost"; port = 0; unix_socket = m_connectionInfo.port_or_socket.c_str(); } else // generic case { port = atoi(m_connectionInfo.port_or_socket.c_str()); unix_socket = 0; } #endif m_Mysql = mysql_real_connect(mysqlInit, m_connectionInfo.host.c_str(), m_connectionInfo.user.c_str(), m_connectionInfo.password.c_str(), m_connectionInfo.database.c_str(), port, unix_socket, 0); if (m_Mysql) { if (!m_reconnecting) { sLog->outSQLDriver("MySQL client library: %s", mysql_get_client_info()); sLog->outSQLDriver("MySQL server ver: %s ", mysql_get_server_info(m_Mysql)); if (mysql_get_server_version(m_Mysql) != mysql_get_client_version()) sLog->outSQLDriver( "[WARNING] MySQL client/server version mismatch; may conflict with behaviour of prepared statements."); } sLog->outDetail("Connected to MySQL database at %s", m_connectionInfo.host.c_str()); mysql_autocommit(m_Mysql, 1); // set connection properties to UTF8 to properly handle locales for different // server configs - core sends data in UTF8, so MySQL must expect UTF8 too mysql_set_character_set(m_Mysql, "utf8"); return PrepareStatements(); } else { sLog->outError("Could not connect to MySQL database at %s: %s\n", m_connectionInfo.host.c_str(), mysql_error(mysqlInit)); mysql_close(mysqlInit); return false; } }
static PyObject* wsql_get_client_info(PyObject *self) { CHECK_SERVER(NULL); return PyString_FromString(mysql_get_client_info()); }
void sql_connecter::show_info() { std::cout<<mysql_get_client_info()<<std::endl; }
int main () { printf("MySQL Client version: %s\n", mysql_get_client_info()); }
/* {{{ pdo_mysql_get_attribute */ static int pdo_mysql_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *return_value) { pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data; PDO_DBG_ENTER("pdo_mysql_get_attribute"); PDO_DBG_INF_FMT("dbh=%p", dbh); PDO_DBG_INF_FMT("attr=%l", attr); switch (attr) { case PDO_ATTR_CLIENT_VERSION: ZVAL_STRING(return_value, (char *)mysql_get_client_info()); break; case PDO_ATTR_SERVER_VERSION: ZVAL_STRING(return_value, (char *)mysql_get_server_info(H->server)); break; case PDO_ATTR_CONNECTION_STATUS: ZVAL_STRING(return_value, (char *)mysql_get_host_info(H->server)); break; case PDO_ATTR_SERVER_INFO: { #if defined(PDO_USE_MYSQLND) zend_string *tmp; if (mysqlnd_stat(H->server, &tmp) == PASS) { ZVAL_STR(return_value, tmp); #else char *tmp; if ((tmp = (char *)mysql_stat(H->server))) { ZVAL_STRING(return_value, tmp); #endif } else { pdo_mysql_error(dbh); PDO_DBG_RETURN(-1); } } break; case PDO_ATTR_AUTOCOMMIT: ZVAL_LONG(return_value, dbh->auto_commit); break; case PDO_ATTR_DEFAULT_STR_PARAM: ZVAL_LONG(return_value, H->assume_national_character_set_strings ? PDO_PARAM_STR_NATL : PDO_PARAM_STR_CHAR); break; case PDO_MYSQL_ATTR_USE_BUFFERED_QUERY: ZVAL_LONG(return_value, H->buffered); break; case PDO_ATTR_EMULATE_PREPARES: case PDO_MYSQL_ATTR_DIRECT_QUERY: ZVAL_LONG(return_value, H->emulate_prepare); break; #ifndef PDO_USE_MYSQLND case PDO_MYSQL_ATTR_MAX_BUFFER_SIZE: ZVAL_LONG(return_value, H->max_buffer_size); break; #endif default: PDO_DBG_RETURN(0); } PDO_DBG_RETURN(1); } /* }}} */ /* {{{ pdo_mysql_check_liveness */ static int pdo_mysql_check_liveness(pdo_dbh_t *dbh) { pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data; PDO_DBG_ENTER("pdo_mysql_check_liveness"); PDO_DBG_INF_FMT("dbh=%p", dbh); if (mysql_ping(H->server)) { PDO_DBG_RETURN(FAILURE); } PDO_DBG_RETURN(SUCCESS); }
int main(int argc, char* argv[]) { char sPGhost[26], sPGport[26], sPGdb[26], sPGuser[26], sPGpass[26]; printf("Postgres connection settings\n Host>"); scanf("%s",sPGhost); printf(" Port>"); scanf("%s",sPGport); printf(" Base>"); scanf("%s",sPGdb); printf(" User>"); scanf("%s",sPGuser); printf(" Pass>"); scanf("%s",sPGpass); /////////////////////////////// ///////PGSQL Connect/////////// /////////////////////////////// PGconn *mPGconn=NULL; mPGconn = PQsetdbLogin(sPGhost,sPGport, NULL, NULL, sPGdb, sPGuser, sPGpass); if (PQstatus(mPGconn) != CONNECTION_OK) { printf("Could not connect to Postgre database at [%s]: \n %s\n",sPGhost, PQerrorMessage(mPGconn)); PQfinish(mPGconn); return 1; } else { printf("Connected to Postgre database at [%s]\n", sPGhost); printf(" PostgreSQL server ver: [%d]\n\n",PQserverVersion(mPGconn)); } /// Set dummy notice processor PQsetNoticeProcessor(mPGconn, pg_notice, mPGconn); /////////////////////////////// ///////MySQL Connect/////////// /////////////////////////////// MYSQL *mysqlInit; mysqlInit = mysql_init(NULL); if (!mysqlInit) { printf( "Could not initialize Mysql connection\n" ); return 1; } char sMYhost[26], sMYdb[26], sMYuser[26], sMYpass[26]; int iMYport; printf("Mysql connection settings \n Host>"); scanf("%s",sMYhost); printf(" Port>"); scanf("%d",&iMYport); printf(" Base>"); scanf("%s",sMYdb); printf(" User>"); scanf("%s",sMYuser); printf(" Pass>"); scanf("%s",sMYpass); mysql_options(mysqlInit,MYSQL_SET_CHARSET_NAME,"utf8"); MYSQL *mMysql; mMysql = mysql_real_connect(mysqlInit, sMYhost, sMYuser, sMYpass, sMYdb, iMYport, NULL, 0); if (mMysql) { printf( "Connected to MySQL database at [%s] \n", sMYhost); printf( " MySQL client library: [%s] \n", mysql_get_client_info()); printf( " MySQL server ver: [%s] \n\n", mysql_get_server_info( mMysql)); } else { printf("Could not connect to MySQL database at [%s]:\n %s\n", sMYhost ,mysql_error(mysqlInit)); mysql_close(mysqlInit); return 1; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// MYSQL_RES *result = NULL; MYSQL_ROW row; MYSQL_FIELD *fields = NULL; uint64 rowCount = 0; uint32 fieldCount =0; result = mysql_list_tables( mMysql , NULL ); rowCount = mysql_num_rows(result); /***********************/ /* get list of tables */ /***********************/ T_TableList mTableList; mTableList.reserve((size_t)rowCount); while( (row = mysql_fetch_row(result)) !=NULL ) { for (uint32 i = 0;i<mysql_num_fields(result);i++) { mTableList.push_back(row[i]); } } mysql_free_result(result); /****************************************/ /* convert filed type and default type */ /****************************************/ T_Table m_Table; TDataBase m_DataBase_Map; m_DataBase_Map.clear(); for (uint32 j=0; j<mTableList.size();++j) { result = mysql_list_fields(mMysql, mTableList[j].c_str(), NULL); fieldCount = mysql_num_fields(result); fields = mysql_fetch_fields(result); for (uint32 i=0; i<fieldCount;++i) { sField mfield; mfield.name = fields[i].name; if (!fields[i].def) { mfield.def = "NULL"; } else if (!strcmp(fields[i].def,"0000-00-00 00:00:00")) { /// Convert MySQL Default timestamp to PGSQL Default timestamp mfield.def.append("'1970-01-01 00:00:00'"); } else { /// Append ' mfield.def.append("'"); mfield.def.append(fields[i].def);; mfield.def.append("'"); } mfield.type = ConvertNativeType(fields[i].type,fields[i].length); mfield.flags = fields[i].flags; m_Table.push_back(mfield); } m_DataBase_Map[mTableList[j]] = m_Table; m_Table.clear(); mysql_free_result(result); } /******************************************/ /* Conversion of the layout of the tables */ /******************************************/ uint32 count = 0; TDataBase::const_iterator citr; for (citr = m_DataBase_Map.begin(); citr != m_DataBase_Map.end(); ++citr) { ostringstream sql_str; sql_str<<"DROP TABLE IF EXISTS "<<(*citr).first.c_str()<<";\n"; sql_str<<"CREATE TABLE "<<(*citr).first.c_str()<<"(\n"; T_Table::const_iterator v_iter; ostringstream prim_key_str; ostringstream index_str; for (v_iter = (*citr).second.begin(); v_iter != (*citr).second.end(); ++v_iter) { sql_str<<" "<<(*v_iter).name; if (((*v_iter).flags & AUTO_INCREMENT_FLAG)!=0) { /// AUTO_INCREMENT fields not have "default" data sql_str<<" bigserial"; } else { sql_str<<" "<<(*v_iter).type; sql_str<<" default "<<(*v_iter).def; } /// IF column have PRIMARY KEY flag then use column in PRIMARY KEY if (IS_PRI_KEY( (*v_iter).flags )!=0) { if( prim_key_str.str().size()) prim_key_str << ", "; else { prim_key_str << "ALTER TABLE "; prim_key_str << (*citr).first.c_str(); prim_key_str << " ADD CONSTRAINT pk_"; prim_key_str << (*citr).first.c_str(); prim_key_str << "_"; prim_key_str << (*v_iter).name; prim_key_str << " PRIMARY KEY ("; } prim_key_str<<(*v_iter).name; } else if (((*v_iter).flags & MULTIPLE_KEY_FLAG)!=0) { /// IF column have INDEX flag then create INDEX index_str << "CREATE INDEX idx_"; index_str << (*citr).first.c_str(); index_str << "_"; index_str << (*v_iter).name; index_str << " ON "; index_str << (*citr).first.c_str(); index_str << " USING btree ("; index_str << (*v_iter).name; index_str << ");\n"; } else if (((*v_iter).flags & UNIQUE_KEY_FLAG)!=0) { /// IF column have UNIQUE INDEX flag then create INDEX index_str << "CREATE UNIQUE INDEX uidx_"; index_str << (*citr).first.c_str(); index_str << "_"; index_str << (*v_iter).name; index_str << " ON "; index_str << (*citr).first.c_str(); index_str << " USING btree ("; index_str << (*v_iter).name; index_str << ");\n"; } /// don't output "," for last column if(v_iter + 1 != (*citr).second.end()) sql_str<< ",\n"; else sql_str<< "\n"; } sql_str<< ")\n"; /// Out Table structure PG_Exec_str(sql_str.str(),mPGconn); /// out PRIMARY KEY if(prim_key_str.str().size()) { prim_key_str<<")"; PG_Exec_str(prim_key_str.str(),mPGconn); } /// out INDEX's if (index_str.str().size()) PG_Exec_str(index_str.str(),mPGconn); ++count; printf("Convert [%d] tables...\r",count); } printf("Completed the conversion of [%d] tables!\n", count); /****************/ /* Copying data */ /****************/ count = 0; for (uint32 j=0; j<mTableList.size();++j) { ostringstream sql_str; sql_str << "SELECT * FROM "; sql_str << mTableList[j].c_str(); if (mysql_query(mysqlInit,sql_str.str().c_str()) ) continue; if (!(result = mysql_store_result(mysqlInit))) continue; while ((row = mysql_fetch_row(result))!=NULL) { ostringstream insert_str; insert_str << "INSERT INTO "; insert_str << mTableList[j].c_str(); insert_str << " VALUES ("; fieldCount = mysql_num_fields(result); fields = mysql_fetch_fields(result); for (uint32 i = 0 ; i < fieldCount ; ++i) { if (!row[i]) insert_str << "NULL"; else { if (IsNeeedEscapeString(fields[i].type)) { string field_str = row[i]; PG_Escape_Str(field_str); insert_str << "E'"; insert_str << field_str.c_str(); insert_str << "'"; } else if (!strcmp(row[i],"0000-00-00 00:00:00")) { /// Convert MySQL timestamp to PGSQL timestamp insert_str << "'1970-01-01 00:00:00'"; } else { insert_str << "'"; insert_str << row[i]; insert_str << "'"; } } /// don't output "," for last column if(i + 1 != fieldCount ) insert_str<< ","; else insert_str<< ")\n"; } PG_Exec_str(insert_str.str(), mPGconn); } mysql_free_result(result); ++count; printf("Copied data from [%d] tables...\r",count); } printf("Finished copying the data from [%d] tables!\n",count); mTableList.clear(); m_DataBase_Map.clear(); /// Close connections mysql_close(mMysql); PQfinish(mPGconn); printf("end\n"); return 0; }
/* {{{ pdo_mysql_get_attribute */ static int pdo_mysql_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *return_value) { pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data; PDO_DBG_ENTER("pdo_mysql_get_attribute"); PDO_DBG_INF_FMT("dbh=%p", dbh); PDO_DBG_INF_FMT("attr=%l", attr); switch (attr) { case PDO_ATTR_CLIENT_VERSION: ZVAL_STRING(return_value, (char *)mysql_get_client_info()); break; case PDO_ATTR_SERVER_VERSION: ZVAL_STRING(return_value, (char *)mysql_get_server_info(H->server)); break; case PDO_ATTR_CONNECTION_STATUS: ZVAL_STRING(return_value, (char *)mysql_get_host_info(H->server)); break; case PDO_ATTR_SERVER_INFO: { #if defined(PDO_USE_MYSQLND) zend_string *tmp; if (mysqlnd_stat(H->server, &tmp) == PASS) { ZVAL_STR(return_value, tmp); #else char *tmp; if ((tmp = (char *)mysql_stat(H->server))) { ZVAL_STRING(return_value, tmp); #endif } else { pdo_mysql_error(dbh); PDO_DBG_RETURN(-1); } } break; case PDO_ATTR_AUTOCOMMIT: ZVAL_LONG(return_value, dbh->auto_commit); break; case PDO_MYSQL_ATTR_USE_BUFFERED_QUERY: ZVAL_LONG(return_value, H->buffered); break; case PDO_ATTR_EMULATE_PREPARES: case PDO_MYSQL_ATTR_DIRECT_QUERY: ZVAL_LONG(return_value, H->emulate_prepare); break; #ifndef PDO_USE_MYSQLND case PDO_MYSQL_ATTR_MAX_BUFFER_SIZE: ZVAL_LONG(return_value, H->max_buffer_size); break; #endif default: PDO_DBG_RETURN(0); } PDO_DBG_RETURN(1); } /* }}} */ /* {{{ pdo_mysql_check_liveness */ static int pdo_mysql_check_liveness(pdo_dbh_t *dbh) { pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data; #if MYSQL_VERSION_ID <= 32230 void (*handler) (int); unsigned int my_errno; #endif PDO_DBG_ENTER("pdo_mysql_check_liveness"); PDO_DBG_INF_FMT("dbh=%p", dbh); #if MYSQL_VERSION_ID > 32230 if (mysql_ping(H->server)) { PDO_DBG_RETURN(FAILURE); } #else /* no mysql_ping() */ handler = signal(SIGPIPE, SIG_IGN); mysql_stat(H->server); switch (mysql_errno(H->server)) { case CR_SERVER_GONE_ERROR: case CR_SERVER_LOST: signal(SIGPIPE, handler); PDO_DBG_RETURN(FAILURE); default: break; } signal(SIGPIPE, handler); #endif /* end mysql_ping() */ PDO_DBG_RETURN(SUCCESS); }
void dbInit(char * iniFilename, int channelCount, char dbColumns[][MAX_COLUMN_NAME_LEN], char dbTypes[][MAX_COLUMN_TYPE_LEN]) { char server[30]; char database[30]; char rootUsername[30]; char rootPassword[30]; char username[30]; char password[30]; char query[2000]; int errno; int channelNr; strcpy(_iniFilename, iniFilename); _channelCount = channelCount; GetPrivateProfileString_("DB", "root_username", "root", rootUsername, sizeof(rootUsername), _iniFilename); GetPrivateProfileString_("DB", "root_password", "", rootPassword, sizeof(rootPassword), _iniFilename); GetPrivateProfileString_("DB", "username", "sma", username, sizeof(username), _iniFilename); GetPrivateProfileString_("DB", "password", "smysqlogger", password, sizeof(password), _iniFilename); GetPrivateProfileString_("DB", "server", "localhost", server, sizeof(server), _iniFilename); GetPrivateProfileString_("DB", "database", "sma", database, sizeof(database), _iniFilename); printLog(LEVEL_DETAIL, "Connecting to MySQL as %s@%s:%s (client version: %s)\n", trim(username), trim(server), trim(database), mysql_get_client_info()); // Init connection structure _conn = mysql_init(NULL); if (_conn == NULL) { printLog(LEVEL_FATAL, "Error %u initializing connection structure : %s\n", mysql_errno(_conn), mysql_error(_conn)); exit(-10); } // Connect to DB if (mysql_real_connect(_conn, server, username, password, database, 0, NULL, 0) == NULL) { errno = mysql_errno(_conn); if (errno != 1049 && errno != 1045) { printLog(LEVEL_FATAL, "Error %u connecting to Database: %s\n", errno, mysql_error(_conn)); exit(-11); } else { // DB instance doesn't exist. Let's create it. // Information is sent to stdout and not logged to file for this one-shot code printf("Database '%s' doesn't exist. Trying to create it...", database); // Connect without specifying DB if (mysql_real_connect(_conn, server, rootUsername, rootPassword, NULL, 0, NULL, 0) == NULL) { printf("Error %u connecting to Database: %s\n", mysql_errno(_conn), mysql_error(_conn)); exit(-12); } // Create DB if it doesn't exist sprintf(query, "create database if not exists %s", database); if (mysql_query(_conn, query)) { printf("Error %u creating Database: %s\n", mysql_errno(_conn), mysql_error(_conn)); exit(-13); } // Create User if it doesn't exist sprintf(query, "create user %s@localhost identified by '%s'", username, password); if (mysql_query(_conn, query)) { printf("Error %u creating user: %s\n", mysql_errno(_conn), mysql_error(_conn)); exit(-14); } // Grant User rights sprintf(query, "GRANT ALL PRIVILEGES ON %s.* TO %s@localhost;", database, username); if (mysql_query(_conn, query)) { printf("Error %u granting rights: %s\n", mysql_errno(_conn), mysql_error(_conn)); exit(-15); } // Succeeded. Let's reconnect to new DB mysql_close(_conn); printf("Done. Reconnecting to newly created database...\n", database); _conn = mysql_init(NULL); if (_conn == NULL) { printf("Error %u re-initializing connection structure : %s\n", mysql_errno(_conn), mysql_error(_conn)); exit(-16); } if (mysql_real_connect(_conn, server, username, password, database, 0, NULL, 0) == NULL) { printLog(LEVEL_FATAL, "Error %u connecting to new Database: %s\n", mysql_errno(_conn), mysql_error(_conn)); exit(-17); } printf("\nCongratulations. A new database called '%s' has been created, with the table 'logged_values'.\n\ A new user '%s' has also been created and was granted access to the new DB.\n\ It is now strongly recommended to edit yasdi.ini to remove the\n\ root_username/root_password information.\n\nWaiting 20 seconds...\n", database, username); fflush(stdout); sleep(20); } }
int main(void) { int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; struct sigaction sa; int yes=1; char s[INET6_ADDRSTRLEN]; int rv; // Connect to the database MYSQL *MySQLConRet; MYSQL *MySQLConnection = NULL; const char *hostName = "localhost"; const char *userId = "espuser"; const char *password = "******"; const char *DB = "tanklevels"; MySQLConnection = mysql_init( NULL ); // try // { MySQLConRet = mysql_real_connect( MySQLConnection,hostName,userId,password,DB,0,NULL,0 ); if ( MySQLConRet == NULL ) { printf("error connecting to SQL"); printf(mysql_error(MySQLConnection)); exit; } printf("MySQL Connection Info: %s \n", mysql_get_host_info(MySQLConnection)); printf("MySQL Client Info: %s \n", mysql_get_client_info()); printf("MySQL Server Info: %s \n", mysql_get_server_info(MySQLConnection)); // } // catch ( FFError e ) // { // printf("%s\n",e.Label.c_str()); // return 1; // } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } freeaddrinfo(servinfo); // all done with this structure if (p == NULL) { fprintf(stderr, "server: failed to bind\n"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } sa.sa_handler = sigchld_handler; // reap all dead processes sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } printf("server: waiting for connections...\n"); while(1) { // main accept() loop sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { perror("accept"); continue; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); printf("server: got connection from %s\n", s); if (!fork()) { // this is the child process close(sockfd); // child doesn't need the listener //const char *filename1 = "data.log"; //const char *filename2 = "data2.log"; char buf[MAXDATASIZE]; int numbytes = 0; int done = 0; while(done == 0) { if ((numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); break; } if (numbytes == 0) { printf("\nConnection closed by client\n"); break; } buf[numbytes] = '\0'; printf("%s: received '%s'\n",s,buf); char buffer [500]; if ((strncmp(buf, "GET", 3) == 0) || (strncmp(buf, "q", 1) == 0)){ sprintf(buffer, "SELECT * FROM tanklevel_rt\0"); printf(buffer); printf("\n"); if (mysql_query(MySQLConnection, buffer)) { printf("Error %u: %s\n", mysql_errno(MySQLConnection), mysql_error(MySQLConnection)); } else { char sbuffer [5000]; char sbuf [500]; printf("selected tanklevel_rt\n"); MYSQL_RES *res; /* holds the result set */ res = mysql_store_result(MySQLConnection); // get the number of the columns int num_fields = mysql_num_fields(res); MYSQL_ROW row; sbuffer[0] = '\0'; // Fetch all rows from the result while ((row = mysql_fetch_row(res))) { sbuf[0] = '\0'; // Print all columns int i = 0; for(i = 0; i < num_fields; i++) { // Make sure row[i] is valid! if(row[i] != NULL) { sprintf(sbuf, "%s%s,", sbuf, row[i]); } else { sprintf(sbuf, "%sNULL,", sbuf); } // Also, you can use ternary operator here instead of if-else // cout << row[i] ? row[i] : "NULL" << endl; } sprintf(sbuffer, "%s%s\n\0", sbuffer, sbuf); sprintf(sbuf,"%s\0", sbuf); printf("%s\n", sbuf); } //if (send(new_fd, "<h1>Hello, world!</h1>", 22, 0) == -1) { char sbuffer2 [5000]; if (strncmp(buf, "GET", 3) == 0) { printf("%s\n", sbuffer); sprintf(sbuffer2, "<html><body>%s</body></html>\0", sbuffer); } else { printf("%s\n", sbuffer); sprintf(sbuffer2, "%s\0", sbuffer); } if (send(new_fd, sbuffer2, strlen(sbuffer2), 0) == -1) { printf("Error sending"); } else { printf("Sent: %s\n",sbuffer2); } done = 1; } } else { struct tm *current; time_t now; time(&now); current = localtime(&now); char id; id = s[strlen(s)-1]; sprintf(buffer, "%i-%i-%i %i:%i:%i,%s,%s-%c\n\0", current->tm_year+1900, current->tm_mon+1, current->tm_mday, current->tm_hour, current->tm_min, current->tm_sec, s, buf, id); printf("%s", buffer); //FILE *file1; //file1 = fopen(filename1, "a"); //if (file1) { // fwrite(buffer, sizeof(char), strlen(buffer), file1); // fclose (file1); //} int buf_int = atoi(buf); if ((buf_int < 20000) && (buf_int > 0)) { struct timeval tv; gettimeofday(&tv, NULL); uint64 start = tv.tv_usec; start /= 1000; start += (tv.tv_sec * 1000); sprintf(buffer, "UPDATE tanklevel_rt SET value=%s, timestamp=\"%i-%i-%i %i:%i:%i\" WHERE tankid = %c\0", buf, current->tm_year+1900, current->tm_mon+1, current->tm_mday, current->tm_hour, current->tm_min, current->tm_sec, id); printf("%c-%s",id,buffer); printf("\n"); if (mysql_query(MySQLConnection, buffer)) { printf("%c-Error %u: %s\n", id,mysql_errno(MySQLConnection), mysql_error(MySQLConnection)); } else { gettimeofday(&tv, NULL); uint64 end = tv.tv_usec; end /= 1000; end += (tv.tv_sec * 1000); printf("%c-Updated DB (%dms)\n", id, end-start); } } else { printf("Invalid value %d\n", buf_int); } } } close(new_fd); exit(0); } close(new_fd); // parent doesn't need this } return 0; }
int main(){ MYSQL *MySQLConRet; MYSQL *MySQLConnection = NULL; char *hostname = "localhost"; char *user = "******"; char password[20]; char *db = "hedistest"; MySQLConnection = mysql_init(NULL); printf("enter password: "******"%s", password); MySQLConRet = mysql_real_connect(MySQLConnection, hostname, user, password, db, 0, NULL, 0); if(MySQLConRet == NULL){ printf("fail\n"); return 1; } printf("MySQL Connection Info: %s \n", mysql_get_host_info(MySQLConnection)); printf("MySQL Client Info: %s \n", mysql_get_client_info()); printf("MySQL Server Info: %s \n", mysql_get_server_info(MySQLConnection)); int mysqlStatus = 0; MYSQL_RES *mysqlResult = NULL; if(mysqlResult){ mysql_free_result(mysqlResult); mysqlResult = NULL; } MYSQL_ROW mysqlRow; MYSQL_FIELD *mysqlFields; my_ulonglong numRows; unsigned int numFields; char *sqlSelStatement = "select * from user"; mysqlStatus = mysql_query(MySQLConnection, sqlSelStatement); if(mysqlStatus){ printf((char *)mysql_error(MySQLConnection)); return 1; } mysqlResult = mysql_store_result(MySQLConnection); if(mysqlResult){ numRows = mysql_num_rows(mysqlResult); numFields = mysql_field_count(MySQLConnection); numFields = mysql_num_fields(mysqlResult); printf("Number of rows=%u Number of fields=%u \n", numRows, numFields); }else{ printf("Result set is empty\n"); } mysqlFields = mysql_fetch_fields(mysqlResult); for(int i = 0; i < numFields; i++){ printf("%s\t", mysqlFields[i].name); } printf("\n"); while(mysqlRow = mysql_fetch_row(mysqlResult)){ for(int i = 0; i < numFields; i++){ printf("%s\t", mysqlRow[i] ? mysqlRow[i] : "NULL"); } printf("\n"); } if(mysqlResult){ mysql_free_result(mysqlResult); mysqlResult = NULL; } mysql_close(MySQLConnection); return 0; }
void init_mysql2_client() { #ifdef _WIN32 /* verify the libmysql we're about to use was the version we were built against https://github.com/luislavena/mysql-gem/commit/a600a9c459597da0712f70f43736e24b484f8a99 */ int i; int dots = 0; const char *lib = mysql_get_client_info(); for (i = 0; lib[i] != 0 && MYSQL_LINK_VERSION[i] != 0; i++) { if (lib[i] == '.') { dots++; /* we only compare MAJOR and MINOR */ if (dots == 2) break; } if (lib[i] != MYSQL_LINK_VERSION[i]) { rb_raise(rb_eRuntimeError, "Incorrect MySQL client library version! This gem was compiled for %s but the client library is %s.", MYSQL_LINK_VERSION, lib); } } #endif /* Initializing mysql library, so different threads could call Client.new */ /* without race condition in the library */ if (mysql_library_init(0, NULL, NULL) != 0) { rb_raise(rb_eRuntimeError, "Could not initialize MySQL client library"); } #if 0 mMysql2 = rb_define_module("Mysql2"); Teach RDoc about Mysql2 constant. #endif cMysql2Client = rb_define_class_under(mMysql2, "Client", rb_cObject); rb_define_alloc_func(cMysql2Client, allocate); rb_define_singleton_method(cMysql2Client, "escape", rb_mysql_client_escape, 1); rb_define_singleton_method(cMysql2Client, "info", rb_mysql_client_info, 0); rb_define_method(cMysql2Client, "close", rb_mysql_client_close, 0); rb_define_method(cMysql2Client, "closed?", rb_mysql_client_closed, 0); rb_define_method(cMysql2Client, "abandon_results!", rb_mysql_client_abandon_results, 0); rb_define_method(cMysql2Client, "escape", rb_mysql_client_real_escape, 1); rb_define_method(cMysql2Client, "server_info", rb_mysql_client_server_info, 0); rb_define_method(cMysql2Client, "socket", rb_mysql_client_socket, 0); rb_define_method(cMysql2Client, "async_result", rb_mysql_client_async_result, 0); rb_define_method(cMysql2Client, "last_id", rb_mysql_client_last_id, 0); rb_define_method(cMysql2Client, "affected_rows", rb_mysql_client_affected_rows, 0); rb_define_method(cMysql2Client, "prepare", rb_mysql_client_prepare_statement, 1); rb_define_method(cMysql2Client, "thread_id", rb_mysql_client_thread_id, 0); rb_define_method(cMysql2Client, "ping", rb_mysql_client_ping, 0); rb_define_method(cMysql2Client, "select_db", rb_mysql_client_select_db, 1); rb_define_method(cMysql2Client, "more_results?", rb_mysql_client_more_results, 0); rb_define_method(cMysql2Client, "next_result", rb_mysql_client_next_result, 0); rb_define_method(cMysql2Client, "store_result", rb_mysql_client_store_result, 0); rb_define_method(cMysql2Client, "automatic_close?", get_automatic_close, 0); rb_define_method(cMysql2Client, "automatic_close=", set_automatic_close, 1); rb_define_method(cMysql2Client, "reconnect=", set_reconnect, 1); rb_define_method(cMysql2Client, "warning_count", rb_mysql_client_warning_count, 0); rb_define_method(cMysql2Client, "query_info_string", rb_mysql_info, 0); rb_define_method(cMysql2Client, "ssl_cipher", rb_mysql_get_ssl_cipher, 0); #ifdef HAVE_RUBY_ENCODING_H rb_define_method(cMysql2Client, "encoding", rb_mysql_client_encoding, 0); #endif rb_define_private_method(cMysql2Client, "connect_timeout=", set_connect_timeout, 1); rb_define_private_method(cMysql2Client, "read_timeout=", set_read_timeout, 1); rb_define_private_method(cMysql2Client, "write_timeout=", set_write_timeout, 1); rb_define_private_method(cMysql2Client, "local_infile=", set_local_infile, 1); rb_define_private_method(cMysql2Client, "charset_name=", set_charset_name, 1); rb_define_private_method(cMysql2Client, "secure_auth=", set_secure_auth, 1); rb_define_private_method(cMysql2Client, "default_file=", set_read_default_file, 1); rb_define_private_method(cMysql2Client, "default_group=", set_read_default_group, 1); rb_define_private_method(cMysql2Client, "init_command=", set_init_command, 1); rb_define_private_method(cMysql2Client, "ssl_set", set_ssl_options, 5); rb_define_private_method(cMysql2Client, "ssl_mode=", rb_set_ssl_mode_option, 1); rb_define_private_method(cMysql2Client, "enable_cleartext_plugin=", set_enable_cleartext_plugin, 1); rb_define_private_method(cMysql2Client, "initialize_ext", initialize_ext, 0); rb_define_private_method(cMysql2Client, "connect", rb_connect, 7); rb_define_private_method(cMysql2Client, "_query", rb_query, 2); sym_id = ID2SYM(rb_intern("id")); sym_version = ID2SYM(rb_intern("version")); sym_header_version = ID2SYM(rb_intern("header_version")); sym_async = ID2SYM(rb_intern("async")); sym_symbolize_keys = ID2SYM(rb_intern("symbolize_keys")); sym_as = ID2SYM(rb_intern("as")); sym_array = ID2SYM(rb_intern("array")); sym_stream = ID2SYM(rb_intern("stream")); intern_brackets = rb_intern("[]"); intern_merge = rb_intern("merge"); intern_merge_bang = rb_intern("merge!"); intern_new_with_args = rb_intern("new_with_args"); #ifdef CLIENT_LONG_PASSWORD rb_const_set(cMysql2Client, rb_intern("LONG_PASSWORD"), LONG2NUM(CLIENT_LONG_PASSWORD)); #else /* HACK because MariaDB 10.2 no longer defines this constant, * but we're using it in our default connection flags. */ rb_const_set(cMysql2Client, rb_intern("LONG_PASSWORD"), INT2NUM(0)); #endif #ifdef CLIENT_FOUND_ROWS rb_const_set(cMysql2Client, rb_intern("FOUND_ROWS"), LONG2NUM(CLIENT_FOUND_ROWS)); #endif #ifdef CLIENT_LONG_FLAG rb_const_set(cMysql2Client, rb_intern("LONG_FLAG"), LONG2NUM(CLIENT_LONG_FLAG)); #endif #ifdef CLIENT_CONNECT_WITH_DB rb_const_set(cMysql2Client, rb_intern("CONNECT_WITH_DB"), LONG2NUM(CLIENT_CONNECT_WITH_DB)); #endif #ifdef CLIENT_NO_SCHEMA rb_const_set(cMysql2Client, rb_intern("NO_SCHEMA"), LONG2NUM(CLIENT_NO_SCHEMA)); #endif #ifdef CLIENT_COMPRESS rb_const_set(cMysql2Client, rb_intern("COMPRESS"), LONG2NUM(CLIENT_COMPRESS)); #endif #ifdef CLIENT_ODBC rb_const_set(cMysql2Client, rb_intern("ODBC"), LONG2NUM(CLIENT_ODBC)); #endif #ifdef CLIENT_LOCAL_FILES rb_const_set(cMysql2Client, rb_intern("LOCAL_FILES"), LONG2NUM(CLIENT_LOCAL_FILES)); #endif #ifdef CLIENT_IGNORE_SPACE rb_const_set(cMysql2Client, rb_intern("IGNORE_SPACE"), LONG2NUM(CLIENT_IGNORE_SPACE)); #endif #ifdef CLIENT_PROTOCOL_41 rb_const_set(cMysql2Client, rb_intern("PROTOCOL_41"), LONG2NUM(CLIENT_PROTOCOL_41)); #endif #ifdef CLIENT_INTERACTIVE rb_const_set(cMysql2Client, rb_intern("INTERACTIVE"), LONG2NUM(CLIENT_INTERACTIVE)); #endif #ifdef CLIENT_SSL rb_const_set(cMysql2Client, rb_intern("SSL"), LONG2NUM(CLIENT_SSL)); #endif #ifdef CLIENT_IGNORE_SIGPIPE rb_const_set(cMysql2Client, rb_intern("IGNORE_SIGPIPE"), LONG2NUM(CLIENT_IGNORE_SIGPIPE)); #endif #ifdef CLIENT_TRANSACTIONS rb_const_set(cMysql2Client, rb_intern("TRANSACTIONS"), LONG2NUM(CLIENT_TRANSACTIONS)); #endif #ifdef CLIENT_RESERVED rb_const_set(cMysql2Client, rb_intern("RESERVED"), LONG2NUM(CLIENT_RESERVED)); #endif #ifdef CLIENT_SECURE_CONNECTION rb_const_set(cMysql2Client, rb_intern("SECURE_CONNECTION"), LONG2NUM(CLIENT_SECURE_CONNECTION)); #else /* HACK because MySQL5.7 no longer defines this constant, * but we're using it in our default connection flags. */ rb_const_set(cMysql2Client, rb_intern("SECURE_CONNECTION"), LONG2NUM(0)); #endif #ifdef CLIENT_MULTI_STATEMENTS rb_const_set(cMysql2Client, rb_intern("MULTI_STATEMENTS"), LONG2NUM(CLIENT_MULTI_STATEMENTS)); #endif #ifdef CLIENT_PS_MULTI_RESULTS rb_const_set(cMysql2Client, rb_intern("PS_MULTI_RESULTS"), LONG2NUM(CLIENT_PS_MULTI_RESULTS)); #endif #ifdef CLIENT_SSL_VERIFY_SERVER_CERT rb_const_set(cMysql2Client, rb_intern("SSL_VERIFY_SERVER_CERT"), LONG2NUM(CLIENT_SSL_VERIFY_SERVER_CERT)); #endif #ifdef CLIENT_REMEMBER_OPTIONS rb_const_set(cMysql2Client, rb_intern("REMEMBER_OPTIONS"), LONG2NUM(CLIENT_REMEMBER_OPTIONS)); #endif #ifdef CLIENT_ALL_FLAGS rb_const_set(cMysql2Client, rb_intern("ALL_FLAGS"), LONG2NUM(CLIENT_ALL_FLAGS)); #endif #ifdef CLIENT_BASIC_FLAGS rb_const_set(cMysql2Client, rb_intern("BASIC_FLAGS"), LONG2NUM(CLIENT_BASIC_FLAGS)); #endif #if defined(FULL_SSL_MODE_SUPPORT) // MySQL 5.7.11 and above rb_const_set(cMysql2Client, rb_intern("SSL_MODE_DISABLED"), INT2NUM(SSL_MODE_DISABLED)); rb_const_set(cMysql2Client, rb_intern("SSL_MODE_PREFERRED"), INT2NUM(SSL_MODE_PREFERRED)); rb_const_set(cMysql2Client, rb_intern("SSL_MODE_REQUIRED"), INT2NUM(SSL_MODE_REQUIRED)); rb_const_set(cMysql2Client, rb_intern("SSL_MODE_VERIFY_CA"), INT2NUM(SSL_MODE_VERIFY_CA)); rb_const_set(cMysql2Client, rb_intern("SSL_MODE_VERIFY_IDENTITY"), INT2NUM(SSL_MODE_VERIFY_IDENTITY)); #elif defined(HAVE_CONST_MYSQL_OPT_SSL_ENFORCE) // MySQL 5.7.3 - 5.7.10 rb_const_set(cMysql2Client, rb_intern("SSL_MODE_DISABLED"), INT2NUM(SSL_MODE_DISABLED)); rb_const_set(cMysql2Client, rb_intern("SSL_MODE_REQUIRED"), INT2NUM(SSL_MODE_REQUIRED)); #endif #ifndef HAVE_CONST_SSL_MODE_DISABLED rb_const_set(cMysql2Client, rb_intern("SSL_MODE_DISABLED"), INT2NUM(0)); #endif #ifndef HAVE_CONST_SSL_MODE_PREFERRED rb_const_set(cMysql2Client, rb_intern("SSL_MODE_PREFERRED"), INT2NUM(0)); #endif #ifndef HAVE_CONST_SSL_MODE_REQUIRED rb_const_set(cMysql2Client, rb_intern("SSL_MODE_REQUIRED"), INT2NUM(0)); #endif #ifndef HAVE_CONST_SSL_MODE_VERIFY_CA rb_const_set(cMysql2Client, rb_intern("SSL_MODE_VERIFY_CA"), INT2NUM(0)); #endif #ifndef HAVE_CONST_SSL_MODE_VERIFY_IDENTITY rb_const_set(cMysql2Client, rb_intern("SSL_MODE_VERIFY_IDENTITY"), INT2NUM(0)); #endif }
/* {{{ property driver_client_info_read */ static zval *driver_client_info_read(mysqli_object *obj, zval *retval) { ZVAL_STRING(retval, (char *)mysql_get_client_info()); return retval; }
/*++ DbInit Initializes the procedure table and database connection pool. Arguments: getProc - Pointer to ioFTPD's GetProc function. Return Values: If the function succeeds, the return value is nonzero (true). If the function fails, the return value is zero (false). --*/ BOOL FCALL DbInit(Io_GetProc *getProc) { DWORD result; #if 0 // Wait for debugger to be attached before proceeding WaitForDebugger(); #endif TRACE("refCount=%d", refCount); // Only initialize the database pool once if (InterlockedIncrement(&refCount) > 1) { TRACE("Already initialized, returning."); return TRUE; } // Initialize procedure table result = ProcTableInit(getProc); if (result != ERROR_SUCCESS) { TRACE("Unable to initialize procedure table (error %lu).", result); return FALSE; } // Initialize configuration structures result = ConfigInit(); if (result != ERROR_SUCCESS) { TRACE("Unable to initialize configuration system (error %lu).", result); return FALSE; } // Initialize logging system result = LogInit(); if (result != ERROR_SUCCESS) { TRACE("Unable to initialize logging system (error %lu).", result); return FALSE; } // // Now that the logging system has been initialized, the LOG_* macros are // available for use. Prior to this point, the TRACE macro must be used. // // Load configuration options result = ConfigLoad(); if (result != ERROR_SUCCESS) { TRACE("Unable to load configuration (error %lu).", result); DbFinalize(); return FALSE; } // Create connection pool result = PoolCreate(&dbPool, dbConfigPool.minimum, dbConfigPool.average, dbConfigPool.maximum, dbConfigPool.timeoutMili, ConnectionOpen, ConnectionCheck, ConnectionClose, NULL); if (result != ERROR_SUCCESS) { LOG_ERROR("Unable to initialize connection pool (error %lu).", result); DbFinalize(); return FALSE; } LOG_INFO("nxMyDB v%s loaded, using MySQL Client Library v%s.", STRINGIFY(VERSION), mysql_get_client_info()); return TRUE; }
LRESULT CALLBACK AboutDialog( HWND hwnd, unsigned int msg, WPARAM wparam, LPARAM lparam ) { HWND richtext; switch ( msg ) { case WM_COMMAND: if ( HIWORD( wparam ) == BN_CLICKED && ( HWND ) lparam == GetDlgItem( hwnd, IDOK ) ) { EndDialog( hwnd, 0 ); } break; case WM_CLOSE: EndDialog( hwnd, 0 ); break; case WM_INITDIALOG: richtext = GetDlgItem( hwnd, IDC_RICHEDIT ); if ( richtext ) { HRSRC resource = FindResource( appInstance, MAKEINTRESOURCE( IDD_CREDITS ), RT_RCDATA ); HGLOBAL rData = LoadResource( appInstance, resource ); const char* data = ( const char* ) LockResource( rData ); QStringList creditList = QStringList::split( ",", data ); UnlockResource( rData ); FreeResource( rData ); CHARRANGE cr; CHARFORMAT2 cf; ZeroMemory( &cf, sizeof( cf ) ); cf.cbSize = sizeof( cf ); // Add a version information header (just like the console) QString version = QString( "%1 %2 %3\n" ).arg( productString(), productBeta(), productVersion() ); cf.dwMask = CFM_COLOR | CFM_WEIGHT | CFM_SIZE; cf.yHeight = 20 * 14; cf.wWeight = FW_BOLD; cf.crTextColor = RGB( 60, 140, 70 ); SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf ); SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) version.latin1() ); cf.dwMask = CFM_COLOR | CFM_WEIGHT | CFM_SIZE; cf.yHeight = 20 * 8; cf.wWeight = FW_NORMAL; cf.crTextColor = RGB( 0, 0, 0 ); QString credits; credits += tr( "Compiled: %1 %2\n" ).arg( __DATE__, __TIME__ ); credits += tr( "Qt: %1 %2 (Compiled: %3)\n" ).arg( qVersion() ).arg( qSharedBuild() ? "Shared" : "Static" ).arg( QT_VERSION_STR ); QString pythonBuild = Py_GetVersion(); pythonBuild = pythonBuild.left( pythonBuild.find( ' ' ) ); #if defined(Py_ENABLE_SHARED) credits += tr( "Python: %1 Shared (Compiled: %2)\n" ).arg( pythonBuild ).arg( PY_VERSION ); #else credits += tr( "Python: %1 Static (Compiled: %2)\n" ).arg( pythonBuild ).arg( PY_VERSION ); #endif credits += tr( "Compiled with SQLite %1\n" ).arg( SQLITE_VERSION ); #if defined (MYSQL_DRIVER) credits += tr( "Compiled for MySQL %1 (Using: %2)\n" ).arg( MYSQL_SERVER_VERSION, mysql_get_client_info() ); #else credits += tr( "MySQL Support: disabled\n" ); #endif cr.cpMin = GetWindowTextLength( richtext ); cr.cpMax = cr.cpMin; SendMessage( richtext, EM_EXSETSEL, 0, ( LPARAM ) & cr ); SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf ); SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) credits.latin1() ); credits = tr( "\nThis is an unsorted and not neccesarily complete list of people who contributed to Wolfpack:\n\n" ); cr.cpMin = GetWindowTextLength( richtext ); cr.cpMax = cr.cpMin; cf.wWeight = FW_BOLD; SendMessage( richtext, EM_EXSETSEL, 0, ( LPARAM ) & cr ); SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf ); SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) credits.latin1() ); cf.wWeight = FW_NORMAL; credits = ""; for ( unsigned int i = 0; i < creditList.size(); ++i ) { credits.append( creditList[i] ); } cr.cpMin = GetWindowTextLength( richtext ); cr.cpMax = cr.cpMin; SendMessage( richtext, EM_EXSETSEL, 0, ( LPARAM ) & cr ); SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf ); SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) credits.latin1() ); } } return FALSE; }
static JSVAL get_client_info(JSARGS args) { HandleScope scope; return scope.Close(String::New(mysql_get_client_info())); }
// const char * STDCALL mysql_get_client_info(void); static IDL_VPTR IDL_mg_mysql_get_client_info(int argc, IDL_VPTR *argv) { const char *info = mysql_get_client_info(); return IDL_StrToSTRING(info); }
static String HHVM_FUNCTION(mysql_get_client_info) { return String(mysql_get_client_info(), CopyString); }
int main(int argc, char **argv) { printf("MySQL Client Info: %s\n", mysql_get_client_info()); return EXIT_SUCCESS; }
String f_mysql_get_client_info() { return String(mysql_get_client_info(), CopyString); }
int main(void) { printf("MySQL client version: %s\n", mysql_get_client_info()); return 0; }
bool MySQLConnection::Initialize(const char* infoString) { MYSQL* mysqlInit = mysql_init(NULL); if (!mysqlInit) { sLog.outError("Could not initialize Mysql connection"); return false; } Tokens tokens = StrSplit(infoString, ";"); Tokens::iterator iter; std::string host, port_or_socket, user, password, database; int port; char const* unix_socket; iter = tokens.begin(); if (iter != tokens.end()) { host = *iter++; } if (iter != tokens.end()) { port_or_socket = *iter++; } if (iter != tokens.end()) { user = *iter++; } if (iter != tokens.end()) { password = *iter++; } if (iter != tokens.end()) { database = *iter++; } mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8"); mysql_options(mysqlInit, MYSQL_OPT_RECONNECT, "1"); #ifdef WIN32 if (host == ".") // named pipe use option (Windows) { unsigned int opt = MYSQL_PROTOCOL_PIPE; mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); port = 0; unix_socket = 0; } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #else if (host == ".") // socket use option (Unix/Linux) { unsigned int opt = MYSQL_PROTOCOL_SOCKET; mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); host = "localhost"; port = 0; unix_socket = port_or_socket.c_str(); } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #endif mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, unix_socket, 0); if (!mMysql) { sLog.outError("Could not connect to MySQL database at %s: %s\n", host.c_str(), mysql_error(mysqlInit)); mysql_close(mysqlInit); return false; } DETAIL_LOG("Connected to MySQL database %s@%s:%s/%s", user.c_str(), host.c_str(), port_or_socket.c_str(), database.c_str()); sLog.outString("MySQL client library: %s", mysql_get_client_info()); sLog.outString("MySQL server ver: %s ", mysql_get_server_info(mMysql)); /*----------SET AUTOCOMMIT ON---------*/ // It seems mysql 5.0.x have enabled this feature // by default. In crash case you can lose data!!! // So better to turn this off // --- // This is wrong since mangos use transactions, // autocommit is turned of during it. // Setting it to on makes atomic updates work // --- // LEAVE 'AUTOCOMMIT' MODE ALWAYS ENABLED!!! // W/O IT EVEN 'SELECT' QUERIES WOULD REQUIRE TO BE WRAPPED INTO 'START TRANSACTION'<>'COMMIT' CLAUSES!!! if (!mysql_autocommit(mMysql, 1)) { DETAIL_LOG("AUTOCOMMIT SUCCESSFULLY SET TO 1"); } else { DETAIL_LOG("AUTOCOMMIT NOT SET TO 1"); } /*-------------------------------------*/ // set connection properties to UTF8 to properly handle locales for different // server configs - core sends data in UTF8, so MySQL must expect UTF8 too Execute("SET NAMES `utf8`"); Execute("SET CHARACTER SET `utf8`"); return true; }
void version() { printf("Version:%s\n", mysql_get_client_info()); }
int main( int argc, char * argv[] ) { char szSQL[ 200 ], aszFlds[ 25 ][ 25 ], szDB[ 50 ] ; const char * pszT; int i, j, k, l, x ; MYSQL * myData ; MYSQL_RES * res ; MYSQL_FIELD * fd ; MYSQL_ROW row ; //....just curious.... printf( "sizeof( MYSQL ) == %d\n", sizeof( MYSQL ) ) ; if ( argc == 2 ) { strcpy( szDB, argv[ 1 ] ) ; strcpy( szSQL, DEFALT_SQL_STMT ) ; if (!strcmp(szDB,"--debug")) { strcpy( szDB, "mysql" ) ; printf("Some mysql struct information (size and offset):\n"); printf("net:\t%3d %3d\n",sizeof(myData->net),offsetof(MYSQL,net)); printf("host:\t%3d %3d\n",sizeof(myData->host),offsetof(MYSQL,host)); printf("port:\t%3d %3d\n",sizeof(myData->port),offsetof(MYSQL,port)); printf("protocol_version:\t%3d %3d\n",sizeof(myData->protocol_version), offsetof(MYSQL,protocol_version)); printf("thread_id:\t%3d %3d\n",sizeof(myData->thread_id), offsetof(MYSQL,thread_id)); printf("affected_rows:\t%3d %3d\n",sizeof(myData->affected_rows), offsetof(MYSQL,affected_rows)); printf("packet_length:\t%3d %3d\n",sizeof(myData->packet_length), offsetof(MYSQL,packet_length)); printf("status:\t%3d %3d\n",sizeof(myData->status), offsetof(MYSQL,status)); printf("fields:\t%3d %3d\n",sizeof(myData->fields), offsetof(MYSQL,fields)); printf("field_alloc:\t%3d %3d\n",sizeof(myData->field_alloc), offsetof(MYSQL,field_alloc)); printf("free_me:\t%3d %3d\n",sizeof(myData->free_me), offsetof(MYSQL,free_me)); printf("options:\t%3d %3d\n",sizeof(myData->options), offsetof(MYSQL,options)); puts(""); } } else if ( argc > 2 ) { strcpy( szDB, argv[ 1 ] ) ; strcpy( szSQL, argv[ 2 ] ) ; } else { strcpy( szDB, "mysql" ) ; strcpy( szSQL, DEFALT_SQL_STMT ) ; } //.... if ( (myData = mysql_init((MYSQL*) 0)) && mysql_real_connect( myData, NULL, NULL, NULL, NULL, MYSQL_PORT, NULL, 0 ) ) { if ( mysql_select_db( myData, szDB ) < 0 ) { printf( "Can't select the %s database !\n", szDB ) ; mysql_close( myData ) ; return 2 ; } } else { printf( "Can't connect to the mysql server on port %d !\n", MYSQL_PORT ) ; mysql_close( myData ) ; return 1 ; } //.... if ( ! mysql_query( myData, szSQL ) ) { res = mysql_store_result( myData ) ; i = (int) mysql_num_rows( res ) ; l = 1 ; printf( "Query: %s\nNumber of records found: %ld\n", szSQL, i ) ; //....we can get the field-specific characteristics here.... for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ ) strcpy( aszFlds[ x ], fd->name ) ; //.... while ( row = mysql_fetch_row( res ) ) { j = mysql_num_fields( res ) ; printf( "Record #%ld:-\n", l++ ) ; for ( k = 0 ; k < j ; k++ ) printf( " Fld #%d (%s): %s\n", k + 1, aszFlds[ k ], (((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ; puts( "==============================\n" ) ; } mysql_free_result( res ) ; } else printf( "Couldn't execute %s on the server !\n", szSQL ) ; //.... puts( "==== Diagnostic info ====" ) ; pszT = mysql_get_client_info() ; printf( "Client info: %s\n", pszT ) ; //.... pszT = mysql_get_host_info( myData ) ; printf( "Host info: %s\n", pszT ) ; //.... pszT = mysql_get_server_info( myData ) ; printf( "Server info: %s\n", pszT ) ; //.... res = mysql_list_processes( myData ) ; l = 1 ; if (res) { for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ ) strcpy( aszFlds[ x ], fd->name ) ; while ( row = mysql_fetch_row( res ) ) { j = mysql_num_fields( res ) ; printf( "Process #%ld:-\n", l++ ) ; for ( k = 0 ; k < j ; k++ ) printf( " Fld #%d (%s): %s\n", k + 1, aszFlds[ k ], (((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ; puts( "==============================\n" ) ; } } else { printf("Got error %s when retreiving processlist\n",mysql_error(myData)); } //.... res = mysql_list_tables( myData, "%" ) ; l = 1 ; for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ ) strcpy( aszFlds[ x ], fd->name ) ; while ( row = mysql_fetch_row( res ) ) { j = mysql_num_fields( res ) ; printf( "Table #%ld:-\n", l++ ) ; for ( k = 0 ; k < j ; k++ ) printf( " Fld #%d (%s): %s\n", k + 1, aszFlds[ k ], (((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ; puts( "==============================\n" ) ; } //.... pszT = mysql_stat( myData ) ; puts( pszT ) ; //.... mysql_close( myData ) ; return 0 ; }
int main(int argc, char **argv) { printf("MySQL client version: %s\n", mysql_get_client_info()); exit(0); }
bool MySQLConnection::Open(const std::string& infoString) { MYSQL *mysqlInit; mysqlInit = mysql_init(NULL); if (!mysqlInit) { sLog.outError("Could not initialize Mysql connection"); return false; } Tokens tokens = StrSplit(infoString, ";"); Tokens::iterator iter; std::string host, port_or_socket, user, password, database; int port; char const* unix_socket; iter = tokens.begin(); if (iter != tokens.end()) host = *iter++; if (iter != tokens.end()) port_or_socket = *iter++; if (iter != tokens.end()) user = *iter++; if (iter != tokens.end()) password = *iter++; if (iter != tokens.end()) database = *iter++; mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8"); #ifdef _WIN32 if (host==".") // named pipe use option (Windows) { unsigned int opt = MYSQL_PROTOCOL_PIPE; mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); port = 0; unix_socket = 0; } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #else if (host==".") // socket use option (Unix/Linux) { unsigned int opt = MYSQL_PROTOCOL_SOCKET; mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); host = "localhost"; port = 0; unix_socket = port_or_socket.c_str(); } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #endif m_Mysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, unix_socket, 0); if (m_Mysql) { sLog.outSQLDriver("MySQL client library: %s", mysql_get_client_info()); sLog.outSQLDriver("MySQL server ver: %s ", mysql_get_server_info(m_Mysql)); if (mysql_get_server_version(m_Mysql) != mysql_get_client_version()) sLog.outSQLDriver("[WARNING] MySQL client/server version mismatch; may conflict with behaviour of prepared statements."); sLog.outDetail("Connected to MySQL database at %s", host.c_str()); if (!mysql_autocommit(m_Mysql, 1)) sLog.outSQLDriver("AUTOCOMMIT SUCCESSFULLY SET TO 1"); else sLog.outSQLDriver("AUTOCOMMIT NOT SET TO 1"); // set connection properties to UTF8 to properly handle locales for different // server configs - core sends data in UTF8, so MySQL must expect UTF8 too Execute("SET NAMES `utf8`"); Execute("SET CHARACTER SET `utf8`"); #if MYSQL_VERSION_ID >= 50003 my_bool my_true = (my_bool)1; if (mysql_options(m_Mysql, MYSQL_OPT_RECONNECT, &my_true)) sLog.outSQLDriver("Failed to turn on MYSQL_OPT_RECONNECT."); else sLog.outSQLDriver("Successfully turned on MYSQL_OPT_RECONNECT."); #else #warning "Your mySQL client lib version does not support reconnecting after a timeout.\nIf this causes you any trouble we advice you to upgrade your mySQL client libs to at least mySQL 5.0.13 to resolve this problem." #endif return true; } else { sLog.outError("Could not connect to MySQL database at %s: %s\n", host.c_str(), mysql_error(mysqlInit)); mysql_close(mysqlInit); return false; } }
bool DatabaseMysql::Initialize(const char *infoString) { if(!Database::Initialize(infoString)) return false; tranThread = NULL; MYSQL *mysqlInit; mysqlInit = mysql_init(NULL); if (!mysqlInit) { sLog.outError( "Could not initialize Mysql connection" ); return false; } InitDelayThread(); Tokens tokens = StrSplit(infoString, ";"); Tokens::iterator iter; std::string host, port_or_socket, user, password, database; int port; char const* unix_socket; iter = tokens.begin(); if(iter != tokens.end()) host = *iter++; if(iter != tokens.end()) port_or_socket = *iter++; if(iter != tokens.end()) user = *iter++; if(iter != tokens.end()) password = *iter++; if(iter != tokens.end()) database = *iter++; mysql_options(mysqlInit,MYSQL_SET_CHARSET_NAME,"utf8"); #ifdef WIN32 if(host==".") // named pipe use option (Windows) { unsigned int opt = MYSQL_PROTOCOL_PIPE; mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt); port = 0; unix_socket = 0; } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #else if(host==".") // socket use option (Unix/Linux) { unsigned int opt = MYSQL_PROTOCOL_SOCKET; mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt); host = "localhost"; port = 0; unix_socket = port_or_socket.c_str(); } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #endif mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, unix_socket, 0); if (mMysql) { DETAIL_LOG( "Connected to MySQL database at %s", host.c_str()); sLog.outString( "MySQL client library: %s", mysql_get_client_info()); sLog.outString( "MySQL server ver: %s ", mysql_get_server_info( mMysql)); /*----------SET AUTOCOMMIT ON---------*/ // It seems mysql 5.0.x have enabled this feature // by default. In crash case you can lose data!!! // So better to turn this off // --- // This is wrong since mangos use transactions, // autocommit is turned of during it. // Setting it to on makes atomic updates work if (!mysql_autocommit(mMysql, 1)) DETAIL_LOG("AUTOCOMMIT SUCCESSFULLY SET TO 1"); else DETAIL_LOG("AUTOCOMMIT NOT SET TO 1"); /*-------------------------------------*/ // set connection properties to UTF8 to properly handle locales for different // server configs - core sends data in UTF8, so MySQL must expect UTF8 too PExecute("SET NAMES `utf8`"); PExecute("SET CHARACTER SET `utf8`"); return true; } else { sLog.outError( "Could not connect to MySQL database at %s: %s\n", host.c_str(),mysql_error(mysqlInit)); mysql_close(mysqlInit); return false; } }
/* 得到客户信息 */ const char * CppMySQL3DB::getClientInfo() { return mysql_get_client_info(); }
void init_mysql2_client() { // verify the libmysql we're about to use was the version we were built against // https://github.com/luislavena/mysql-gem/commit/a600a9c459597da0712f70f43736e24b484f8a99 int i; int dots = 0; const char *lib = mysql_get_client_info(); for (i = 0; lib[i] != 0 && MYSQL_SERVER_VERSION[i] != 0; i++) { if (lib[i] == '.') { dots++; // we only compare MAJOR and MINOR if (dots == 2) break; } if (lib[i] != MYSQL_SERVER_VERSION[i]) { rb_raise(rb_eRuntimeError, "Incorrect MySQL client library version! This gem was compiled for %s but the client library is %s.", MYSQL_SERVER_VERSION, lib); return; } } #if 0 mMysql2 = rb_define_module("Mysql2"); Teach RDoc about Mysql2 constant. #endif cMysql2Client = rb_define_class_under(mMysql2, "Client", rb_cObject); rb_define_alloc_func(cMysql2Client, allocate); rb_define_singleton_method(cMysql2Client, "escape", rb_mysql_client_escape, 1); rb_define_method(cMysql2Client, "close", rb_mysql_client_close, 0); rb_define_method(cMysql2Client, "query", rb_mysql_client_query, -1); rb_define_method(cMysql2Client, "escape", rb_mysql_client_real_escape, 1); rb_define_method(cMysql2Client, "info", rb_mysql_client_info, 0); rb_define_method(cMysql2Client, "server_info", rb_mysql_client_server_info, 0); rb_define_method(cMysql2Client, "socket", rb_mysql_client_socket, 0); rb_define_method(cMysql2Client, "async_result", rb_mysql_client_async_result, 0); rb_define_method(cMysql2Client, "last_id", rb_mysql_client_last_id, 0); rb_define_method(cMysql2Client, "affected_rows", rb_mysql_client_affected_rows, 0); rb_define_method(cMysql2Client, "thread_id", rb_mysql_client_thread_id, 0); rb_define_method(cMysql2Client, "ping", rb_mysql_client_ping, 0); rb_define_method(cMysql2Client, "select_db", rb_mysql_client_select_db, 1); rb_define_method(cMysql2Client, "more_results", rb_mysql_client_more_results, 0); rb_define_method(cMysql2Client, "next_result", rb_mysql_client_next_result, 0); rb_define_method(cMysql2Client, "store_result", rb_mysql_client_store_result, 0); rb_define_method(cMysql2Client, "options", rb_mysql_client_options, 2); #ifdef HAVE_RUBY_ENCODING_H rb_define_method(cMysql2Client, "encoding", rb_mysql_client_encoding, 0); #endif rb_define_private_method(cMysql2Client, "reconnect=", set_reconnect, 1); rb_define_private_method(cMysql2Client, "connect_timeout=", set_connect_timeout, 1); rb_define_private_method(cMysql2Client, "read_timeout=", set_read_timeout, 1); rb_define_private_method(cMysql2Client, "local_infile=", set_local_infile, 1); rb_define_private_method(cMysql2Client, "charset_name=", set_charset_name, 1); rb_define_private_method(cMysql2Client, "ssl_set", set_ssl_options, 5); rb_define_private_method(cMysql2Client, "initialize_ext", initialize_ext, 0); rb_define_private_method(cMysql2Client, "connect", rb_connect, 7); intern_encoding_from_charset = rb_intern("encoding_from_charset"); sym_id = ID2SYM(rb_intern("id")); sym_version = ID2SYM(rb_intern("version")); sym_async = ID2SYM(rb_intern("async")); sym_symbolize_keys = ID2SYM(rb_intern("symbolize_keys")); sym_as = ID2SYM(rb_intern("as")); sym_array = ID2SYM(rb_intern("array")); sym_stream = ID2SYM(rb_intern("stream")); intern_merge = rb_intern("merge"); intern_error_number_eql = rb_intern("error_number="); intern_sql_state_eql = rb_intern("sql_state="); #ifdef CLIENT_LONG_PASSWORD rb_const_set(cMysql2Client, rb_intern("LONG_PASSWORD"), INT2NUM(CLIENT_LONG_PASSWORD)); #endif #ifdef CLIENT_FOUND_ROWS rb_const_set(cMysql2Client, rb_intern("FOUND_ROWS"), INT2NUM(CLIENT_FOUND_ROWS)); #endif #ifdef CLIENT_LONG_FLAG rb_const_set(cMysql2Client, rb_intern("LONG_FLAG"), INT2NUM(CLIENT_LONG_FLAG)); #endif #ifdef CLIENT_CONNECT_WITH_DB rb_const_set(cMysql2Client, rb_intern("CONNECT_WITH_DB"), INT2NUM(CLIENT_CONNECT_WITH_DB)); #endif #ifdef CLIENT_NO_SCHEMA rb_const_set(cMysql2Client, rb_intern("NO_SCHEMA"), INT2NUM(CLIENT_NO_SCHEMA)); #endif #ifdef CLIENT_COMPRESS rb_const_set(cMysql2Client, rb_intern("COMPRESS"), INT2NUM(CLIENT_COMPRESS)); #endif #ifdef CLIENT_ODBC rb_const_set(cMysql2Client, rb_intern("ODBC"), INT2NUM(CLIENT_ODBC)); #endif #ifdef CLIENT_LOCAL_FILES rb_const_set(cMysql2Client, rb_intern("LOCAL_FILES"), INT2NUM(CLIENT_LOCAL_FILES)); #endif #ifdef CLIENT_IGNORE_SPACE rb_const_set(cMysql2Client, rb_intern("IGNORE_SPACE"), INT2NUM(CLIENT_IGNORE_SPACE)); #endif #ifdef CLIENT_PROTOCOL_41 rb_const_set(cMysql2Client, rb_intern("PROTOCOL_41"), INT2NUM(CLIENT_PROTOCOL_41)); #endif #ifdef CLIENT_INTERACTIVE rb_const_set(cMysql2Client, rb_intern("INTERACTIVE"), INT2NUM(CLIENT_INTERACTIVE)); #endif #ifdef CLIENT_SSL rb_const_set(cMysql2Client, rb_intern("SSL"), INT2NUM(CLIENT_SSL)); #endif #ifdef CLIENT_IGNORE_SIGPIPE rb_const_set(cMysql2Client, rb_intern("IGNORE_SIGPIPE"), INT2NUM(CLIENT_IGNORE_SIGPIPE)); #endif #ifdef CLIENT_TRANSACTIONS rb_const_set(cMysql2Client, rb_intern("TRANSACTIONS"), INT2NUM(CLIENT_TRANSACTIONS)); #endif #ifdef CLIENT_RESERVED rb_const_set(cMysql2Client, rb_intern("RESERVED"), INT2NUM(CLIENT_RESERVED)); #endif #ifdef CLIENT_SECURE_CONNECTION rb_const_set(cMysql2Client, rb_intern("SECURE_CONNECTION"), INT2NUM(CLIENT_SECURE_CONNECTION)); #endif #ifdef CLIENT_MULTI_STATEMENTS rb_const_set(cMysql2Client, rb_intern("MULTI_STATEMENTS"), INT2NUM(CLIENT_MULTI_STATEMENTS)); #endif #ifdef CLIENT_PS_MULTI_RESULTS rb_const_set(cMysql2Client, rb_intern("PS_MULTI_RESULTS"), INT2NUM(CLIENT_PS_MULTI_RESULTS)); #endif #ifdef CLIENT_SSL_VERIFY_SERVER_CERT rb_const_set(cMysql2Client, rb_intern("SSL_VERIFY_SERVER_CERT"), INT2NUM(CLIENT_SSL_VERIFY_SERVER_CERT)); #endif #ifdef CLIENT_REMEMBER_OPTIONS rb_const_set(cMysql2Client, rb_intern("REMEMBER_OPTIONS"), INT2NUM(CLIENT_REMEMBER_OPTIONS)); #endif #ifdef CLIENT_ALL_FLAGS rb_const_set(cMysql2Client, rb_intern("ALL_FLAGS"), INT2NUM(CLIENT_ALL_FLAGS)); #endif #ifdef CLIENT_BASIC_FLAGS rb_const_set(cMysql2Client, rb_intern("BASIC_FLAGS"), INT2NUM(CLIENT_BASIC_FLAGS)); #endif }
static int check_session(const char *assertion, char *email) { printf("MySQL client version: %s\n", mysql_get_client_info()); MYSQL *conn; int query_rs; int num_rs; MYSQL_RES *rs; MYSQL_ROW row; char assertion_esc[300]; char *select_email = "SELECT email FROM browserid_session WHERE digest = MD5('%s')"; char select_email_esc[1024]; char *update_session = "UPDATE browserid_session SET created = NOW() WHERE digest = MD5('%s')"; char update_session_esc[1024]; int rv = 0; conn = mysql_init(NULL); if (conn == NULL) { error(1, 1, "Unable to mysql_init"); } conn = mysql_real_connect(conn, "localhost", "root", "", "mozillians", NULL, NULL, (void *) 0); if (conn == NULL) { printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); error(1, 1, "Unable to connect to mysql server"); } mysql_real_escape_string(conn, assertion_esc, assertion, strlen(assertion)); sprintf(select_email_esc, select_email, assertion_esc); printf(select_email_esc); printf("\n"); if (mysql_query(conn, select_email_esc) == 0) { rs = mysql_store_result(conn); while((row = mysql_fetch_row(rs))) { printf("Email: %s\n", row[0]); printf("\n"); strcpy(email, row[0]); rv = 1; /* Touch session */ sprintf(update_session_esc, update_session, assertion_esc); printf(update_session_esc); printf("\n"); mysql_query(conn, update_session_esc); break; } if (rs != 0) { mysql_free_result(rs); } } else if (query_rs == CR_UNKNOWN_ERROR) { error(1, 1, "Unkown Error"); } else if (query_rs == CR_SERVER_GONE_ERROR ||\ query_rs == CR_SERVER_LOST) { error(1, 1, "Executed query, SOL"); } else { printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); error(1, 1, mysql_error(conn)); } mysql_close(conn); return rv; }