int main(int argc, char** argv) { char SQLq[2048]; /* exit routine */ atexit (exitProc); /* check arguments */ if (readArgs(argc, argv) == FALSE) { fprintf (stderr, "You have to provide DB-Connection infos and the input directory with the XML-Files.\n"); return EXIT_FAILURE; } /* connect to Database, keep connection Idle */ if (!connectDB()) return EXIT_FAILURE; setlocale (LC_CTYPE,""); /* Drop old tables if they exist */ bzero (SQLq, 2048); sprintf (SQLq, db_DROP_TABLE, db_tvtable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while droping Table:%s.\n\t%s", db_tvtable, mysql_error(mysql_conn)); } printD ("Dropped Table:%s\n", db_tvtable); bzero (SQLq, 2048); sprintf (SQLq, db_CREATE_TVTABLE, db_tvtable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while creating Table:%s.\n\t%s", db_tvtable, mysql_error(mysql_conn)); } printD ("Created Table:%s\n", db_tvtable); /****TVEND****/ bzero (SQLq, 2048); sprintf (SQLq, db_DROP_TABLE, db_movietable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while droping Table:%s.\n\t%s", db_tvtable, mysql_error(mysql_conn)); } printD ("Dropped Table:%s\n", db_movietable); bzero (SQLq, 2048); sprintf (SQLq, db_CREATE_MOVIETABLE, db_movietable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while creating Table:%s.\n\t%s", db_movietable, mysql_error(mysql_conn)); } printD ("Created Table:%s\n", db_movietable); /****MOVIEEND****/ if (db_newstable) { bzero (SQLq, 2048); sprintf (SQLq, db_DROP_TABLE, db_newstable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while droping Table:%s.\n\t%s", db_newstable, mysql_error(mysql_conn)); } printD ("Dropped Table:%s\n", db_newstable); bzero (SQLq, 2048); sprintf (SQLq, db_CREATE_NEWS, db_newstable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while creating Table:%s.\n\t%s", db_newstable, mysql_error(mysql_conn)); } printD ("Created Table:%s\n", db_newstable); } /****NEWSEND****/ /* enter Mainloop and walk thru directory... */ mainLoop(); printD ("Mainloop returned gracefully, cleaning up the mess and leaving...\n"); return EXIT_SUCCESS; }
static int sqlalias_redir(request_rec *r) { MYSQL *dblink = NULL; server_rec *s = r->server; sqlalias_conf_t *s_cfg = (sqlalias_conf_t *) ap_get_module_config(s->module_config, &sqlalias_module); if (r->uri[0] != '/' && r->uri[0] != '\0') { return DECLINED; } else if(!s_cfg->enable || sqlalias_filter(r, s_cfg->filters) == FILTERED_URI || !(dblink = sqlalias_dbconnect(r->server, s_cfg))) { return DECLINED; } else { MYSQL_RES *result = NULL; MYSQL_ROW row; char *query = NULL; int found = 0; int response = 0; const char *ccp; int uri_length = strlen(r->uri); char *uri = (char *) malloc(sizeof(char) * (uri_length * 2 + 1)); strcpy(uri, r->uri); #ifndef SQLALIAS_PERFECT_MATCH if (uri_length > 1 && uri[uri_length-1] == '/') { uri[uri_length-1] = '\0'; uri_length--; } #endif /* SQLALIAS_PERFECT_MATCH */ mysql_real_escape_string(dblink, uri, uri, uri_length); query = apr_psprintf(r->pool, s_cfg->db_query, uri); free(uri); if(mysql_real_query(dblink, query, strlen(query))) { ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r->server, "sqlalias: %s.", mysql_error(dblink)); #ifdef SQLALIAS_USE_PCONNECT apr_thread_mutex_unlock(sqlalias_mutex); #else DEBUG_MSG(r->server, "sqlalias: Database connection closed. (pid:%d)", getpid()); mysql_close(dblink); #endif /* SQLALIAS_USE_PCONNECT */ return DECLINED; } if (!(result = mysql_store_result(dblink))) { ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r->server, "sqlalias: %s.", mysql_error(dblink)); #ifdef SQLALIAS_USE_PCONNECT apr_thread_mutex_unlock(sqlalias_mutex); #else DEBUG_MSG(r->server, "sqlalias: Database connection closed. (pid:%d)", getpid()); mysql_close(dblink); #endif /* SQLALIAS_USE_PCONNECT */ return DECLINED; } if((row = mysql_fetch_row(result))) { found = 1; response = (mysql_num_fields(result) > 1) ? atoi(row[1]) : DECLINED ; if(ap_is_HTTP_REDIRECT(response) || (is_absolute_uri(row[0]) && (response = HTTP_MOVED_TEMPORARILY))) { char *destination = apr_pstrdup(r->pool, row[0]); DEBUG_MSG(r->server, "sqlalias: %s redirect to %s (R=%d)", r->uri, destination, response?response:HTTP_OK); apr_table_setn(r->headers_out, "Location", destination); } else { DEBUG_MSG(r->server, "sqlalias: rewrite %s -> %s", r->uri, row[0]); /* the filename must be either an absolute local path or an * absolute local URL. */ if (*row[0] != '/' && !ap_os_is_path_absolute(r->pool, row[0])) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, "sqlalias: Bad redirection for %s (%s)", r->uri, row[0]); response = HTTP_BAD_REQUEST; } else if ((ccp = ap_document_root(r)) != NULL) { char *q = NULL; r->uri = apr_pstrdup(r->pool, row[0]); q = strchr(r->uri, '?'); if (q != NULL) { char *olduri = NULL; olduri = apr_pstrdup(r->pool, r->uri); *q++ = '\0'; if(r->args) r->args = apr_pstrcat(r->pool, q, "&", r->args, NULL); else r->args = apr_pstrdup(r->pool, q); if(strlen(r->args) == 0) r->args = NULL; } } } #ifdef SQLALIAS_DEBUG } else { DEBUG_MSG(r->server, "sqlalias: No entry for %s", r->uri); #endif /* SQLALIAS_DEBUG */ } mysql_free_result(result); #ifdef SQLALIAS_USE_PCONNECT apr_thread_mutex_unlock(sqlalias_mutex); #else DEBUG_MSG(r->server, "sqlalias: Database connection closed. (pid:%d)", getpid()); mysql_close(dblink); #endif /* SQLALIAS_USE_PCONNECT */ if(found && response != 200) return response; } return DECLINED; }
string DBConn::Query_single_mr_sql(string mr_id) { string mr_sql = SELECT_SINGLE_MR_SQL + Utils::AddSingleQuoteMark(mr_id); string fac_sql = SELECT_SINGLE_MR_FACILITY_SQL + Utils::AddSingleQuoteMark(mr_id); //查询可添加设备SQL string add_fac_sql=SELECT_MR_ADD_FACILITY_SQL; Json::Value Mr; Json::Value arrayObj, item;//已有设备 Json::Value arrayAdd, fac;//已有设备 int t = mysql_real_query(&mysql, mr_sql.c_str(), (unsigned int) strlen(mr_sql.c_str())); if (t == -1) { cout << "query failed:" << mysql_errno(&mysql) << mysql_error(&mysql) << endl; } else { res = mysql_store_result(&mysql); //返回查询的全部结果集 field = mysql_fetch_fields(res); while (row = mysql_fetch_row(res)) { //mysql_fetch_row取结果集的下一行 for (t = 0; t < mysql_num_fields(res); t++) { //结果集的列的数量 Mr[field[t].name] = Json::Value(row[t]); } } mysql_free_result(res); } //查询已有设备 int num = 0; int t2 = mysql_real_query(&mysql, fac_sql.c_str(), (unsigned int) strlen(fac_sql.c_str())); if (t2 == -1) { cout << "query failed:" << mysql_errno(&mysql) << mysql_error(&mysql) << endl; } else { res = mysql_store_result(&mysql); //返回查询的全部结果集 field = mysql_fetch_fields(res); while (row = mysql_fetch_row(res)) { //mysql_fetch_row取结果集的下一行 for (t = 0; t < mysql_num_fields(res); t++) { //结果集的列的数量 item[field[t].name] = Json::Value(row[t]); } arrayObj.append(item); item.clear(); num++; } Mr["Num"] = Json::Value(num); Mr["facility"] = Json::Value(arrayObj); } //查询可添加设备 int addNum = 0; int t1 = mysql_real_query(&mysql, add_fac_sql.c_str(), (unsigned int) strlen(add_fac_sql.c_str())); if (t1 == -1) { cout << "query failed:" << mysql_errno(&mysql) << mysql_error(&mysql) << endl; } else { res = mysql_store_result(&mysql); //返回查询的全部结果集 field = mysql_fetch_fields(res); while (row = mysql_fetch_row(res)) { //mysql_fetch_row取结果集的下一行 for (t = 0; t < mysql_num_fields(res); t++) { //结果集的列的数量 fac[field[t].name] = Json::Value(row[t]); } arrayAdd.append(fac); fac.clear(); addNum++; } Mr["addNum"] = Json::Value(addNum); Mr["addFacility"] = Json::Value(arrayAdd); } return Mr.toStyledString(); }
static int test_conversion(MYSQL *mysql) { MYSQL_STMT *stmt; const char *stmt_text; int rc; MYSQL_BIND my_bind[1]; uchar buff[4]; ulong length; stmt_text= "DROP TABLE IF EXISTS t1"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); stmt_text= "CREATE TABLE t1 (a TEXT) DEFAULT CHARSET latin1"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); stmt_text= "SET character_set_connection=utf8, character_set_client=utf8, " " character_set_results=latin1"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); stmt= mysql_stmt_init(mysql); FAIL_IF(!stmt, mysql_error(mysql)); stmt_text= "INSERT INTO t1 (a) VALUES (?)"; rc= mysql_stmt_prepare(stmt, SL(stmt_text)); check_stmt_rc(rc, stmt); memset(my_bind, '\0', sizeof(my_bind)); my_bind[0].buffer= (char*) buff; my_bind[0].length= &length; my_bind[0].buffer_type= MYSQL_TYPE_STRING; mysql_stmt_bind_param(stmt, my_bind); buff[0]= (uchar) 0xC3; buff[1]= (uchar) 0xA0; length= 2; rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); stmt_text= "SELECT a FROM t1"; rc= mysql_stmt_prepare(stmt, SL(stmt_text)); check_stmt_rc(rc, stmt); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); my_bind[0].buffer_length= sizeof(buff); mysql_stmt_bind_result(stmt, my_bind); rc= mysql_stmt_fetch(stmt); check_stmt_rc(rc, stmt); FAIL_UNLESS(length == 1, "length != 1"); FAIL_UNLESS(buff[0] == 0xE0, "buff[0] != 0xE0"); rc= mysql_stmt_fetch(stmt); FAIL_UNLESS(rc == MYSQL_NO_DATA, "rc != MYSQL_NO_DATA"); mysql_stmt_close(stmt); stmt_text= "DROP TABLE t1"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); stmt_text= "SET NAMES DEFAULT"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); return OK; }
static int test_ps_i18n(MYSQL *mysql) { MYSQL_STMT *stmt; int rc; const char *stmt_text; MYSQL_BIND bind_array[2]; /* Represented as numbers to keep UTF8 tools from clobbering them. */ const char *koi8= "\xee\xd5\x2c\x20\xda\xc1\x20\xd2\xd9\xc2\xc1\xcc\xcb\xd5"; const char *cp1251= "\xcd\xf3\x2c\x20\xe7\xe0\x20\xf0\xfb\xe1\xe0\xeb\xea\xf3"; char buf1[16], buf2[16]; ulong buf1_len, buf2_len; stmt_text= "DROP TABLE IF EXISTS t1"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); /* Create table with binary columns, set session character set to cp1251, client character set to koi8, and make sure that there is conversion on insert and no conversion on select */ stmt_text= "CREATE TABLE t1 (c1 VARBINARY(255), c2 VARBINARY(255))"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); stmt_text= "SET CHARACTER_SET_CLIENT=koi8r, " "CHARACTER_SET_CONNECTION=cp1251, " "CHARACTER_SET_RESULTS=koi8r"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); memset(bind_array, '\0', sizeof(bind_array)); bind_array[0].buffer_type= MYSQL_TYPE_STRING; bind_array[0].buffer= (void *) koi8; bind_array[0].buffer_length= (unsigned long)strlen(koi8); bind_array[1].buffer_type= MYSQL_TYPE_STRING; bind_array[1].buffer= (void *) koi8; bind_array[1].buffer_length= (unsigned long)strlen(koi8); stmt= mysql_stmt_init(mysql); check_stmt_rc(rc, stmt); stmt_text= "INSERT INTO t1 (c1, c2) VALUES (?, ?)"; rc= mysql_stmt_prepare(stmt, SL(stmt_text)); check_stmt_rc(rc, stmt); mysql_stmt_bind_param(stmt, bind_array); check_stmt_rc(rc, stmt); // mysql_stmt_send_long_data(stmt, 0, koi8, strlen(koi8)); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); stmt_text= "SELECT c1, c2 FROM t1"; /* c1 and c2 are binary so no conversion will be done on select */ rc= mysql_stmt_prepare(stmt, SL(stmt_text)); check_stmt_rc(rc, stmt); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); bind_array[0].buffer= buf1; bind_array[0].buffer_length= sizeof(buf1); bind_array[0].length= &buf1_len; bind_array[1].buffer= buf2; bind_array[1].buffer_length= sizeof(buf2); bind_array[1].length= &buf2_len; mysql_stmt_bind_result(stmt, bind_array); rc= mysql_stmt_fetch(stmt); check_stmt_rc(rc, stmt); FAIL_UNLESS(buf1_len == strlen(cp1251), "buf1_len != strlen(cp1251)"); FAIL_UNLESS(buf2_len == strlen(cp1251), "buf2_len != strlen(cp1251)"); FAIL_UNLESS(!memcmp(buf1, cp1251, buf1_len), "buf1 != cp1251"); FAIL_UNLESS(!memcmp(buf2, cp1251, buf1_len), "buf2 != cp1251"); rc= mysql_stmt_fetch(stmt); FAIL_UNLESS(rc == MYSQL_NO_DATA, "rc != MYSQL_NO_DATA"); stmt_text= "DROP TABLE IF EXISTS t1"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); /* Now create table with two cp1251 columns, set client character set to koi8 and supply columns of one row as string and another as binary data. Binary data must not be converted on insert, and both columns must be converted to client character set on select. */ stmt_text= "CREATE TABLE t1 (c1 VARCHAR(255) CHARACTER SET cp1251, " "c2 VARCHAR(255) CHARACTER SET cp1251)"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); stmt_text= "INSERT INTO t1 (c1, c2) VALUES (?, ?)"; rc= mysql_stmt_prepare(stmt, SL(stmt_text)); check_stmt_rc(rc, stmt); /* this data must be converted */ bind_array[0].buffer_type= MYSQL_TYPE_STRING; bind_array[0].buffer= (void *) koi8; bind_array[0].buffer_length= (unsigned long)strlen(koi8); bind_array[1].buffer_type= MYSQL_TYPE_STRING; bind_array[1].buffer= (void *) koi8; bind_array[1].buffer_length= (unsigned long)strlen(koi8); mysql_stmt_bind_param(stmt, bind_array); // mysql_stmt_send_long_data(stmt, 0, koi8, strlen(koi8)); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); /* this data must not be converted */ bind_array[0].buffer_type= MYSQL_TYPE_BLOB; bind_array[0].buffer= (void *) cp1251; bind_array[0].buffer_length= (unsigned long)strlen(cp1251); bind_array[1].buffer_type= MYSQL_TYPE_BLOB; bind_array[1].buffer= (void *) cp1251; bind_array[1].buffer_length= (unsigned long)strlen(cp1251); mysql_stmt_bind_param(stmt, bind_array); // mysql_stmt_send_long_data(stmt, 0, cp1251, strlen(cp1251)); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); /* Fetch data and verify that rows are in koi8 */ stmt_text= "SELECT c1, c2 FROM t1"; /* c1 and c2 are binary so no conversion will be done on select */ rc= mysql_stmt_prepare(stmt, SL(stmt_text)); check_stmt_rc(rc, stmt); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); bind_array[0].buffer= buf1; bind_array[0].buffer_length= sizeof(buf1); bind_array[0].length= &buf1_len; bind_array[1].buffer= buf2; bind_array[1].buffer_length= sizeof(buf2); bind_array[1].length= &buf2_len; mysql_stmt_bind_result(stmt, bind_array); while ((rc= mysql_stmt_fetch(stmt)) == 0) { FAIL_UNLESS(buf1_len == strlen(koi8), "buf1_len != strlen(koi8)"); FAIL_UNLESS(buf2_len == strlen(koi8), "buf2_len != strlen(koi8)"); FAIL_UNLESS(!memcmp(buf1, koi8, buf1_len), "buf1 != koi8"); FAIL_UNLESS(!memcmp(buf2, koi8, buf1_len), "buf2 != koi8"); } FAIL_UNLESS(rc == MYSQL_NO_DATA, "rc != MYSQL_NO_DATA"); mysql_stmt_close(stmt); stmt_text= "DROP TABLE t1"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); stmt_text= "SET NAMES DEFAULT"; rc= mysql_real_query(mysql, SL(stmt_text)); check_mysql_rc(rc, mysql); return OK; }
/* * Load a zone from the db server. If need be, update an * existing zone. This is the start of the real sql code. */ int update_zone_mysql(struct sql_rec_head *rec_head){ MYSQL_RES *sql_res; MYSQL_ROW sql_row; char q1[]="select sqlOrigin,sqlOwner,sqlClass,sqlType,sqlData,sqlTTL,sqlPref,sqlID,unix_timestamp(sqlTime) from"; char q2[]="order by sqlID"; char sql_query[255]; struct SQL_REC tmp_sql_rec; ns_updrec *cur_ns_rec, *tmp_ns_rec; /* build up the query string for the zone */ sprintf(sql_query, "%s %s %s", q1, fixname(rec_head->dbzone), q2); /* * Connect to the db and query it. * Complain about any errors and return. */ if(db_connect(rec_head)){ warning(LOG_DB, "Error connecting to db server\n"); } /* Query the db. Complain on error. */ if(mysql_real_query(&rec_head->sql_sock, sql_query, strlen(sql_query)) < 0 || !(sql_res=mysql_store_result(&rec_head->sql_sock))){ warning(LOG_DB, "Query failed\n"); return 1; } while (sql_row=mysql_fetch_row(sql_res)) { tmp_sql_rec.sqlType = savestr(sql_row[3], 1); /* don't mess with soa's just yet */ if(strcmp(tmp_sql_rec.sqlType, "SOA")!=0){ tmp_sql_rec.sqlOrigin = savestr(sql_row[0], 1); tmp_sql_rec.sqlOwner = savestr(sql_row[1], 1); tmp_sql_rec.sqlClass = savestr(sql_row[2], 1); tmp_sql_rec.sqlData = savestr(sql_row[4], 1); tmp_sql_rec.sqlTTL = atoi(sql_row[5]); tmp_sql_rec.sqlPref = savestr(sql_row[6], 1); tmp_sql_rec.sqlID = atoi(sql_row[7]); tmp_sql_rec.sqlTime = atoi(sql_row[8]); /* start looping through the linked list to place the record */ if(rec_head->r_head == NULL){ rec_head->r_head=(ns_updrec *)new_rec(tmp_sql_rec, ADD); }else{ for(cur_ns_rec=rec_head->r_head;cur_ns_rec!=NULL;cur_ns_rec=cur_ns_rec->r_next){ /* Handle deletes and adding new records */ if(cur_ns_rec->r_next!=NULL){ if(need_del_rec(cur_ns_rec->r_next, tmp_sql_rec)){ /* put in the delete record */ tmp_ns_rec=cur_ns_rec->r_next->r_next; cur_ns_rec->r_next->r_ttl=0; cur_ns_rec->r_next->r_opcode=0; cur_ns_rec->r_next->r_next=(ns_updrec *)new_rec(tmp_sql_rec, ADD); cur_ns_rec->r_next->r_next->r_next=tmp_ns_rec; break; } }else{ if(!rec_exists(rec_head->r_head, tmp_sql_rec)) cur_ns_rec->r_next=(ns_updrec *)new_rec(tmp_sql_rec, ADD); break; } } /* close the for loop used to place records */ } /* close the null head if test */ } /* close the soa if test */ } /* close the while that loops through records */ /* Clean up after our self */ mysql_free_result(sql_res); return 0; }
bool CMySql::query(const char *q){ bool r = mysql_real_query(conn, q, strlen(q)); if(!r){ result = mysql_store_result(conn); set_assoc();} return !r; }
static HB_ERRCODE mysqlOpen( SQLBASEAREAP pArea ) { MYSQL * pMySql = ( ( SDDCONN * ) pArea->pConnection->pSDDConn )->pMySql; SDDDATA * pSDDData; PHB_ITEM pItemEof, pItem; HB_ULONG ulIndex; HB_USHORT uiFields, uiCount; HB_ERRCODE errCode = 0; HB_BOOL bError; DBFIELDINFO pFieldInfo; MYSQL_FIELD * pMyField; void ** pRow; pArea->pSDDData = memset( hb_xgrab( sizeof( SDDDATA ) ), 0, sizeof( SDDDATA ) ); pSDDData = ( SDDDATA * ) pArea->pSDDData; if( mysql_real_query( pMySql, pArea->szQuery, ( unsigned long ) strlen( pArea->szQuery ) ) ) { hb_errRT_MySQLDD( EG_OPEN, ESQLDD_INVALIDQUERY, ( const char * ) mysql_error( pMySql ), pArea->szQuery, mysql_errno( pMySql ) ); return HB_FAILURE; } if( ( pSDDData->pResult = mysql_store_result( pMySql ) ) == NULL ) { hb_errRT_MySQLDD( EG_MEM, ESQLDD_INVALIDQUERY, ( const char * ) mysql_error( pMySql ), pArea->szQuery, mysql_errno( pMySql ) ); return HB_FAILURE; } uiFields = ( HB_USHORT ) mysql_num_fields( pSDDData->pResult ); SELF_SETFIELDEXTENT( ( AREAP ) pArea, uiFields ); pItemEof = hb_itemArrayNew( uiFields ); bError = HB_FALSE; for( uiCount = 0; uiCount < uiFields; uiCount++ ) { pMyField = mysql_fetch_field_direct( pSDDData->pResult, uiCount ); pFieldInfo.atomName = pMyField->name; pFieldInfo.uiLen = ( HB_USHORT ) pMyField->length; pFieldInfo.uiDec = 0; switch( pMyField->type ) { case MYSQL_TYPE_TINY: case MYSQL_TYPE_SHORT: pFieldInfo.uiType = HB_FT_INTEGER; break; case MYSQL_TYPE_LONG: case MYSQL_TYPE_LONGLONG: case MYSQL_TYPE_INT24: pFieldInfo.uiType = HB_FT_LONG; break; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: pFieldInfo.uiType = HB_FT_DOUBLE; pFieldInfo.uiDec = ( HB_USHORT ) pMyField->decimals; break; case MYSQL_TYPE_STRING: case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_ENUM: pFieldInfo.uiType = HB_FT_STRING; break; case MYSQL_TYPE_DATE: pFieldInfo.uiType = HB_FT_DATE; break; case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: pFieldInfo.uiType = HB_FT_MEMO; break; case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATETIME: pFieldInfo.uiType = HB_FT_TIMESTAMP; pFieldInfo.uiLen = 8; break; case MYSQL_TYPE_TIME: pFieldInfo.uiType = HB_FT_TIME; pFieldInfo.uiLen = 4; break; /* case MYSQL_TYPE_YEAR: case MYSQL_TYPE_NEWDATE: case MYSQL_TYPE_ENUM: case MYSQL_TYPE_SET: */ default: bError = HB_TRUE; errCode = ( HB_ERRCODE ) pMyField->type; pFieldInfo.uiType = 0; break; } if( ! bError ) { switch( pFieldInfo.uiType ) { case HB_FT_STRING: { char * pStr; pStr = ( char * ) hb_xgrab( pFieldInfo.uiLen + 1 ); memset( pStr, ' ', pFieldInfo.uiLen ); pStr[ pFieldInfo.uiLen ] = '\0'; pItem = hb_itemPutCL( NULL, pStr, pFieldInfo.uiLen ); hb_xfree( pStr ); break; } case HB_FT_MEMO: pItem = hb_itemPutC( NULL, NULL ); break; case HB_FT_INTEGER: pItem = hb_itemPutNI( NULL, 0 ); break; case HB_FT_LONG: pItem = hb_itemPutNL( NULL, 0 ); break; case HB_FT_DOUBLE: pItem = hb_itemPutND( NULL, 0.0 ); break; case HB_FT_DATE: pItem = hb_itemPutDS( NULL, NULL ); break; case HB_FT_TIMESTAMP: case HB_FT_TIME: pItem = hb_itemPutTDT( NULL, 0, 0 ); break; default: pItem = hb_itemNew( NULL ); bError = HB_TRUE; break; } hb_arraySetForward( pItemEof, uiCount + 1, pItem ); hb_itemRelease( pItem ); /* if( pFieldInfo.uiType == HB_IT_DOUBLE || pFieldInfo.uiType == HB_IT_INTEGER ) pFieldInfo.uiType = HB_IT_LONG; */ if( ! bError ) bError = ( SELF_ADDFIELD( ( AREAP ) pArea, &pFieldInfo ) == HB_FAILURE ); } if( bError ) break; } if( bError ) { hb_itemRelease( pItemEof ); hb_errRT_MySQLDD( EG_CORRUPTION, ESQLDD_INVALIDFIELD, "Invalid field type", pArea->szQuery, errCode ); return HB_FAILURE; } pArea->ulRecCount = ( HB_ULONG ) mysql_num_rows( pSDDData->pResult ); pArea->pRow = ( void ** ) hb_xgrab( ( pArea->ulRecCount + 1 ) * sizeof( void * ) ); pArea->pRowFlags = ( HB_BYTE * ) hb_xgrab( ( pArea->ulRecCount + 1 ) * sizeof( HB_BYTE ) ); memset( pArea->pRowFlags, 0, ( pArea->ulRecCount + 1 ) * sizeof( HB_BYTE ) ); pArea->ulRecMax = pArea->ulRecCount + 1; pRow = pArea->pRow; *pRow = pItemEof; pArea->pRowFlags[ 0 ] = SQLDD_FLAG_CACHED; pRow++; for( ulIndex = 1; ulIndex <= pArea->ulRecCount; ulIndex++ ) { *pRow++ = ( void * ) mysql_row_tell( pSDDData->pResult ); mysql_fetch_row( pSDDData->pResult ); } pArea->fFetched = HB_TRUE; return HB_SUCCESS; }
char * getcoop(in_addr_t host, char *attr) { struct hostent *hostp; struct in_addr in; int i; char *value = NULL; char *ip; #ifdef WITH_MYSQL MYSQL_ROW row; MYSQL mysql; MYSQL_RES *result; char query[1024];; int mysql_ready; #endif /* * most likely the coop value has already been recorded in the * downloads table */ if (dt_table != NULL) { for (i = 0 ; i < dt_table->size ; ++i) { if ((dt_table->entry[i].host == host) && (dt_table->entry[i].coop != NULL)) { value = strdup(dt_table->entry[i].coop); #ifdef DEBUG fprintf(stderr, "getcoop: found cached value %s\n", value); #endif return(value); } } } in.s_addr = host; ip = inet_ntoa(in); #ifdef WITH_MYSQL if ((value = gethostattr(ip, attr)) != NULL) { return(value); } mysql_ready = 0; if (mysql_init(&mysql) != NULL) { if (mysql_options(&mysql, MYSQL_READ_DEFAULT_FILE, "/opt/rocks/etc/my.cnf") == 0) { if (mysql_real_connect(&mysql, "localhost", "apache", NULL, "cluster", 0, NULL, 0) != NULL) { mysql_ready = 1; } } } if (mysql_ready) { /* * try to return the rack number for this host */ sprintf(query, "select n.rack from nodes n, networks net where \ net.ip = '%s' and net.node = n.id", ip); if (mysql_real_query(&mysql, query, strlen(query)) != 0) { fprintf(stderr, "gethostattr:mysql_real_query:failed: %s\n", mysql_error(&mysql)); } if ((result = mysql_store_result(&mysql)) == NULL) { fprintf(stderr, "gethostattr:mysql_store_result:failed: %s\n", mysql_error(&mysql)); } if ((row = mysql_fetch_row(result)) != NULL) { value = strdup(row[0]); } mysql_free_result(result); mysql_close(&mysql); if (value != NULL) { return(value); } } #endif /* * the last resort - try to parse the host name */ hostp = gethostbyaddr(&in, sizeof(in), AF_INET); if (hostp != NULL) { int i; char name[128], rack[16], rank[16]; char *ptr; /* * convert the last 2 '-' characters into blanks */ for (i = 0 ; i < 2 ; ++i) { ptr = strrchr(hostp->h_name, '-'); if (ptr != NULL) { *ptr = ' '; } else { /* * this host name is not standard form */ return(NULL); } } sscanf(hostp->h_name, "%s %s %s.local", name, rack, rank); value = strdup(rack); } return(value); }
int mysql_drv_describe(drv_caps_t *caps, const char * table_name) { db_conn_t con; char query[1024]; MYSQL_RES *res = NULL; MYSQL_ROW row; MYSQL_FIELD *fields; unsigned int num_fields; unsigned int i; int connected = 0; int rc = 0; *caps = mysql_drv_caps; if (table_name == NULL) goto exit; /* Try to determine table type */ if (mysql_drv_connect(&con)) goto error; /* Fix the hosts list */ hosts_pos = args.hosts; connected = 1; snprintf(query, sizeof(query), "SHOW TABLE STATUS LIKE '%s'", table_name); rc = mysql_real_query(con.ptr, query, strlen(query)); DEBUG("mysql_real_query(%p, \"%s\", %d) = %d", con.ptr, query, strlen(query), rc); if (rc) goto error; res = mysql_store_result(con.ptr); DEBUG("mysql_store_result(%p) = %p", con.ptr, res); if (res == NULL) goto error; num_fields = mysql_num_fields(res); DEBUG("mysql_num_fields(%p) = %d", res, num_fields); fields = mysql_fetch_fields(res); DEBUG("mysql_fetch_fields(%p) = %p", res, fields); for (i = 0; i < num_fields; i++) if (!strcasecmp(fields[i].name, "type") || !strcasecmp(fields[i].name, "engine")) break; if (i >= num_fields) goto error; row = mysql_fetch_row(res); DEBUG("mysql_fetch_row(%p) = %p", res, row); if (row == NULL || row[i] == NULL) goto error; rc = parse_table_engine(row[i]); *caps = mysql_drv_caps; goto exit; error: log_text(LOG_ALERT, "Error: failed to determine table '%s' type!", table_name); log_text(LOG_ALERT, "MySQL error: %s", mysql_error(con.ptr)); rc = 1; exit: if (res != NULL) { mysql_free_result(res); DEBUG("mysql_free_result(%p)", res); } if (connected) mysql_drv_disconnect(&con); return rc; }
int PlatDbConn::exec_multi_query(const char* sql, vector<MYSQL_RES*> & result_set_list) { if(conn_flag_ == 0) { int ret = connect(); if(ret != 0) { return ret; } } if (mysql_real_query(&mysql_, sql, strlen(sql)) != 0) { snprintf(err_msg_, sizeof(err_msg_), "PlatDbConn mysql_real_query failed:%d,%s", mysql_errno(&mysql_), mysql_error(&mysql_)); //svr gone or lost connection if(CR_SERVER_GONE_ERROR==mysql_errno(&mysql_) || CR_SERVER_LOST==mysql_errno(&mysql_) ) { disconnect(); //清理,便于下次重连 return -1; } return mysql_errno(&mysql_); } int keep_going = 1; do { MYSQL_RES* result_set = mysql_store_result(&mysql_); if(result_set==NULL) { snprintf(err_msg_, sizeof(err_msg_), "PlatDbConn mysql_store_result failed:%d,%s", mysql_errno(&mysql_), mysql_error(&mysql_)); //svr gone or lost connection if(CR_SERVER_GONE_ERROR==mysql_errno(&mysql_) || CR_SERVER_LOST==mysql_errno(&mysql_) ) { disconnect(); //清理,便于下次重连 return -1; } return mysql_errno(&mysql_); } else { result_set_list.push_back(result_set); } int status = mysql_next_result(&mysql_); if(status !=0) { keep_going = 0; if(status>0) { snprintf(err_msg_, sizeof(err_msg_), "PlatDbConn mysql_store_result failed:%d,%s", mysql_errno(&mysql_), mysql_error(&mysql_)); } } }while(keep_going); return 0; }
/* * function: format3 * * export flows into MySQL Database */ int format3(struct ftio *ftio, struct options *opt) { #ifdef HAVE_MYSQL struct fts3rec_offsets fo; struct ftver ftv; char fields[1024], values[1024], query[3*1024]; char *rec; char *db_host, *db_name, *db_table, *db_user, *db_pwd, *db_tmp, *tmp; int db_port; int len; MYSQL mysql; db_host = MYSQL_DEFAULT_DBHOST; db_name = MYSQL_DEFAULT_DBNAME; db_port = MYSQL_DEFAULT_DBPORT; db_user = MYSQL_DEFAULT_DBUSER; db_table = MYSQL_DEFAULT_DBTABLE; db_pwd = MYSQL_DEFAULT_DBPWD; /* parse URI string */ if (strlen(opt->dbaseURI)) { tmp = opt->dbaseURI; db_user = strsep(&tmp, ":"); db_pwd = strsep(&tmp, ":"); db_host = strsep(&tmp, ":"); db_tmp = strsep(&tmp, ":"); db_name = strsep(&tmp, ":"); db_table = strsep(&tmp, ":"); db_port = atoi(db_tmp); if (!db_user || !db_pwd || !db_host || !db_tmp || !db_name || !db_table) { fterr_warnx("Missing field in dbaseURI, expecting user:pwd:host:port:name:table."); return -1; } } /* dbaseURI */ ftio_get_ver(ftio, &ftv); fts3rec_compute_offsets(&fo, &ftv); /* remove invalid fields */ opt->ft_mask &= ftrec_xfield(&ftv); /* generate the field names once */ fmt_xfields_type(fields, opt->ft_mask); /* open MySQL database */ if (!(mysql_init(&mysql))) fterr_errx(1, "mysql_init(): failed"); if (mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, "simple")) fterr_errx(1, "mysql_options(): %s", mysql_error(&mysql)); if (mysql_real_connect(&mysql, db_host, db_user, db_pwd, db_name, db_port, NULL, 0) == NULL) fterr_errx(1,"mysql_real_connect(): %s\n", mysql_error(&mysql)); /* foreach flow */ while ((rec = ftio_read(ftio))) { len = fmt_xfields_val(values, rec, &fo, opt->ft_mask, 1); /* form SQL query and execute it */ if (len) { strcpy (query, "INSERT INTO "); strcat (query, db_table); strcat (query, "("); strcat (query, fields); strcat (query, ") VALUES ("); strcat (query, values); strcat (query, ")"); if (debug) fprintf(stderr, "field=%s\n val=%s\n query=%s\n", fields, values, query); if (mysql_real_query(&mysql, query, strlen(query)) != 0) fterr_warnx("mysql_real_query(): %s", mysql_error(&mysql)); } ++opt->records; } /* while */ /* close database */ mysql_close(&mysql); #else /* MYSQL */ fterr_warnx("Format not supported"); #endif /* MYSQL */ return 0; } /* format3 */
MYSQL_RES *KDBTools::CreateRecordSet( const char cszTableName[], const FIELD_NAME_VECTOR &crFieldNameVector, const FIELD_ID_VECTOR &crOrderByFields, const bool bHasCondition, const char cszSearchFieldName[], const char cszSearchThing[] ) { int nResult = false; int nRetCode = false; MYSQL_RES *pRetRecordSet = NULL; string strQuery; unsigned uTableFieldCount = 0; //unsigned uOrderByFieldCount = 0; //unsigned uFieldID = 0; KGLOG_PROCESS_ERROR(cszTableName); KGLOG_PROCESS_ERROR(cszTableName[0]); uTableFieldCount = (unsigned)crFieldNameVector.size(); KGLOG_PROCESS_ERROR(uTableFieldCount); strQuery = "select"; for (unsigned i = 0; i < uTableFieldCount; i++) { if (i > 0) strQuery += ","; strQuery += " `"; strQuery += crFieldNameVector[i]; strQuery += "`"; } strQuery += " from `"; strQuery += cszTableName; strQuery += "`"; if (bHasCondition) { strQuery += " where "; strQuery += cszSearchFieldName; strQuery += " = \""; strQuery += cszSearchThing; strQuery += "\""; } //// crOrderByFields is empty indicate the record set not order by any fields. //uOrderByFieldCount = (unsigned)crOrderByFields.size(); //if (uOrderByFieldCount > 0) //{ // strQuery += " order by"; // for (unsigned i = 0; i < uOrderByFieldCount; i++) // { // uFieldID = crOrderByFields[i]; // KGLOG_PROCESS_ERROR(uFieldID < uTableFieldCount); // if (i > 0) // strQuery += ","; // strQuery += " `"; // strQuery += crFieldNameVector[uFieldID]; // strQuery += "`"; // } //} ASSERT(m_pDBHandle); nRetCode = mysql_real_query( m_pDBHandle, strQuery.c_str(), (unsigned long)strQuery.length() ); KGD_MYSQL_PROCESS_ERROR(nRetCode == 0, m_pDBHandle, strQuery.c_str()); pRetRecordSet = mysql_use_result(m_pDBHandle); KGD_MYSQL_PROCESS_ERROR(pRetRecordSet, m_pDBHandle, "mysql_use_result()"); nResult = true; Exit0: if (!nResult) { if (pRetRecordSet) { mysql_free_result(pRetRecordSet); pRetRecordSet = NULL; } } return pRetRecordSet; }
int DBAccess::nUpdate(char *szSQL) { int nRtn = 0; for(int index=0; index<m_connectcount; index++) { if(index >= m_connectcount) { LOG (LOG_ERROR,"Error, all of the mysql connection lost![%d]", m_connectcount); return -1; } m_Index++; if(m_Index >= m_connectcount) m_Index = 0; if(m_MYSQL_BB[m_Index].m_nIsConnect != 1) { continue; } //释放上次请求内容 if(m_MYSQL_BB[m_Index].m_res != NULL) { mysql_free_result(m_MYSQL_BB[m_Index].m_res); m_MYSQL_BB[m_Index].m_res = NULL; } nRtn = mysql_real_query(&m_MYSQL_BB[m_Index].m_mysql,szSQL,strlen(szSQL)); if(nRtn == 0) { return 0; } else { LOG (LOG_ERROR,"mysql_real_query[%s] return %d, errno=%d,%s", szSQL, nRtn, mysql_errno(&m_MYSQL_BB[m_Index].m_mysql), mysql_error(&m_MYSQL_BB[m_Index].m_mysql)); if(!mysql_ping(&m_MYSQL_BB[m_Index].m_mysql)) { LOG (LOG_ERROR,"mysql_ping error! reconnect!"); if(NULL == mysql_real_connect(&m_MYSQL_BB[m_Index].m_mysql,m_szHostIP,m_szUserName,m_szPasswd,m_szDefDBName,0,NULL,0)) { LOG (LOG_ERROR,"mysql_real_connect return NULL, errno=%d,%s", mysql_errno(&m_MYSQL_BB[m_Index].m_mysql), mysql_error(&m_MYSQL_BB[m_Index].m_mysql)); m_MYSQL_BB[m_Index].m_nIsConnect = 0; } else { LOG (LOG_DEBUG,"mysql_real_connect[%d] success!", m_Index); m_MYSQL_BB[m_Index].m_nIsConnect = 1; } continue; } else { continue; } } } return -1; }
void createNews(void) { xmlDocPtr doc; xmlNodePtr seekPtr, parentPtr; xmlChar *mediaTitle, *season; char *filePath, *SQLexec=NULL; MYSQL_ROW idrow; MYSQL_RES *idres; int seas_check; printf ("\nGenerating new movies...\n"); filePath=(char*)malloc(sizeof(char)* (strlen(input_dir)+strlen(yamj_newmovies)+2 ) ); sprintf (filePath, "%s/%s", input_dir, yamj_newmovies); if ((doc = xmlParseFile(filePath)) != NULL) { parentPtr = doc->children; if ( (seekPtr = getChildNodeByName(parentPtr, "movies")) != NULL ) { parentPtr = seekPtr->children; while (parentPtr) { if (parentPtr->type == XML_ELEMENT_NODE) { if ( strcasecmp((char*)parentPtr->name, "movie") == 0 ) { if ( (seekPtr = getChildNodeByName(parentPtr, "title")) != NULL ) { if ( (mediaTitle = xmlNodeGetContent(seekPtr)) != NULL ) { SQLexec = (char*)malloc(sizeof(char)* (strlen(db_FIND_MOVIENEWS) + strlen(db_movietable) + strlen((char*)mediaTitle) +2 )); sprintf (SQLexec, db_FIND_MOVIENEWS, db_movietable, mediaTitle); if (mysql_real_query(mysql_conn, SQLexec, strlen(SQLexec)) == 0) { if ( (idres = mysql_store_result(mysql_conn)) != NULL ) { idrow = mysql_fetch_row(idres); free (SQLexec); SQLexec = (char*)malloc(sizeof(char) * (strlen(db_INSERT_MOVIENEWS) + strlen(idrow[0])+2)); sprintf (SQLexec, db_INSERT_MOVIENEWS, db_newstable, idrow[0]); if ( mysql_real_query (mysql_conn, SQLexec, strlen(SQLexec)) != 0) fprintf (stderr, "Error while storing newmovies into newstable\n"); mysql_free_result(idres); } } } } } } parentPtr = parentPtr->next; } } xmlFreeDoc(doc); } free (filePath); printf ("Generating new tv...\n"); filePath=(char*)malloc(sizeof(char)* (strlen(input_dir)+strlen(yamj_newtv)+2 ) ); sprintf (filePath, "%s/%s", input_dir, yamj_newtv); if ((doc = xmlParseFile(filePath)) != NULL) { parentPtr = doc->children; if ( (seekPtr = getChildNodeByName(parentPtr, "movies")) != NULL ) { parentPtr = seekPtr->children; while (parentPtr) { if (parentPtr->type == XML_ELEMENT_NODE) { if ( !strcasecmp((char*)parentPtr->name, "movie") && parentPtr->name ) { if ( (seekPtr = getChildNodeByName(parentPtr, "title")) != NULL ) { if ( (mediaTitle = xmlNodeGetContent(seekPtr)) != NULL ) { if ( (seekPtr = getChildNodeByName(parentPtr, "season")) != NULL ) { if ( (season = xmlNodeGetContent(seekPtr)) != NULL ) { seas_check = atoi ((char*)season); if (seas_check < 1) { fprintf (stderr, "WARNING:%s(season) < 1, seeking in DB for ID.\n", (char*)mediaTitle); SQLexec = (char*)malloc( sizeof(char)*( strlen(db_FIND_TVNEWS_FAILED)+strlen(db_movietable)+strlen((char*)mediaTitle) ) ); sprintf (SQLexec, db_FIND_TVNEWS_FAILED, db_tvtable, mediaTitle); } else { SQLexec = (char*)malloc(sizeof(char)* (strlen(db_FIND_TVNEWS) + strlen(db_movietable) + strlen((char*)mediaTitle) + strlen((char*)season)+2 )); sprintf (SQLexec, db_FIND_TVNEWS, db_tvtable, mediaTitle, season); } if (mysql_real_query(mysql_conn, SQLexec, strlen(SQLexec)) == 0) { if ( (idres = mysql_store_result(mysql_conn)) != NULL ) { idrow = mysql_fetch_row(idres); if (SQLexec) free (SQLexec); SQLexec = (char*)malloc(sizeof(char) * (strlen(db_INSERT_TVNEWS) + strlen(idrow[0])+2)); sprintf (SQLexec, db_INSERT_TVNEWS, db_newstable, idrow[0]); if ( mysql_real_query (mysql_conn, SQLexec, strlen(SQLexec)) != 0) fprintf (stderr, "Error while storing newmovies into newstable\n"); mysql_free_result(idres); } } } } } } } } parentPtr = parentPtr->next; } } xmlFreeDoc(doc); } free (filePath); }
char * gethostattr(char *ip, char *attr) { MYSQL_ROW row; MYSQL mysql; MYSQL_RES *result; char query[1024];; char *value = NULL; if (mysql_init(&mysql) == NULL) { fprintf(stderr, "gethostattr:mysql_init:failed: errno %d\n", errno); return(NULL); } if (mysql_options(&mysql, MYSQL_READ_DEFAULT_FILE, "/opt/rocks/etc/my.cnf") != 0) { fprintf(stderr, "gethostattr:mysql_options:failed: %s\n", mysql_error(&mysql)); return(NULL); } if (mysql_real_connect(&mysql, "localhost", "apache", NULL, "cluster", 0, NULL, 0) == NULL) { fprintf(stderr, "gethostattr:mysql_real_connect:failed: %s\n", mysql_error(&mysql)); return(NULL); } /* * first see if there is a host attribute */ sprintf(query, "select a.value from node_attributes a, nodes n, \ networks net where net.ip = '%s' and net.name = n.name and \ n.id = a.node and a.attr = '%s'", ip, attr); if (mysql_real_query(&mysql, query, strlen(query)) != 0) { fprintf(stderr, "gethostattr:mysql_real_query:failed: %s\n", mysql_error(&mysql)); } if ((result = mysql_store_result(&mysql)) == NULL) { fprintf(stderr, "gethostattr:mysql_store_result:failed: %s\n", mysql_error(&mysql)); } if ((row = mysql_fetch_row(result)) != NULL) { value = strdup(row[0]); } mysql_free_result(result); if (value != NULL) { mysql_close(&mysql); return(value); } /* * there is no host attribute, see if there is an appliance attribute */ sprintf(query, "select a.value from appliance_attributes a, \ nodes n, networks net, memberships m, appliances app \ where net.ip = '%s' and net.name = n.name and \ n.membership = m.id and m.appliance = app.id and \ a.appliance = app.id and a.attr = '%s'", ip, attr); if (mysql_real_query(&mysql, query, strlen(query)) != 0) { fprintf(stderr, "gethostattr:mysql_real_query:failed: %s\n", mysql_error(&mysql)); } if ((result = mysql_store_result(&mysql)) == NULL) { fprintf(stderr, "gethostattr:mysql_store_result:failed: %s\n", mysql_error(&mysql)); } if ((row = mysql_fetch_row(result)) != NULL) { value = strdup(row[0]); } mysql_free_result(result); if (value != NULL) { mysql_close(&mysql); return(value); } /* * there is no host and no appliance attribute, see if there is an * OS attribute */ sprintf(query, "select a.value from os_attributes a, nodes n, \ networks net where net.ip = '%s' and net.name = n.name and \ a.os = n.os and a.attr = '%s'", ip, attr); if (mysql_real_query(&mysql, query, strlen(query)) != 0) { fprintf(stderr, "gethostattr:mysql_real_query:failed: %s\n", mysql_error(&mysql)); } if ((result = mysql_store_result(&mysql)) == NULL) { fprintf(stderr, "gethostattr:mysql_store_result:failed: %s\n", mysql_error(&mysql)); } if ((row = mysql_fetch_row(result)) != NULL) { value = strdup(row[0]); } mysql_free_result(result); if (value != NULL) { mysql_close(&mysql); return(value); } /* * there is no host, no appliance and no OS attribute, see * if there is a global attribute */ sprintf(query, "select value from global_attributes where attr = '%s'", attr); if (mysql_real_query(&mysql, query, strlen(query)) != 0) { fprintf(stderr, "gethostattr:mysql_real_query:failed: %s\n", mysql_error(&mysql)); } if ((result = mysql_store_result(&mysql)) == NULL) { fprintf(stderr, "gethostattr:mysql_store_result:failed: %s\n", mysql_error(&mysql)); } if ((row = mysql_fetch_row(result)) != NULL) { value = strdup(row[0]); } mysql_free_result(result); mysql_close(&mysql); return(value); }
/* create table `toplog` ( `id` int unsigned NOT NULL auto_increment, `userid` char(15) NOT NULL default '', `bname` char(31) NOT NULL default '', `title` char(81) NOT NULL default '', `time` timestamp NOT NULL, `date` date NOT NULL, `topth` int NOT NULL default '1', `count` int NOT NULL default '0', `threadid` int unsigned NOT NULL default '0', PRIMARY KEY (`id`), KEY userid (`userid`), KEY bname(`bname`, `threadid`), KEY date(`date`), UNIQUE top (`date`,`topth`) ) TYPE=MyISAM COMMENT='toplog'; create table `toplog_all` ( `id` int unsigned NOT NULL auto_increment, `userid` char(15) NOT NULL default '', `bname` char(31) NOT NULL default '', `title` char(81) NOT NULL default '', `time` timestamp NOT NULL, `date` date NOT NULL, `topth` int NOT NULL default '1', `count` int NOT NULL default '0', `threadid` int unsigned NOT NULL default '0', PRIMARY KEY (`id`), KEY userid (`userid`), KEY bname(`bname`, `threadid`), KEY date(`date`), ) TYPE=MyISAM COMMENT='toplog_all'; */ int log_top() { MYSQL s; char sqlbuf[500]; char newtitle[161]; int i; char newts[20]; time_t now; struct tm ptime; mysql_init(&s); if (! my_connect_mysql(&s)) { return 0;; } for (i=0;i<topnum;i++) { mysql_escape_string(newtitle, top[i].title, strlen(top[i].title)); #ifdef NEWSMTH MYSQL_RES *res; MYSQL_ROW row; sprintf(sqlbuf, "SELECT id FROM toplog_all WHERE date=CURDATE() AND bname='%s' AND threadid=%d; ", top[i].board, top[i].groupid); if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) { printf("%s\n", mysql_error(&s)); } else { res = mysql_store_result(&s); row = mysql_fetch_row(res); if (row==NULL) { char title[STRLEN],file[STRLEN]; // auto post top10 to ShiDa sprintf(title, "[%s] %s", top[i].board,top[i].title); sprintf(file, "boards/%s/%s", top[i].board,top[i].filename); post_file(NULL, "", file , "ShiDa", title, 0, 1, getSession()); // insert into toplog_all sprintf(sqlbuf, "INSERT INTO toplog_all VALUES (NULL,'%s','%s','%s','%s',CURDATE(),'%d','%d','%d');",top[i].userid, top[i].board, newtitle, tt2timestamp(top[i].date,newts), i+1, top[i].number, top[i].groupid); if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) { printf("%s\n", mysql_error(&s)); } } else { // update toplog_all sprintf(sqlbuf,"UPDATE toplog_all SET userid='%s',bname='%s',title='%s',count='%d',time='%s',threadid='%d' WHERE date=CURDATE() AND bname='%s' AND threadid=%d;;", top[i].userid, top[i].board, newtitle, top[i].number, tt2timestamp(top[i].date,newts), top[i].groupid, top[i].board, top[i].groupid); if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) { printf("%s\n", mysql_error(&s)); } } } time(&now); ptime = *localtime(&now); if (ptime.tm_hour == 23) { total_post_top10(top[i].groupid,top[i].board,top[i].title); } #endif sprintf(sqlbuf,"UPDATE toplog SET userid='%s',bname='%s',title='%s',count='%d',time='%s',threadid='%d' WHERE date=CURDATE() AND topth='%d';", top[i].userid, top[i].board, newtitle, top[i].number, tt2timestamp(top[i].date,newts), top[i].groupid, i+1); if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) { printf("%s\n", mysql_error(&s)); continue; } if ((int)mysql_affected_rows(&s) <= 0) { sprintf(sqlbuf, "INSERT INTO toplog VALUES (NULL,'%s','%s','%s','%s',CURDATE(),'%d','%d','%d');",top[i].userid, top[i].board, newtitle, tt2timestamp(top[i].date,newts), i+1, top[i].number, top[i].groupid); if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) { printf("%s\n", mysql_error(&s)); continue; } } } mysql_close(&s); return 1; }
int main(int argc, char *argv[]) { static MYSQL demo_db; char mysql_query [2048]; MYSQL_RES *mysqlres; /* To be used to fetch information into */ MYSQL_ROW mysqlrow; int res; struct issuedaddFormat issuedadd; char clickStatus[33]; unsigned int addid; char addurl[251]; char remote_addr[32]; #ifdef DEBUG printf("Content-type: text/html\n\n"); #endif if (getenv("QUERY_STRING") == NULL) { if (argc != 4 ) { fprintf(stderr,"no QUERY_STRING and no command lin input.\n\n\tUsage addout.cgi addid http://www.test.com\n"); exit(1); } else { addid = strtoul(argv[1], (char **)NULL, 10); strcpy(addurl,argv[2]); strncpy(remote_addr,argv[3],sizeof(remote_addr) -1); } } else { //leser inn cgi variabler // Initialize the CGI lib res = cgi_init(); // Was there an error initializing the CGI??? if (res != CGIERR_NONE) { fprintf(stderr,"Error # %d: %s\n", res, cgi_strerror(res)); exit(1); } if (cgi_getentrystr("addurl") == NULL) { fprintf(stderr,"Did'n receive any addurl.\n"); exit(1); } else { strncpy(addurl,cgi_getentrystr("addurl"),sizeof(addurl) -1); } if (cgi_getentrystr("addid") == NULL) { fprintf(stderr,"Did'n receive any id.\n"); exit(1); } else { addid = strtoul(cgi_getentrystr("addid"), (char **)NULL, 10); } if (getenv("REMOTE_ADDR") == NULL) { fprintf(stderr,"Did'n receive any REMOTE_ADDR.\n"); exit(1); } else { strncpy(remote_addr,getenv("REMOTE_ADDR"),sizeof(remote_addr) -1); } } mysql_init(&demo_db); //if(!mysql_real_connect(&demo_db, "www2.boitho.com", "boitho_remote", "G7J7v5L5Y7", "boitho", 3306, NULL, 0)){ if(!mysql_real_connect(&demo_db, "localhost", "boitho", "G7J7v5L5Y7", "boithoweb", 3306, NULL, 0)){ fprintf(stderr,mysql_error(&demo_db)); exit(1); } #ifdef DEBUG printf("add id %u\n",addid); #endif sprintf(mysql_query, "select keyword,bid,uri,clickfrequency,ppcuser,affuser,ipadress,UNIX_TIMESTAMP(issuetime),UNIX_TIMESTAMP(NOW()),HTTP_ACCEPT_LANGUAGE,HTTP_USER_AGENT,HTTP_REFERER,betaler_keyword_id,betaler_side_id from issuedadds where id='%u'",addid); if(mysql_real_query(&demo_db, mysql_query, strlen(mysql_query))){ /* Make query */ fprintf(stderr,mysql_error(&demo_db)); exit(1); } //henter svaret mysqlres=mysql_store_result(&demo_db); /* Download result from server */ if ((mysqlrow=mysql_fetch_row(mysqlres)) == NULL) { /* Get a row from the results */ fprintf(stderr,"cnat't fint the add in db.\n"); strcpy(clickStatus,"CANT_FIND_ADD"); } else { #ifdef DEBUG printf("%s<br>\n%s<br>\n%s<br>\n%s<br>\n%s<br>\n%s<br>\n%s<br>\n%s<br>\n%s<br>\n%s<br>\n%s<br>\n%s<br>\n",mysqlrow[0],mysqlrow[1],mysqlrow[2],mysqlrow[3],mysqlrow[4],mysqlrow[5],mysqlrow[6],mysqlrow[7],mysqlrow[8],mysqlrow[9],mysqlrow[10],mysqlrow[11]); #endif strncpy(issuedadd.query,mysqlrow[0],sizeof(issuedadd.query)-1); issuedadd.bid = atof(mysqlrow[1]); strncpy(issuedadd.uri,mysqlrow[2],sizeof(issuedadd.uri) -1); issuedadd.clickfrequency = atoi(mysqlrow[3]); strncpy(issuedadd.ppcuser,mysqlrow[4],sizeof(issuedadd.ppcuser)-1); strncpy(issuedadd.affuser,mysqlrow[5],sizeof(issuedadd.ppcuser)-1); strncpy(issuedadd.ipadress,mysqlrow[6],sizeof(issuedadd.ipadress)-1); issuedadd.issuetime = atoi(mysqlrow[7]); issuedadd.nowtime = atoi(mysqlrow[8]); strncpy(issuedadd.HTTP_REFERER,mysqlrow[11],sizeof(issuedadd.HTTP_REFERER)-1); issuedadd.betaler_keyword_id = atoi(mysqlrow[12]); issuedadd.DocID = strtoul(mysqlrow[13], (char **)NULL, 10); //sjekker om vi har noe klikk på denne ipen til samme side fra før sprintf(mysql_query, "select * from short_out_logg where betaler_side_id='%u' AND ip_adresse='%s' AND tid > (NOW() - INTERVAL 24 HOUR)",issuedadd.DocID,issuedadd.ipadress); if(mysql_real_query(&demo_db, mysql_query, strlen(mysql_query))){ /* Make query */ printf(mysql_error(&demo_db)); exit(1); } int limit24hour;; mysqlres=mysql_store_result(&demo_db); /* Download result from server */ if ((mysqlrow=mysql_fetch_row(mysqlres)) != NULL) { /* Get a row from the results */ //printf("we have a record in short_out_logg\n"); //bør kansje oppdatere klikk frekvens her limit24hour = 1; } else { //printf("we dont have a record in short_out_logg.\n %s\n",mysql_query); //legger den inn sprintf(mysql_query, "insert into short_out_logg values('%u','%s','%i',%s)", issuedadd.DocID, issuedadd.ipadress, 0, "NOW()"); if(mysql_real_query(&demo_db, mysql_query, strlen(mysql_query))){ /* Make query */ printf(mysql_error(&demo_db)); exit(1); } limit24hour = 0; } //sjekker om dette er et gyldig klikk if (strcmp(remote_addr,issuedadd.ipadress) != 0){ strcpy(clickStatus,"IP_MISS_MATCH"); } //Sjekker om annonsen er ung nokk. // bruker now time fra mysql server isteden for time() da vi ikke nødvendivis kjører på //samme server, og klokkene ikke er synkronisert else if (issuedadd.nowtime > (issuedadd.issuetime + 3600)) { strcpy(clickStatus,"ADD_TO_OLD"); } else if (issuedadd.clickfrequency > 0) { strcpy(clickStatus,"MORE_THEN_ONE_CLICK"); } else if (limit24hour) { strcpy(clickStatus,"24_HOUR_LIMIT"); } else { //vi har en ok status strcpy(clickStatus,"OK"); } //redirekter brukeren if (strcmp(clickStatus,"OK") == 0) { printf("Location:%s\n\n",issuedadd.uri); } else { printf("Location:%s\n\n",addurl); } //kan vel egentlig stenge ned standat utputt nå? //oppdaterer klikk frekvens sprintf(mysql_query, "update issuedadds set clickfrequency = clickfrequency+1 where id='%u'",addid); if(mysql_real_query(&demo_db, mysql_query, strlen(mysql_query))){ /* Make query */ fprintf(stderr,mysql_error(&demo_db)); exit(1); } //trekker penger hvis vi har ok status if (strcmp(clickStatus,"OK") == 0) { //trekker penger fra ppc brukene sprintf(mysql_query, "update brukere set penger=penger - %f where bruker_navn='%s'",issuedadd.bid,issuedadd.ppcuser); if(mysql_real_query(&demo_db, mysql_query, strlen(mysql_query))){ /* Make query */ fprintf(stderr,mysql_error(&demo_db)); exit(1); } //betaler search/aff brukeren sprintf(mysql_query, "update brukere set penger=penger + %f where bruker_navn='%s'",issuedadd.bid,issuedadd.affuser); if(mysql_real_query(&demo_db, mysql_query, strlen(mysql_query))){ /* Make query */ fprintf(stderr,mysql_error(&demo_db)); exit(1); } } //logger sprintf(mysql_query, "insert DELAYED into out_logg values(%s,%s,'%s','%s','%s','%i','%s','%s','%f','%s')", "NULL", "NOW()", issuedadd.query, issuedadd.affuser, issuedadd.ppcuser, issuedadd.betaler_keyword_id, issuedadd.ipadress, issuedadd.HTTP_REFERER, issuedadd.bid, clickStatus); if(mysql_real_query(&demo_db, mysql_query, strlen(mysql_query))){ /* Make query */ fprintf(stderr,mysql_error(&demo_db)); exit(1); } } mysql_free_result(mysqlres); mysql_close(&demo_db); }
/*********** 根据type得到十大列表,已经经过排序等一系列检查,可以直接输出 type!=4的时候还得到分区十大 *******/ int get_top(int type) { MYSQL s; MYSQL_RES *res; MYSQL_ROW row; char sqlbuf[500]; char cmptime[200]; int start=0; int i,secid; int threadid; char title[81]; char userid[IDLEN+1]; int m,n; #ifdef BLESS_BOARD const struct boardheader *bh; #endif topnum = 0; if (type < 0 || type > 4) return 0; mysql_init(&s); if (! my_connect_mysql(&s)) { return 0;; } if (type==0 || type==4) { //sprintf(cmptime,"YEAR(time)=YEAR(CURDATE()) AND MONTH(time)=MONTH(CURDATE()) AND DAYOFMONTH(time)=DAYOFMONTH(CURDATE())"); sprintf(cmptime,"time>curdate()"); } else if (type==1) { sprintf(cmptime,"YEAR(date)=YEAR(CURDATE()) AND WEEK(date)=WEEK(CURDATE())"); } else if (type==2) { sprintf(cmptime,"YEAR(date)=YEAR(CURDATE()) AND MONTH(date)=MONTH(CURDATE())"); } else if (type==3) { sprintf(cmptime,"YEAR(date)=YEAR(CURDATE())"); } bzero(top, TOPCOUNT * sizeof(struct postrec)); bzero(sectop, SECNUM * SECTOPCOUNT * sizeof(struct postrec)); for (i=0;i<SECNUM;i++) sectopnum[i]=0; sectopnumtotal=0; while (1) { if (type==4) { if (topnum>=mytop[type]) break; } else if (type==0) { if (topnum>=mytop[type] && sectopnumtotal>=SECNUM*SECTOPCOUNT) break; } else { if (topnum >= mytop[type]) break; } if (start > MAXCMP) break; if (type==0 || type==4) sprintf(sqlbuf,"SELECT bname,threadid,MAX(UNIX_TIMESTAMP(time)) AS maxtime,count(DISTINCT userid) AS count FROM postlog WHERE %s GROUP BY bname,threadid ORDER BY count desc LIMIT %d,%d;", cmptime, start, INTERVAL); else sprintf(sqlbuf,"SELECT bname,threadid,UNIX_TIMESTAMP(time),count,title,userid FROM toplog WHERE %s ORDER BY count desc LIMIT %d,%d",cmptime,start, INTERVAL); if (mysql_real_query(&s, sqlbuf, strlen(sqlbuf))) { printf("%s\n", mysql_error(&s)); mysql_close(&s); return topnum; } res = mysql_store_result(&s); while (1) { row = mysql_fetch_row(res); if (row==NULL) break; /***检查是否该计算十大***/ bh = getbcache(row[0]); if (bh==NULL || bh->flag & BOARD_POSTSTAT) { continue; } if (!normal_board(bh->filename)) continue; #ifdef BLESS_BOARD if (type==0) { if (! strcasecmp(row[0], BLESS_BOARD)) { continue; } } else if (type==4) { if (strcasecmp(row[0], BLESS_BOARD)) { continue; } } #endif secid= get_seccode_index(bh->title[0]); if (topnum >= mytop[type] && (secid==-1 || sectopnum[secid] >= SECTOPCOUNT)) continue; threadid = atoi(row[1]); if (type==0 || type==4) { if (get_file_title(row[0], threadid, title, userid) == NULL) { continue; } } else { strncpy(title, row[4], 80); title[80]=0; strncpy(userid, row[5], IDLEN); userid[IDLEN]=0; } /**一个版面最多3个十大**/ if (type==0) { m = 0; for (n = 0; n < topnum; n++) { if (!strcmp(row[0], top[n].board)) m++; } if (m>0) continue; /***分区十大里一个版面也最多3个***/ if (secid!=-1) { m = 0; for (n = 0; n < sectopnum[secid]; n++) { if (!strcmp(row[0], sectop[secid][n].board)) m++; } if (m>0) continue; } } /***先记录正常十大的值***/ if (topnum < mytop[type]) { strncpy(top[topnum].board, row[0], BOARDNAMELEN); top[topnum].board[BOARDNAMELEN-1]='\0'; top[topnum].groupid = threadid; strncpy(top[topnum].title, title, 80); top[topnum].title[80]='\0'; strncpy(top[topnum].userid, userid, IDLEN); top[topnum].userid[IDLEN]='\0'; top[topnum].date = atol(row[2]); top[topnum].number = atoi(row[3]); topnum++; } /***计算分区十大***/ if (type==0) { i=secid; if (i!=-1) { if (sectopnum[i] < SECTOPCOUNT) { strncpy(sectop[i][sectopnum[i]].board, row[0], BOARDNAMELEN); sectop[i][sectopnum[i]].board[BOARDNAMELEN-1]='\0'; sectop[i][sectopnum[i]].groupid = threadid; strncpy(sectop[i][sectopnum[i]].title, title, 80); sectop[i][sectopnum[i]].title[80]='\0'; strncpy(sectop[i][sectopnum[i]].userid, userid, IDLEN); sectop[i][sectopnum[i]].userid[IDLEN]='\0'; sectop[i][sectopnum[i]].date = atol(row[2]); sectop[i][sectopnum[i]].number = atoi(row[3]); sectopnum[i]++; sectopnumtotal++; } } }//type==0 if (type==4) { if (topnum>=mytop[type]) break; } else if (type==0) { if (topnum >= mytop[type] && sectopnumtotal >= SECNUM*SECTOPCOUNT) break; } else { if (topnum >= mytop[type]) break; } } mysql_free_result(res); start += INTERVAL; } mysql_close(&s); return topnum; }
int get_verify_from_db(unsigned char *verify_str,int* verify_len,unsigned char* filename_hash,int filename_hash_len) { int index,i; unsigned char query[8500]; sprintf((char*)query,"select %s from %s where %s = 0x",VALUE,TABLE,KEY); index = strlen(query); for(i = 0;i < filename_hash_len;i++) { sprintf((char*)(query+index),"%02x",filename_hash[i]); index += 2; } int rc = mysql_real_query(mysql,query,index); if(rc) { printf("can't complete query\n"); return -1; } if((results = mysql_use_result(mysql)) == NULL) { printf("can't get the result\n"); return -1; } if((record = mysql_fetch_row(results)) != NULL) { unsigned long * len = mysql_fetch_lengths(results); if(len[0] == 0) { *verify_len = 0; }else { // printf("%d ",len[0]); for(i = 0;i < len[0]; i++) { // printf("%02x ",record[0][i]); verify_str[i] = record[0][i]; } *verify_len = len[0]; } mysql_free_result(results); return 0; }else{ if(mysql_errno(mysql) == 0) { //no such key *verify_len = 0; mysql_free_result(results); return 0; }else { printf("error occurrs when fetching\n"); mysql_free_result(results); return -1; } } mysql_free_result(results); return 0; }