/************************************************************************** Saves pconn fields to the database. If the username already exists, replace the data. **************************************************************************/ static bool auth_db_save(struct connection *pconn) { #ifdef HAVE_AUTH char buffer[1024] = ""; const int bufsize = sizeof(buffer); char *name_buffer = NULL; char *pw_buffer = NULL; MYSQL *sock, mysql; int str_result; mysql_init(&mysql); /* attempt to connect to the server */ if (!(sock = mysql_real_connect(&mysql, auth_config.host.value, auth_config.user.value, auth_config.password.value, auth_config.database.value, atoi(auth_config.port.value), NULL, 0))) { freelog(LOG_ERROR, "Can't connect to server! (%s)", mysql_error(&mysql)); return FALSE; } name_buffer = alloc_escaped_string(&mysql, pconn->username); pw_buffer = alloc_escaped_string(&mysql, pconn->server.password); if (name_buffer == NULL || pw_buffer == NULL) { free_escaped_string(name_buffer); mysql_close(sock); return FALSE; } /* insert new user into table. we insert the following things: name * md5sum of the password, the creation time in seconds, the accesstime * also in seconds from 1970, the users address (twice) and the logincount */ str_result = my_snprintf(buffer, bufsize, "insert into %s values " "(NULL, '%s', '%s', NULL, " "unix_timestamp(), unix_timestamp()," "'%s', '%s', 0)", auth_config.table.value, name_buffer, pw_buffer, pconn->server.ipaddr, pconn->server.ipaddr); /* Password is not needed for further queries. */ free_escaped_string(pw_buffer); pw_buffer = NULL; if (str_result < 0 || str_result >= bufsize || mysql_query(sock, buffer)) { freelog(LOG_ERROR, "db_save insert failed for new user: %s (%s)", pconn->username, mysql_error(sock)); mysql_close(sock); return FALSE; } /* insert an entry into our log */ memset(buffer, 0, bufsize); str_result = my_snprintf(buffer, bufsize, "insert into %s (name, logintime, address, succeed) " "values ('%s',unix_timestamp(),'%s', 'S')", auth_config.login_table.value, name_buffer, pconn->server.ipaddr); free_escaped_string(name_buffer); name_buffer = 0; if (str_result < 0 || str_result >= bufsize || mysql_query(sock, buffer)) { freelog(LOG_ERROR, "db_load insert loginlog failed for user: %s (%s)", pconn->username, mysql_error(sock)); } mysql_close(sock); #endif return TRUE; }
BOOL CDlgHistoryLogSystem::SearchAndSetHistoryListInfo(char *szStartTime,char *szStopTime) { if (szStartTime == NULL||szStopTime == NULL) return FALSE; char sql_buf[512] = {0}; bool result=false; MYSQL_RES * res = NULL ; MYSQL_ROW row ; char szServerName[256] = {0}; char szServerType[64] = {0}; char szServerState[64] = {0}; char szCpuUseRate[64] = {0}; char szMemoryUseRate[64] = {0}; char szMemoryUse[64] = {0}; char szDiscUse[64] = {0}; char szUpdateTime[64] = {0}; COLORREF BKColor; COLORREF TextColor; BKColor = RGB(207,235,250); TextColor = RGB(168,0,0); int nCount = 0; //读服务历史日志 sprintf_s(sql_buf, sizeof(sql_buf),"SELECT server_name, server_type, server_state, cpu_use_rate, memory_use_rate, memory_use, disk_use," "time FROM history_server_load_state where time >= '%s' AND time <= '%s' ORDER BY time desc",szStartTime,szStopTime); if (!mysql_query(g_mySqlData, sql_buf)) { res = mysql_store_result(g_mySqlData); while ( row = mysql_fetch_row( res ) ) { if (nCount >= 300) break; sprintf_s(szServerName,"%s", row[0]); sprintf_s(szServerType, "%s", row[1]); sprintf_s(szServerState, "%s", row[2]); sprintf_s(szCpuUseRate,"%s%%",row[3]); sprintf_s(szMemoryUseRate,"%s%%",row[4]); sprintf_s(szMemoryUse,"%sK",row[5]); sprintf_s(szDiscUse,"%sK",row[6]); sprintf_s(szUpdateTime,"%s",row[7]); ////////////////////////////////////////////////////////////////////////// if (strcmp(szServerType,"1") == 0)//类型 { sprintf_s(szServerType,"联动服务器"); } if (strcmp(szServerState,"1") == 0)//状态 { sprintf_s(szServerState,"在线"); } else if (strcmp(szServerState,"0") == 0) { sprintf_s(szServerState,"离线"); } if (strcmp(szMemoryUse,"0K") == 0&&strcmp(szDiscUse,"0K") == 0)//刚上线 { sprintf_s(szServerState,"上线"); } ////////////////////////////////////////////////////////////////////////// m_ListCtrl_SystemLog.InsertItem(nCount,szServerName); m_ListCtrl_SystemLog.SetItemText(nCount,1,szServerType); m_ListCtrl_SystemLog.SetItemText(nCount,2,szServerState); m_ListCtrl_SystemLog.SetItemText(nCount,3,szCpuUseRate); m_ListCtrl_SystemLog.SetItemText(nCount,4,szMemoryUseRate); m_ListCtrl_SystemLog.SetItemText(nCount,5,szMemoryUse); m_ListCtrl_SystemLog.SetItemText(nCount,6,szDiscUse); m_ListCtrl_SystemLog.SetItemText(nCount,7,szUpdateTime); m_ListCtrl_SystemLog.SetRowColor(nCount,BKColor); m_ListCtrl_SystemLog.SetRowTextColor(nCount,TextColor); nCount++; } mysql_free_result( res ) ; } return TRUE; }
OGRErr OGRMySQLDataSource::InitializeMetadataTables() { const char* pszCommand; MYSQL_RES *hResult; OGRErr eErr = OGRERR_NONE; pszCommand = "DESCRIBE geometry_columns"; if( mysql_query(GetConn(), pszCommand ) ) { pszCommand = "CREATE TABLE geometry_columns " "( F_TABLE_CATALOG VARCHAR(256), " "F_TABLE_SCHEMA VARCHAR(256), " "F_TABLE_NAME VARCHAR(256) NOT NULL," "F_GEOMETRY_COLUMN VARCHAR(256) NOT NULL, " "COORD_DIMENSION INT, " "SRID INT," "TYPE VARCHAR(256) NOT NULL)"; if( mysql_query(GetConn(), pszCommand ) ) { ReportError( pszCommand ); eErr = OGRERR_FAILURE; } else CPLDebug("MYSQL","Creating geometry_columns metadata table"); } // make sure to attempt to free results of successful queries hResult = mysql_store_result( GetConn() ); if( hResult != NULL ) { mysql_free_result( hResult ); hResult = NULL; } pszCommand = "DESCRIBE spatial_ref_sys"; if( mysql_query(GetConn(), pszCommand ) ) { pszCommand = "CREATE TABLE spatial_ref_sys " "(SRID INT NOT NULL, " "AUTH_NAME VARCHAR(256), " "AUTH_SRID INT, " "SRTEXT VARCHAR(2048))"; if( mysql_query(GetConn(), pszCommand ) ) { ReportError( pszCommand ); eErr = OGRERR_FAILURE; } else CPLDebug("MYSQL","Creating spatial_ref_sys metadata table"); } // make sure to attempt to free results of successful queries hResult = mysql_store_result( GetConn() ); if( hResult != NULL ) { mysql_free_result( hResult ); hResult = NULL; } return eErr; }
int main(int argc, char** argv) { //reading data values int fd; int ctr_numhits=0; int num_records=0; ssize_t numbytes; int compare = 1; off_t offset = 0; char error_buf[ERROR_BUF_SIZE]; int headersize=DR_HEAER_SIZE; int next_buffer_size=1; int datasize=next_buffer_size; char *header = (char *) malloc(DR_HEAER_SIZE); char *data = (char *) malloc(MAX_DATA_SIZE); //plotting variables int maxbin = 0; int maxvalue = 0; int xmax = (int) BINS; //data values int finebin = 0 ; int bytesread = 1; int value; int pfb_bin = 0; int fft_bin = 0; int fft_bin_loc= 0; int over_thresh = 0; int blank = 0; int event = 0; unsigned int pfb_fft_power = 0; unsigned int fields; long int i = 0; int j = 0; int k = 0; int ctr = 0; int counter=0; int beamnum = 0; double fstep,fscoarse = 0.0; double rfmin,rfctr = 0.0; double freq_fft_bin = 0.0; double bary_freq = 0.0; char rawfile[] = "largefile_MMMDDYYYY_HHMM"; int gooddata=1; int goodfreq=1; long int fileposition=0; //position in input file long int filesize; //position in input file FILE *fout; //create buffers struct spectral_data spectra; struct data_vals *data_ptr; data_ptr = (struct data_vals *)data; //create header structure struct setidata frame; // create time structure tm hittime; double spec_time; // create SQL structures unsigned long int specid; //strcpy(def_password, argv[2]); char sqlquery[1024]; char hitquery[1024]; // file variables FILE *datatext; // connect to mySQL database dbconnect(); #ifdef GRACE // Initialize grace plotting windows grace_init(); // grace_open_deux(8192); // grace_init_deux(maxbin,maxvalue,xmax); #endif //check for error opening file fd = open(argv[1], O_RDONLY); if(fd==-1) { snprintf(error_buf, ERROR_BUF_SIZE, "Error opening file %s", argv[1]); perror(error_buf); return 0; } //if we can't find a header, nothing to be done if(find_first_header(fd)==-1) return 0; //read header //make sure we are reading as much data as expected, otherwise might be at eof while(headersize==DR_HEAER_SIZE && datasize==next_buffer_size) { k = k+1; //reset dataflag to "good" gooddata=1; // read in the header data headersize = read(fd, (void *) header, DR_HEAER_SIZE); fileposition+=headersize; // int iii=0; // for(iii=0; iii<DR_HEAER_SIZE; iii++) // printf("%c", header[iii]); //get the size of spectra and parse header values next_buffer_size = read_header(header); read_header_data(header, &frame); //Read in data datasize = read(fd, (void *) data, next_buffer_size); fileposition+=datasize; // printf("Buffersize, datasize: %d %d\n", next_buffer_size, datasize); // int iii=0; // printf("Printing data header\n"); // for(iii=0; iii<datasize; iii++) // printf("%c", data[iii]); //Parse data header beamnum = read_beam(data, datasize); read_data_header(data, &frame); //Convert to RA and Dec scramAzZatoRaDec(frame.agc_systime, frame.agc_time, frame.agc_az, frame.agc_za, frame.alfashm_alfamotorposition, beamnum/2, 0, &frame.ra, &frame.dec, &hittime); get_filename(argv[1], rawfile); // printf("%s\n", rawfile); //Calculate MJD spec_time = time2mjd(frame.agc_systime, frame.agc_time); // creates query to config table // set digital_lo and board to be constants, because we figured we knew // what they were and that they weren't changing char bid[] = "B2"; sprintf(sqlquery, "INSERT INTO config (thrscale, thrlimit, fftshift, pfbshift, beamnum, obstime, ra, decl, digital_lo, board, AGC_SysTime, AGC_Time, AGC_Az, AGC_Za, AlfaFirstBias, AlfaSecondBias, AlfaMotorPosition, IF1_rfFreq, synI_freqHz, IF1_synI_ampDB, IF1_if1FrqMHz, IF1_alfaFb, TT_TurretEncoder, TT_TurretDegrees, rawfile) VALUES (%ld, %ld, %ld, %ld, %d, %lf, %lf, %lf, %ld, '%s', %ld, %ld, %lf, %lf, %ld, %ld, %lf, %9.1lf, %9.1lf, %ld, %lf, %ld, %ld, %lf, '%s')", frame.thrscale, frame.thrlimit, frame.fft_shift, frame.pfb_shift, beamnum, (double) ((int) spec_time), frame.ra, frame.dec, 200000000, bid, frame.agc_systime, frame.agc_time, frame.agc_az, frame.agc_za, frame.alfashm_alfafirstbias, frame.alfashm_alfasecondbias, frame.alfashm_alfamotorposition, frame.if1_rffreq, frame.if1_syni_freqhz_0, frame.if1_syni_ampdb_0, frame.if1_if1frqmhz, frame.if1_alfafb, frame.tt_turretencoder, frame.tt_turretdegrees, rawfile); #ifndef DEBUG // insert header data into serendipvv config table if (mysql_query(conn, sqlquery)) { fprintf(stderr, "Error inserting data into sql database... \n"); exiterr(3); } // saves specid to be inserted at index in other sql tables if ((res = mysql_store_result(conn))==0 && mysql_field_count(conn)==0 && mysql_insert_id(conn)!=0) { specid = (unsigned long int) mysql_insert_id(conn); } #endif #ifdef DEBUG printf("%s\n", sqlquery); printf("Spec id: %d\n", specid); #endif //doesn't do any bounds checking yet... spectra.numhits = read_data(data, datasize) - 4096; //printf("size of spectra %d\n",spectra.numhits); //header,data data_ptr = (struct data_vals *) (data+SETI_HEADER_SIZE_IN_BYTES); //======================== TEST FILE DATA DUMP ================ /* FILE *datafile; char dataf[100]; sprintf(dataf,"datafiles/datafile%d.dat",counter); datafile = fopen(dataf,"wb"); fwrite(data,spectra.numhits,1,(FILE *)datafile); fflush(datafile); fclose(datafile); */ //============================================== num_records = read_data(data,datasize); ctr_numhits=0; //create file spectraldata and print file header /* char filename[BUFSIZ]; sprintf(filename, "spectraldata%d", beamnum); datatext = fopen(filename,"w"); fprintf(datatext, "specnum,beamnum,coarsebin,coarsepower,hitpower,fftbin\n"); */ //Calc values for freq_topo calc //Freq chan resolution fstep = 200000000.0/134217728; fscoarse = 200000000.0/4096; //Center of the BEE2 bandpass rfctr = frame.if1_rffreq - 50000000.0; //Right edge of the last bin is the lowest freq //because the RF band is flipped in the IF // rfmin=rfctr-0.5*fscoarse; rfmin=rfctr+0.5*fscoarse; //Check to see if there are too many hits if(num_records>0.9*frame.thrlimit*4096) { gooddata=0; fprintf(stderr, "Data bad...more than %5.0lf hits.\n", 0.9*frame.thrlimit*4096); } //****OPEN FILE TO WRITE HITS TO fout=fopen("hits_list.txt", "w"); //============================ // LOOP OVER HITS //============================= for(i=0;i< num_records ;i++) { goodfreq=1; fields = ntohl(data_ptr->raw_data); fft_bin = slice(fields,15,0); pfb_bin = slice(fields,12,15); over_thresh = slice(fields,1,27); blank = slice(fields,3,28); event = slice(fields,1,31); pfb_fft_power = ntohl(data_ptr->overflow_cntr); //32.0 // pfb_fft_power = data_ptr->overflow_cntr; //32.0 //Rearrange the bins //1) Reorder the FFT output order //2) Reverse bins due to RF/IF flip pfb_bin = (pfb_bin + 2048) % 4096; // pfb_bin = 4096 - pfb_bin; pfb_bin = 4095 - pfb_bin; fft_bin = (fft_bin + 16384) % 32768; // fft_bin = 32768 - fft_bin; fft_bin = 32767 - fft_bin; fft_bin_loc = fft_bin; fft_bin+=pfb_bin*32768; freq_fft_bin = rfmin + fstep*fft_bin; //Check that the freq of the hit falls within the valid ranges if(frame.if1_alfafb==1){ if(freq_fft_bin < NBF_FREQ_LO || freq_fft_bin > NBF_FREQ_HI) goodfreq=0; } else if(frame.if1_alfafb==0){ if(freq_fft_bin < ALFA_FREQ_LO || freq_fft_bin > ALFA_FREQ_HI) goodfreq=0; } value = (int) (pfb_fft_power); //printf("%d %d %d %d %d %d\n", pfb_bin, fft_bin, pfb_fft_power, blank, event, over_thresh); if(value < 1) { value = 1; } if(value > maxvalue) { maxvalue = value; maxbin = fft_bin; } //populate coarse bin power if(fft_bin_loc==16383) { spectra.coarse_spectra[pfb_bin] = value; } //Only generate string and insert into database if hit valid if(fft_bin_loc!=16383 && goodfreq==1 && gooddata==1) { // spectra.hits[ctr_numhits][0] = value; // spectra.hits[ctr_numhits][1] = fft_bin; //Calculate the frequency of the fine bins and barycenter bary_freq=freq_fft_bin+seti_dop_FreqOffsetAtBaryCenter(freq_fft_bin, spec_time+2400000.5, frame.ra, frame.dec, 2000.0, AO_LAT, AO_LONG, AO_ELEV); //Prepare mysql query to insert hits sprintf(hitquery, "INSERT INTO hit (eventpower, meanpower, binnum, topocentric_freq, barycentric_freq, specid) VALUES (%f, %e, %d, %lf, %lf, %ld)", (double) value, (double) spectra.coarse_spectra[pfb_bin], fft_bin, freq_fft_bin, bary_freq, specid); //Write row to tmp file fprintf(fout, "\\N\t %f\t %e\t %d\t %lf\t %lf\t 0\t 0\t 0\t 0\t 0\t %ld\t \n", (double) value, (double) spectra.coarse_spectra[pfb_bin], fft_bin, freq_fft_bin, bary_freq, specid); /* #ifndef DEBUG // insert header data into serendipvv config table if (mysql_query(conn, hitquery)) { fprintf(stderr, "Error inserting data into sql database... \n"); exiterr(3); } #endif */ } // fill spectraldata with available data and close file // fprintf(datatext, "%d, %d, %d, %e, %f, %d\n", k, beamnum, pfb_bin, (double) spectra.coarse_spectra[pfb_bin], (double) value, fft_bin); ctr_numhits++; data_ptr++; ctr++; }//for(i=0; i<num_records; i++) fclose(fout); sprintf(hitquery, "LOAD DATA LOCAL INFILE 'hits_list.txt' INTO TABLE hit"); // printf("%s\n", hitquery); if (mysql_query(conn, hitquery)) { fprintf(stderr, "Error inserting data into sql database... \n"); exiterr(3); } // fclose(datatext); #ifndef DEBUG if(load_blob(conn, specid, spectra.coarse_spectra)!=0) { fprintf(stderr, "Blob not loaded\n"); specid=0; } #endif // GracePrintf("autoticks"); // GracePrintf("redraw"); // GracePrintf("updateall"); // GracePrintf("kill g0.s0"); // GracePrintf("saveall \"plots/sample%d.agr\"",counter); // grace_init_deux(maxbin,log10(maxvalue),xmax); counter++; for(i=0;i<4094;i++) { spectra.coarse_spectra[i] = spectra.coarse_spectra[i+1]; } #ifdef GRACE plot_beam(&spectra,beamnum); printf("num_records: %d spectra.numhits %d\n",num_records,spectra.numhits); usleep(200000); if(counter%10 == 0) { printf("autoscaling...\n"); GracePrintf("redraw"); GracePrintf("updateall"); GracePrintf("autoscale"); /* //output pdf via grace GracePrintf("HARDCOPY DEVICE \"EPS\""); printf("start eps create\n"); GracePrintf("PAGE SIZE 600, 600"); GracePrintf("saveall \"sample.agr\""); GracePrintf("PRINT TO \"%s\"", "plot.eps"); GracePrintf("PRINT"); */ } #endif } //===================================================== /* // play with some text for(i=0; i<10; i++){ GracePrintf("WITH STRING %d", i); GracePrintf("STRING COLOR 0"); GracePrintf("STRING FONT 8"); GracePrintf("STRING DEF \"TEST\""); GracePrintf("STRING ON"); GracePrintf("STRING LOCTYPE view"); GracePrintf("STRING 0.70, %f", 0.95 - (((float) i) / 40.0) ); } GracePrintf("redraw"); sleep(5); */ //=========================================================== #ifdef GRACE if (GraceIsOpen()) { //Flush the output buffer and close Grace GraceClose(); // We are done exit(EXIT_SUCCESS); } else { exit(EXIT_FAILURE); } #endif //close file close(fd); return 0; }
int oph_odb_set_job_status_and_nchildrencompleted(int id_job, enum oph__oph_odb_job_status status, int nchildren, int force_nchildren_saving, ophidiadb * oDB) { if (!oDB) { pmesg(LOG_ERROR, __FILE__, __LINE__, "Null input parameter\n"); return OPH_ODB_NULL_PARAM; } if (oph_odb_check_connection_to_ophidiadb(oDB)) { pmesg(LOG_ERROR, __FILE__, __LINE__, "Unable to reconnect to OphidiaDB.\n"); return OPH_ODB_MYSQL_ERROR; } char insertQuery[MYSQL_BUFLEN]; int n; switch (status) { case OPH_ODB_STATUS_UNKNOWN: if (nchildren >= 0) { pmesg(LOG_DEBUG, __FILE__, __LINE__, "Status is not changed\n"); return OPH_ODB_SUCCESS; } n = snprintf(insertQuery, MYSQL_BUFLEN, MYSQL_QUERY_DELETE_OPHIDIADB_JOB, id_job); break; case OPH_ODB_STATUS_CLOSED: pmesg(LOG_ERROR, __FILE__, __LINE__, "Status %s is not allowed\n", OPH_ODB_STATUS_UNKNOWN_STR); return OPH_ODB_MYSQL_ERROR; case OPH_ODB_STATUS_PENDING: case OPH_ODB_STATUS_WAIT: case OPH_ODB_STATUS_START: case OPH_ODB_STATUS_SET_ENV: case OPH_ODB_STATUS_INIT: case OPH_ODB_STATUS_DISTRIBUTE: case OPH_ODB_STATUS_EXECUTE: case OPH_ODB_STATUS_REDUCE: case OPH_ODB_STATUS_DESTROY: case OPH_ODB_STATUS_UNSET_ENV: if (nchildren < 0) n = snprintf(insertQuery, MYSQL_BUFLEN, MYSQL_QUERY_UPDATE_OPHIDIADB_JOB_STATUS_1, oph_odb_convert_status_to_str(status), id_job); else n = snprintf(insertQuery, MYSQL_BUFLEN, MYSQL_QUERY_UPDATE_OPHIDIADB_JOB_STATUS_PARENT_1, oph_odb_convert_status_to_str(status), nchildren, id_job); break; case OPH_ODB_STATUS_RUNNING: if (nchildren < 0) n = snprintf(insertQuery, MYSQL_BUFLEN, MYSQL_QUERY_UPDATE_OPHIDIADB_JOB_STATUS_2, oph_odb_convert_status_to_str(status), id_job); else if (force_nchildren_saving) n = snprintf(insertQuery, MYSQL_BUFLEN, MYSQL_QUERY_UPDATE_OPHIDIADB_JOB_STATUS_PARENT_1, oph_odb_convert_status_to_str(status), nchildren, id_job); else n = snprintf(insertQuery, MYSQL_BUFLEN, MYSQL_QUERY_UPDATE_OPHIDIADB_JOB_STATUS_PARENT_2, oph_odb_convert_status_to_str(status), nchildren, id_job); break; case OPH_ODB_STATUS_COMPLETED: case OPH_ODB_STATUS_ERROR: case OPH_ODB_STATUS_START_ERROR: // Exception due to errors in operator arguments case OPH_ODB_STATUS_ABORTED: case OPH_ODB_STATUS_EXPIRED: if (nchildren < 0) n = snprintf(insertQuery, MYSQL_BUFLEN, MYSQL_QUERY_UPDATE_OPHIDIADB_JOB_STATUS_3, oph_odb_convert_status_to_str(status), id_job); else n = snprintf(insertQuery, MYSQL_BUFLEN, MYSQL_QUERY_UPDATE_OPHIDIADB_JOB_STATUS_PARENT_3, oph_odb_convert_status_to_str(status), nchildren, id_job); break; default: if (nchildren < 0) n = snprintf(insertQuery, MYSQL_BUFLEN, MYSQL_QUERY_UPDATE_OPHIDIADB_JOB_STATUS_4, id_job); else n = snprintf(insertQuery, MYSQL_BUFLEN, MYSQL_QUERY_UPDATE_OPHIDIADB_JOB_STATUS_PARENT_4, nchildren, id_job); } if (n >= MYSQL_BUFLEN) { pmesg(LOG_ERROR, __FILE__, __LINE__, "Size of query exceed query limit.\n"); return OPH_ODB_STR_BUFF_OVERFLOW; } if ((nchildren >= 0) && mysql_set_server_option(oDB->conn, MYSQL_OPTION_MULTI_STATEMENTS_ON)) { pmesg(LOG_ERROR, __FILE__, __LINE__, "MySQL query error: %s\n", mysql_error(oDB->conn)); return OPH_ODB_MYSQL_ERROR; } if (mysql_query(oDB->conn, insertQuery)) { pmesg(LOG_ERROR, __FILE__, __LINE__, "MySQL query error: %s\n", mysql_error(oDB->conn)); return OPH_ODB_MYSQL_ERROR; } pmesg(LOG_DEBUG, __FILE__, __LINE__, "Job status changed into '%s' using: %s\n", oph_odb_convert_status_to_str(status), insertQuery); return OPH_ODB_SUCCESS; }
int main( int argc, char *argv[] ) { zmDbgInit( "zmfix", "", -1 ); zmLoadConfig(); // Only do registered devices static char sql[BUFSIZ]; snprintf( sql, sizeof(sql), "select distinct Device from Monitors where not isnull(Device) and Type = 'Local'" ); if ( mysql_query( &dbconn, sql ) ) { Error( "Can't run query: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } MYSQL_RES *result = mysql_store_result( &dbconn ); if ( !result ) { Error( "Can't use query result: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) { fixDevice( dbrow[0] ); } if ( mysql_errno( &dbconn ) ) { Error( "Can't fetch row: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } // Yadda yadda mysql_free_result( result ); snprintf( sql, sizeof(sql), "select distinct ControlDevice from Monitors where not isnull(ControlDevice)" ); if ( mysql_query( &dbconn, sql ) ) { Error( "Can't run query: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } result = mysql_store_result( &dbconn ); if ( !result ) { Error( "Can't use query result: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) { fixDevice( dbrow[0] ); } if ( mysql_errno( &dbconn ) ) { Error( "Can't fetch row: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } // Yadda yadda mysql_free_result( result ); if ( config.opt_x10 ) { if ( config.x10_device ) { fixDevice( config.x10_device ); } } return( 0 ); }
/** * (re)connect to database */ int IpfixDbWriter::connectToDB() { ostringstream statement; dbError = true; // close (in the case that it was already connected) if (conn) mysql_close(conn); /** get the mysl init handle*/ conn = mysql_init(0); if(conn == 0) { msg(MSG_FATAL,"IpfixDbWriter: Get MySQL connect handle failed. Error: %s", mysql_error(conn)); return 1; } msg(MSG_DEBUG,"IpfixDbWriter: mysql init successful"); /**Connect to Database*/ if (!mysql_real_connect(conn, dbHost.c_str(), dbUser.c_str(), dbPassword.c_str(), 0, dbPort, 0, 0)) { msg(MSG_FATAL,"IpfixDbWriter: Connection to database failed. Error: %s", mysql_error(conn)); return 1; } msg(MSG_DEBUG,"IpfixDbWriter: succesfully connected to database"); /** make query string to create database**/ statement << "CREATE DATABASE IF NOT EXISTS " << dbName; DPRINTF("SQL Query: %s", statement.str().c_str()); /**create database*/ if(mysql_query(conn, statement.str().c_str()) != 0 ) { msg(MSG_FATAL, "IpfixDbWriter: Creation of database %s failed. Error: %s", dbName.c_str(), mysql_error(conn)); return 1; } msg(MSG_INFO,"IpfixDbWriter: Database %s created", dbName.c_str()); /** use database with dbName**/ if(mysql_select_db(conn, dbName.c_str()) !=0) { msg(MSG_FATAL, "IpfixDbWriter: Database %s not selectable. Error: %s", dbName.c_str(), mysql_error(conn)); return 1; } msg(MSG_DEBUG,"IpfixDbWriter: Database %s selected", dbName.c_str()); /**create table exporter*/ statement.str(""); statement.clear(); statement << "CREATE TABLE IF NOT EXISTS exporter (id SMALLINT(5) NOT NULL AUTO_INCREMENT, sourceID INTEGER(10) UNSIGNED DEFAULT NULL, srcIP INTEGER(10) UNSIGNED DEFAULT NULL, PRIMARY KEY(id))"; DPRINTF("SQL Query: %s", statement.str().c_str()); if(mysql_query(conn, statement.str().c_str()) != 0) { msg(MSG_FATAL,"IpfixDbWriter: Creation of exporter table failed. Error: %s", mysql_error(conn)); return 1; } msg(MSG_INFO,"IpfixDbWriter: Exporter table created"); dbError = false; return 0; }
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); } }
//3.获取所有用户信息 //@ domain ... //@ json_Users 返回所有用户信息。 ret_s ldapInfoDB::getLdapAllUsers(out string &json_Users){ int fieldNum,rowNum; int res; MYSQL_RES * my_res; MYSQL_ROW my_row; MYSQL_FIELD *fd; char column[32][32]; checksql(); sprintf(_sql,"select * from EmailUser;"); res = mysql_query(_my_con,_sql); if(!res) { my_res = mysql_store_result(_my_con); if(my_res) { #ifdef TRACE cout<<"number of my_res: "<<(unsigned long)mysql_num_rows(my_res)<<endl; for(fieldNum = 0;fd = mysql_fetch_field(my_res);fieldNum++) { strcpy(column[fieldNum],fd->name); } rowNum = mysql_num_fields(my_res); for(fieldNum = 0;fieldNum < rowNum;fieldNum++) { printf("%s\t",column[fieldNum]); } #endif while(my_row = mysql_fetch_row(my_res)) { User_json userNode; fieldNum = 0; int UserJur = -1; if(my_row[fieldNum]) userNode.user_id = atoi(my_row[fieldNum]); ++fieldNum; if(my_row[fieldNum]) userNode.email = my_row[fieldNum]; ++fieldNum; if(my_row[fieldNum]) userNode.password = my_row[fieldNum]; ++fieldNum; if(my_row[fieldNum]) userNode.is_staff = atoi(my_row[fieldNum]); ++fieldNum; if(my_row[fieldNum]) userNode.is_active = atoi(my_row[fieldNum]); ++fieldNum; if(my_row[fieldNum]) userNode.ctime = atol(my_row[fieldNum]); userNode.jurisdiction = selectJur(userNode.email); _vec_User_Js.push_back(userNode); } } mysql_free_result(my_res); } //组织json buildJsonUser(json_Users); return 0; }
static void btmGaiBerriaAdos() { gchar sql[300]; MYSQL_ROW row; if ( (atoi(gtk_entry_get_text(GTK_ENTRY(txtErosketaKop))) < 1) && (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(checkMateriala)) == 1)) { // Mezua, kopuru desegokia dela esanaz GtkWidget *mezua = gtk_message_dialog_new(GTK_WINDOW(frmGaiBerriaSartu), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "Ez dituzu datu zuzenak sartu!"); gtk_dialog_run(GTK_DIALOG(mezua)); gtk_widget_destroy(mezua); } else { if ( (strcmp(gtk_entry_get_text(GTK_ENTRY(txtIzena)), "") != 0) && (strcmp(gtk_entry_get_text(GTK_ENTRY(txtElkartekoPrezioa)), "") != 0) && (gtk_combo_box_get_active(GTK_COMBO_BOX(cmbAukerak)) != -1) && (strcmp(gtk_entry_get_text(GTK_ENTRY(txtErosketaKop)), "") != 0) && (strcmp(gtk_entry_get_text(GTK_ENTRY(txtErosketaPrezioaUnitateko)), "") != 0) ) { // Gai Berria sartu sprintf(sql, "Select AKodea from Aukerak where Aizenaeus='%s'", gtk_combo_box_get_active_text(GTK_COMBO_BOX(cmbAukerak))); mysql_query(dbElkartea, sql); rstAukerak = mysql_use_result(dbElkartea); row = mysql_fetch_row(rstAukerak); int AKodea = atoi(row[0]); mysql_free_result(rstAukerak); int GKodea=1; int GOrdena=1; mysql_query(dbElkartea, "Select MAX(GKodea) from Gaiak"); rstGaiak = mysql_use_result(dbElkartea); row = mysql_fetch_row(rstGaiak); if (row[0]!=NULL) { GKodea=atoi(row[0])+1; } mysql_free_result(rstGaiak); sprintf(sql, "Select MAX(GOrdena) from Gaiak where AKodea=%d", AKodea); mysql_query(dbElkartea, sql); rstGaiak = mysql_use_result(dbElkartea); row = mysql_fetch_row(rstGaiak); if (row[0]!=NULL) { GOrdena=atoi(row[0])+1; } mysql_free_result(rstGaiak); sprintf(sql, "Insert into Gaiak values('%s', %d, '%s', 0, %d, %d, '', %d, 1)", gtk_entry_get_text(GTK_ENTRY(txtIzena)), gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(checkMateriala)), gtk_entry_get_text(GTK_ENTRY(txtElkartekoPrezioa)), GKodea, AKodea, GOrdena); mysql_query(dbElkartea, sql); //Bodega aktualizatu sprintf(sql, "Insert into Elkartea values(%d, %d)", GKodea, atoi(gtk_entry_get_text(GTK_ENTRY(txtErosketaKop)))); mysql_query(dbElkartea, sql); //Erosketak aktualizatu int HKodea; if (gtk_combo_box_get_active(GTK_COMBO_BOX(cmbHornitzaileak)) == -1) HKodea=0; else { sprintf(sql, "Select HGakoa from Hornitzaileak where HIzena='%s'", gtk_combo_box_get_active_text(GTK_COMBO_BOX(cmbHornitzaileak))); mysql_query(dbElkartea, sql); rstHornitzaileak = mysql_use_result(dbElkartea); row=mysql_fetch_row(rstHornitzaileak); HKodea=atoi(row[0]); mysql_free_result(rstHornitzaileak); } sprintf(sql, "Insert into Erosketak(GaiKodea, GaiKopurua, data, HorniKodea, ErosketaPrezioa) values(%d, %d, CURDATE(), %d, '%s')", GKodea, atoi(gtk_entry_get_text(GTK_ENTRY(txtErosketaKop))), HKodea, gtk_entry_get_text(GTK_ENTRY(txtErosketaPrezioaUnitateko))); mysql_query(dbElkartea, sql); gtk_main_quit(); gtk_widget_destroy(frmGaiBerriaSartu); } else { //mezua!, datuak ez direla zuzenak esanaz GtkWidget *mezua = gtk_message_dialog_new(GTK_WINDOW(frmGaiBerriaSartu), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "Ez dituzu datu zuzenak sartu!"); gtk_dialog_run(GTK_DIALOG(mezua)); gtk_widget_destroy(mezua); } } }
static void handle_data(unsigned char *data, ssize_t len) { ssize_t i; static unsigned char buf[BUFSIZE]; static unsigned int idx = 0; static int datactr = 0; static int8_t pseqno; static uint8_t seqno; uint8_t crc8; int16_t temp; uint16_t rh; FILE *templog = NULL; char filename[PATH_MAX]; #ifdef USE_DATABASE char query[128]; #endif struct tm *tmp; time_t t; char timestr[64]; static enum { STX1, STX2, ADDR, TYPE, DATA, CRC } state = STX1; for (i = 0; i < len; ++i) { /* Make sure that we don't read more data than fits in the read buffer. * If too many bytes are read we reset the state machine and wait for * another message. */ if (idx >= sizeof(buf)) { state = STX1; idx = 0; } switch (state) { case STX1: if (data[i] == STX) { memset(&buf, 0, sizeof(buf)); buf[idx++] = data[i]; state = STX2; } break; case STX2: if (data[i] == STX) { buf[idx++] = data[i]; state = ADDR; } break; case ADDR: buf[idx++] = data[i]; seqno = (data[i] & 0xf0) >> 4; state = TYPE; break; case TYPE: buf[idx++] = data[i]; datactr = 0; state = DATA; break; case DATA: buf[idx++] = data[i]; if (++datactr == 4) state = CRC; break; case CRC: buf[idx++] = data[i]; crc8 = crc(buf, idx-1); if (crc8 == buf[idx-1]) { temp = (buf[4] << 8) | buf[5]; rh = (buf[6] << 8) | buf[7]; //printf("Temperature: %0.1f degC, RH = %0.1f%%\nSeqno = %u\n", (float)temp/10.0f, (float)rh/10.0f, seqno); t = time(NULL); tmp = localtime(&t); if (tmp != NULL) { strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", tmp); } /* Print the long-term log file */ snprintf(filename, PATH_MAX, "templog_%u.csv", buf[2] & 0x0f); templog = fopen(filename, "a+"); if (templog) { if (seqno != pseqno) { printf("%s: %02u: Temperature: %0.1f degC, RH = %0.1f%%, seqno = %u\n", timestr, buf[2] & 0x0f, (float)temp/10.0f, (float)rh/10.0f, seqno); fprintf(templog, "%s,%02u,%02u,%0.1f,%0.1f\n", timestr, buf[2] & 0x0f, seqno, (float)temp/10.0f, (float)rh/10.0f); fclose(templog); #ifdef USE_DATABASE snprintf(query, sizeof(query), "INSERT INTO templog VALUES(%u, '%s', %0.1f, %0.1f)", buf[2] & 0x0f, timestr, (float)temp/10.0f, (float)rh/10.0f); if (mysql_query(con, query)) printf("Failed to insert into database\n"); #endif pseqno = seqno; } } else { printf("Failed to open '%s' for writing data\n", filename); } /* Print the last known value to file in a format that Domoticz understands */ snprintf(filename, PATH_MAX, "temp_rh_current_%u.csv", buf[2] & 0x0f); templog = fopen(filename, "w+"); if (templog) { fprintf(templog, "%0.1f;%0.1f\n", (float)temp/10.0f, (float)rh/10.0f); fclose(templog); } else { printf("Failed to open '%s' for writing data. Errno = %d\n", filename, errno); } } else { printf("Message CRC failed\n"); } state = STX1; idx = 0; break; } } }
BOOL MemoryStatus(const char * strParas , char * szReturn, int &nSize) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); bool bRet = FALSE; CString strHost = _T(""); CString strUserName = _T(""); CString strPWD = _T(""); int nPort = 3306; //MySQL的默认端口号 MYSQL * mysql; //MySQL对象 MYSQL_RES * res; //MySQL记录集指针 MYSQL_ROW row; //MySQL行指针 CStringList strList; MakeStringListByChar(strList, strParas); POSITION pos=strList.GetHeadPosition(); while(pos) { CString strTemp=strList.GetNext(pos); if(strTemp.Find(__MACHINENAME__)==0) { strHost = strTemp.Right(strTemp.GetLength() - (int)strlen(__MACHINENAME__)); } else if(strTemp.Find(__USERACCOUNT__)==0) { strUserName = strTemp.Right(strTemp.GetLength() - (int)strlen(__USERACCOUNT__)); } else if(strTemp.Find(__PASSWORD__)==0) { strPWD = strTemp.Right(strTemp.GetLength() - (int)strlen(__PASSWORD__)); } else if(strTemp.Find(__PORT__)==0) { nPort = atoi(strTemp.Right(strTemp.GetLength() - (int)strlen(__PORT__))); } } if(strHost.IsEmpty()) { sprintf(szReturn,"error=%s$",FuncGetStringFromIDS("SV_MYSQL","MYSQL_SERVER_HOST_IS_NULL")); return FALSE; } if(nPort<=0) { sprintf(szReturn,"error=%s$",FuncGetStringFromIDS("SV_MYSQL","MYSQL_SERVER_PORT_IS_BAD")); return FALSE; } //////////////////////////////////////////////// int Innodb_page_size=0; //页大小(单位:字节) int Innodb_buffer_pool_pages_total =0; //缓冲池总大小(单位:页数) int Innodb_buffer_pool_pages_free = 0; //空页数(单位:页) int Innodb_buffer_pool_pages_data = 0; //包含数据的页(单位:页) int Innodb_buffer_pool_pages_dirty =0; //当前的脏页(单位:页),脏页是指该页包含尚未写磁盘的修改 int Innodb_buffer_pool_pages_latched = 0; //在InnoDB缓冲池中锁定的页数。这是当前正读或写或由于其它原因不能清空或删除的页数 unsigned int nCurrentID=0; //////////////////////////////////////////////// if((mysql = mysql_init((MYSQL *)NULL)) && mysql_real_connect(mysql, strHost, strUserName, strPWD, NULL, nPort, NULL, 0)) { mysql_query(mysql,"show status"); res = mysql_store_result(mysql); while(row = mysql_fetch_row(res)) { if(!strcmp(row[0], "Innodb_page_size")) { Innodb_page_size=atoi(row[1]); Innodb_page_size=Innodb_page_size/1024; //将页的单位从字节转化为Kb } else if(!strcmp(row[0], "Innodb_buffer_pool_pages_total")) { Innodb_buffer_pool_pages_total = atoi(row[1]); } else if(!strcmp(row[0], "Innodb_buffer_pool_pages_free")) { Innodb_buffer_pool_pages_free = atoi(row[1]); } else if(!strcmp(row[0], "Innodb_buffer_pool_pages_data")) { Innodb_buffer_pool_pages_data = atoi(row[1]); } else if(!strcmp(row[0], "Innodb_buffer_pool_pages_dirty")) { Innodb_buffer_pool_pages_dirty = atoi(row[1]); } else if(!strcmp(row[0], "Innodb_buffer_pool_pages_latched")) { Innodb_buffer_pool_pages_latched = atoi(row[1]); } } sprintf(szReturn,"PageSize=%d$TotalPages=%d$FreePages=%d$DataPages=%d$DirtyPages=%d$LatchedPages=%d$", Innodb_page_size, Innodb_buffer_pool_pages_total, Innodb_buffer_pool_pages_free, Innodb_buffer_pool_pages_data, Innodb_buffer_pool_pages_dirty, Innodb_buffer_pool_pages_latched); CString strInput ; strInput =szReturn; MakeCharByString(szReturn,nSize,strInput); mysql_free_result(res); bRet = TRUE; } else { sprintf(szReturn, "error=%s(%s:%d)$", FuncGetStringFromIDS("SV_MYSQL", "MYSQL_CONNECT_DATABASE_FAILED"), strHost, nPort); fprintf(stderr, "Failed to connect to database: Error: %s\n", mysql_error(mysql)); mysql_close( mysql ) ; return FALSE; } /* const char * strEnd = szReturn; while(*strEnd) { PrintLog(strEnd); strEnd+=strlen(strEnd)+1; } */ mysql_close(mysql); return TRUE; }
BOOL SlaveStatus(const char * strParas , char * szReturn, int &nSize) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); bool bRet = false; CString strHost = _T(""); CString strUserName = _T(""); CString strPWD = _T(""); int nPort = 3306; MYSQL_RES * res; //MYSQL数据库的记录集指针 MYSQL_ROW row; MYSQL *mysql; //接收MySQL数据的对象 CStringList paramList; MakeStringListByChar(paramList, strParas); POSITION pos = paramList.GetHeadPosition(); while(pos) { CString strTemp = paramList.GetNext(pos); if(strTemp.Find(__MACHINENAME__, 0)==0) { strHost = strTemp.Right(strTemp.GetLength() - (int)strlen(__MACHINENAME__)); } else if(strTemp.Find(__PORT__, 0)==0) { nPort = atoi(strTemp.Right(strTemp.GetLength() - (int)strlen(__PORT__))); } else if(strTemp.Find(__USERACCOUNT__ , 0)==0) { strUserName = strTemp.Right(strTemp.GetLength() - (int)strlen(__USERACCOUNT__)); } else if(strTemp.Find(__PASSWORD__ , 0)==0) { strPWD = strTemp.Right(strTemp.GetLength() - (int)strlen(__PASSWORD__)); } } if(strHost.IsEmpty()) { sprintf(szReturn,"error=%s",FuncGetStringFromIDS("SV_MYSQL","MYSQL_SERVER_HOST_IS_NULL")); return false; } if(nPort<=0) { sprintf(szReturn,"error=%s",FuncGetStringFromIDS("SV_MYSQL","MYSQL_SERVER_PORT_IS_BAD")); return false; } unsigned int i=0; CString strTMP = _T(""); ////////////////////////////////////////////////// CString strSlaveIOState = _T(""); CString strMasterHost = _T(""); CString strMasterUser = _T(""); CString strSlaveIORunning = _T(""); //Slave是否在运行 CString strSlaveSQLRunning = _T(""); int nMasterPort = 3306; CString strSecondsBehindMaster = _T(""); //最后一次同步时间 ////////////////////////////////////////////////// if((mysql = mysql_init((MYSQL *)NULL)) && mysql_real_connect(mysql,strHost, strUserName, strPWD, NULL, nPort, NULL, 0)) { mysql_query(mysql, "show slave status"); res = mysql_store_result(mysql); while(row = mysql_fetch_row(res)) { /* PrintLog(row[1]); PrintLog(row[2]); PrintLog(row[3]); for (i=0; i<mysql_num_fields(res); i++) { PrintLog(row[i]); } */ strSlaveIOState = row[0]; strMasterHost = row[1]; strMasterUser = row[2]; nMasterPort = atoi(row[3]); strSlaveIORunning =row[10]; strSlaveSQLRunning = row[11]; strSecondsBehindMaster = row[32]; } if(strSlaveIOState.IsEmpty()) strSlaveIOState="null"; if(strMasterHost.IsEmpty()) strMasterHost="null"; if(strMasterUser.IsEmpty()) strMasterUser="******"; if(strSlaveIORunning.IsEmpty()) strSlaveIORunning="null"; sprintf(szReturn,"SlaveIOState=%s$MasterHost=%s$MasterUser=%s$MasterPort=%d$SlaveIORunning=%s$SlaveSQLRunning=%s$SecondsBehindMaster=%s$", strSlaveIOState.GetBuffer(1), strMasterHost.GetBuffer(1), strMasterUser.GetBuffer(1), nMasterPort, strSlaveIORunning.GetBuffer(1), strSlaveSQLRunning.GetBuffer(1), strSecondsBehindMaster.GetBuffer(1)); CString strInput ; strInput =szReturn; MakeCharByString(szReturn,nSize,strInput); mysql_free_result(res); bRet = TRUE; } else { sprintf(szReturn, "error=%s(%s:%d)$", FuncGetStringFromIDS("SV_MYSQL", "MYSQL_CONNECT_DATABASE_FAILED"), strHost, nPort); fprintf(stderr, "Failed to connect to database: Error: %s\n", mysql_error(mysql)); mysql_close( mysql ) ; return FALSE; } mysql_close(mysql); /* char * strEnd = szReturn; while(*strEnd) { PrintLog(strEnd); strEnd+=strlen(strEnd)+1; } */ return bRet; }
BOOL ProInfo(const char * strParas , char * szReturn , int &nSize) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); bool bRet = false; CString strHost = _T(""); CString strUserName = _T(""); CString strPWD = _T(""); int nProID=0; //保存传进来的进程ID号 int nPort = 3306; //MySQL的默认端口号是3306 MYSQL_RES * res; //MYSQL数据库的记录集指针 MYSQL_ROW row; MYSQL *mysql; //接收MySQL数据的对象 CStringList paramList; MakeStringListByChar(paramList, strParas); POSITION pos = paramList.GetHeadPosition(); while(pos) { CString strTemp = paramList.GetNext(pos); if(strTemp.Find(__MACHINENAME__, 0)==0) { strHost = strTemp.Right(strTemp.GetLength() - (int)strlen(__MACHINENAME__)); } else if(strTemp.Find(__PORT__, 0)==0) { nPort = atoi(strTemp.Right(strTemp.GetLength() - (int)strlen(__PORT__))); } else if(strTemp.Find(__USERACCOUNT__ , 0)==0) { strUserName = strTemp.Right(strTemp.GetLength() - (int)strlen(__USERACCOUNT__)); } else if(strTemp.Find(__PASSWORD__ , 0)==0) { strPWD = strTemp.Right(strTemp.GetLength() - (int)strlen(__PASSWORD__)); } else if(strTemp.Find(__PROID__, 0)==0) { nProID = atoi(strTemp.Right(strTemp.GetLength() - (int)strlen(__PROID__))); } } if(strHost.IsEmpty()) { sprintf(szReturn,"error = %s",FuncGetStringFromIDS("SV_MYSQL","MYSQL_SERVER_HOST_IS_NULL")); return false; } if(nPort<=0) { sprintf(szReturn,"error = %s",FuncGetStringFromIDS("SV_MYSQL","MYSQL_SERVER_PORT_IS_BAD")); return false; } unsigned int i=0; CString strTMP = _T(""); ////////////////////////////////////////////////// int nID = 0; //MYSQL线程标识,你要kill一个语句的时候很有用 CString strDBUser = _T(""); //user列,显示当前用户,如果不是root,这个命令就只显示你权限范围内的sql语句 CString strDBHost = _T(""); //host列,显示这个语句是从哪个ip的哪个端口上发出的 CString strDatabase = _T(""); //db列,显示这个进程目前连接的是哪个数据库 CString strCommand = _T(""); //command列,显示当前连接的执行的命令,一般就是休眠(sleep),查询(query),连接(connect)。 int nTime = 0; //time列,此这个状态持续的时间,单位是秒 CString strState = _T(""); //state列,显示使用当前连接的sql语句的状态 CString strInfo = _T(""); //info列,显示这个sql语句,因为长度有限,所以长的sql语句就显示不全 unsigned long nCurrentID = 0; //当前线程ID int nTotalConn=0; //连接总数 map<CString,int> hostMap; map<CString,int>::const_iterator ptrHost; typedef pair <CString,int> hostPair; ////////////////////////////////////////////////// if((mysql = mysql_init((MYSQL *)NULL)) && mysql_real_connect(mysql,strHost, strUserName, strPWD, NULL, nPort, NULL, 0)) { // res = mysql_list_processes(mysql); CString strCommand=_T(""); mysql_query(mysql,"show processlist"); res = mysql_store_result(mysql); nCurrentID = mysql_thread_id(mysql); //获取当前线程ID strCommand.Format("kill %d",nCurrentID); while(row = mysql_fetch_row(res)) { nID = atoi(row[0]); strDBUser = row[1]; strDBHost = row[2]; strDatabase = row[3]; strCommand = row[4]; nTime = atoi(row[5]); strState = row[6]; strInfo = row[7]; strDBHost=strDBHost.Left(strDBHost.Find(':')); //擦掉获得的主机端口号 ptrHost = hostMap.find(strDBHost.GetBuffer(strDBHost.GetLength())); if(nID!=nCurrentID) { if(ptrHost==hostMap.end()) { hostMap.insert(hostPair(strDBHost.GetBuffer(strDBHost.GetLength()),1)); } //用MAP保存主机名,并且将主机出现次数统计在键值中 else { hostMap[strDBHost.GetBuffer(strDBHost.GetLength())]++; } } /* else { PrintLog(row[0]); PrintLog(row[2]); } */ nTotalConn++; } nTotalConn=nTotalConn-1; //减去自身的连接 for(ptrHost=hostMap.begin();ptrHost!=hostMap.end();ptrHost++) { strTMP.Format("%s%s的连接数是%d,",strTMP.GetBuffer(strTMP.GetLength()),ptrHost->first,ptrHost->second); } strTMP.Delete(strTMP.GetLength()-1,1); //去除返回值后多余的一个“,” sprintf(szReturn,"nTotalConn=%d$result=%s",nTotalConn,strTMP.GetBuffer(strTMP.GetLength())); CString strInput ; strInput =szReturn; MakeCharByString(szReturn,nSize,strInput); mysql_free_result(res); //释放结果集使用的内存。 mysql_close(mysql); // 关闭服务器连接。 bRet = TRUE; } else { sprintf(szReturn, "error=%s(%s:%d)$", FuncGetStringFromIDS("SV_MYSQL", "MYSQL_CONNECT_DATABASE_FAILED"), strHost, nPort); fprintf(stderr, "Failed to connect to database: Error: %s\n", mysql_error(mysql)); mysql_close( mysql ) ; return FALSE; } /* const char * strEnd=szReturn; while(*strEnd) { PrintLog(strEnd); strEnd+=strlen(strEnd)+1; } */ return bRet; }
void CManageMySQL::Getname(CString str,int classcount) { int i = classcount + Page * 14; for (int i = 13;i >= 0;i--) { CWnd* DlgHwnd = GetDlgItem(IDC_BUTTON1 + i); DlgHwnd->SetWindowText(_T("")); DlgHwnd->ShowWindow(SW_HIDE); }//隐藏Button GetDlgItem(IDC_BUTTON15)->ShowWindow(SW_HIDE); GetDlgItem(IDC_BUTTON16)->ShowWindow(SW_HIDE); mysql_set_character_set(&my_connection, "gbk"); int res; mysql_query(&my_connection, "use student"); char query1[] = { "SELECT * FROM `message` where (`Grade`=\"" }; char query2[] = { "\" and `Class`='" }; char query3[] = { "')" }; char *ch = (LPSTR)(LPCTSTR)GradeName; char *classname = (LPSTR)(LPCTSTR)str; char query[200]; sprintf(query, "%s%s%s%s%s", query1, ch, query2, classname, query3); res = mysql_query(&my_connection, query); MYSQL_RES *result = mysql_store_result(&my_connection); char** sql_row = mysql_fetch_row(result); for (StudentCount = 0;sql_row != NULL; StudentCount++) { CString str; str.Format(_T("%s"), sql_row[5]); NameTemp[StudentCount] = str; sql_row = mysql_fetch_row(result); //free(result); } if (StudentCount >= 1) { if (StudentCount <= 14) { for (int f = 0;f <= i;f++) { CWnd* DlgHwnd = GetDlgItem(IDC_BUTTON1 + f); DlgHwnd->SetWindowText(NameTemp[f]); DlgHwnd->ShowWindow(SW_SHOW); } } else { for (int f = 0;f <= 13;f++) { CWnd* DlgHwnd = GetDlgItem(IDC_BUTTON1 + f); DlgHwnd->SetWindowText(NameTemp[f]); DlgHwnd->ShowWindow(SW_SHOW); } CString str; str.Format(_T("下一页")); CWnd* DlgHwnd = GetDlgItem(IDC_BUTTON16); DlgHwnd->SetWindowText(str); DlgHwnd->ShowWindow(SW_SHOW); Page = 0; } } DataGuide = 2; }
//8.更新用户信息 //@ domain ... //@ json_UserInfo 要插入用户的信息。 ret_s ldapInfoDB::updateLdapUserInfo(in string json_UserInfo){ //解析json vector<User_json> UserNodes; praseJsonUSer(UserNodes,json_UserInfo); if(UserNodes.size() > 1){ return 66;// 同组类似问题。 } User_json UserNode = UserNodes[0]; int fieldNum,rowNum; int res; MYSQL_RES * my_res; MYSQL_ROW my_row; MYSQL_FIELD *fd; char column[32][32]; checksql(); sprintf(_sql,"select * from EmailUser where id = %d;",UserNode.user_id); res = mysql_query(_my_con,_sql);//查询没有才能插入 if(!res){ my_res = mysql_store_result(_my_con); if(my_res){ rowNum = mysql_num_rows(my_res); if(rowNum == 0){ //不存在便插入。 checksql(); sprintf(_sql,"insert into EmailUser(email, passwd, is_staff, is_active, ctime) value('%s', '%s', %d, %d, %ld);",UserNode.email.c_str(),UserNode.password.c_str(),UserNode.is_staff,UserNode.is_active,UserNode.ctime); res = mysql_query(_my_con, _sql); if(!res){ //插入有问题。 } checksql(); sprintf(_sql,"insert into UserRole(email, role) value('%s', 'default');",UserNode.email.c_str()); res = mysql_query(_my_con, _sql); if(!res){ //插入有问题。 } checksql(); sprintf(_sql,"insert into UserJur(email, jurisdiction) value('%s', %d);",UserNode.email.c_str(),UserNode.jurisdiction); res = mysql_query(_my_con, _sql); if(!res){ //插入有问题。 } }else{ //存在便更新 checksql(); sprintf(_sql,"update EmailUser set email = '%s', passwd = '%s', is_staff = '%d', is_active = '%d', ctime = '%ld' where id = %d;",UserNode.email.c_str(),UserNode.password.c_str(),UserNode.is_staff,UserNode.is_active,UserNode.ctime,UserNode.user_id); res = mysql_query(_my_con, _sql); if(!res){ //插入有问题。 } checksql(); sprintf(_sql,"update UserRole set role = '%s' where email = '%s';","default",UserNode.email.c_str()); res = mysql_query(_my_con, _sql); if(!res){ //插入有问题。 } checksql(); sprintf(_sql,"update UserJur set jurisdiction = %d where email = '%s';",UserNode.jurisdiction,UserNode.email.c_str()); res = mysql_query(_my_con, _sql); if(!res){ //插入有问题。 } } } mysql_free_result(my_res); } return 0; }
void CManageMySQL::GetClass(CString str) { GradeName = str; for (int i = GradeCount;i >= 0;i--) { CWnd* DlgHwnd = GetDlgItem(IDC_BUTTON1 + i); DlgHwnd->SetWindowText(_T("")); DlgHwnd->ShowWindow(SW_HIDE); }//隐藏Button mysql_set_character_set(&my_connection, "gbk"); int res; mysql_query(&my_connection, "use student"); char query1[200] = { "SELECT * FROM `index` where (`Session`=\"" }; char query2[200] = { "\")" }; char *ch = (LPSTR)(LPCTSTR)str; char query[200]; sprintf(query, "%s%s%s", query1, ch, query2); res = mysql_query(&my_connection, query); MYSQL_RES *result = mysql_store_result(&my_connection); char** sql_row = mysql_fetch_row(result); CString strc; strc.Format(_T("%s"), sql_row[1]); int i = _ttoi(strc); if (i >= 1) { if (i <= 14) { for (int f = 0;f <= i;f++) { CString str; str.Format(_T("%d班"), f + 1); CWnd* DlgHwnd = GetDlgItem(IDC_BUTTON1 + f); DlgHwnd->SetWindowText(str); DlgHwnd->ShowWindow(SW_SHOW); } } else { for (int f = 0;f <= 13;f++) { CString str; str.Format(_T("%d班"), f + 1); CWnd* DlgHwnd = GetDlgItem(IDC_BUTTON1 + f); DlgHwnd->SetWindowText(str); DlgHwnd->ShowWindow(SW_SHOW); } CString str; str.Format(_T("下一页")); CWnd* DlgHwnd = GetDlgItem(IDC_BUTTON16); DlgHwnd->SetWindowText(str); DlgHwnd->ShowWindow(SW_SHOW); Page = 0; AllPageThings = i; } } DataGuide = 1; }
static JSVAL query(JSARGS args) { HandleScope scope; MYSQL *handle = (MYSQL *) args[0]->IntegerValue(); String::Utf8Value sql(args[1]->ToString()); return scope.Close(Integer::New((unsigned long)mysql_query(handle, *sql))); }
/** * Returns the id of the exporter table entry or 0 in the case of an error */ int IpfixDbWriter::getExporterID(const IpfixRecord::SourceID& sourceID) { list<ExporterCacheEntry>::iterator iter; MYSQL_RES* dbResult; MYSQL_ROW dbRow; int id = 0; uint32_t expIp = 0; ostringstream statement; iter = exporterCache.begin(); while(iter != exporterCache.end()) { if (equalExporter(iter->sourceID, sourceID)) { // found exporter in exporterCache DPRINTF("Exporter (ODID=%d, id=%d) found in exporter cache", sourceID.observationDomainId, iter->id); exporterCache.push_front(*iter); exporterCache.erase(iter); // update current exporter currentExporter = &exporterCache.front(); return exporterCache.front().id; } iter++; } // convert IP address if(sourceID.exporterAddress.len == 4) expIp = *(uint32_t*)(sourceID.exporterAddress.ip); // search exporter table statement << "SELECT id FROM exporter WHERE sourceID=" << sourceID.observationDomainId << " AND srcIp=" << expIp; DPRINTF("SQL Query: %s", statement.str().c_str()); if(mysql_query(conn, statement.str().c_str()) != 0) { msg(MSG_ERROR,"IpfixDbWriter: Select on exporter table failed. Error: %s", mysql_error(conn)); return 0;// If a failure occurs, return 0 } dbResult = mysql_store_result(conn); if(( dbRow = mysql_fetch_row(dbResult))) { // found in table id = atoi(dbRow[0]); mysql_free_result(dbResult); DPRINTF("ExporterID %d is in exporter table", id); } else { mysql_free_result(dbResult); // insert new exporter table entry statement.str(""); statement.clear(); statement << "INSERT INTO exporter (ID,sourceID,srcIP) VALUES ('NULL','" << sourceID.observationDomainId << "','" << expIp << "')"; DPRINTF("SQL Query: %s", statement.str().c_str()); if(mysql_query(conn, statement.str().c_str()) != 0) { msg(MSG_ERROR,"IpfixDbWriter: Insert in exporter table failed. Error: %s", conn); return 0; } id = mysql_insert_id(conn); msg(MSG_INFO,"IpfixDbWriter: new exporter (ODID=%d, id=%d) inserted in exporter table", sourceID.observationDomainId, id); } // insert exporter in cache ExporterCacheEntry tmp = {sourceID, id}; exporterCache.push_front(tmp); // update current exporter currentExporter = &exporterCache.front(); // pop last element if exporter cache is to long if(exporterCache.size() > MAX_EXPORTER) exporterCache.pop_back(); return id; }
static JSVAL getDataRowsJson(JSARGS args) { HandleScope scope; // MYSQL *handle = (MYSQL *) args[0]->IntegerValue(); String::Utf8Value sql(args[0]); mysql_ping(handle); // printf("%d %s\n", mysql_ping(handle), mysql_error(handle)); int failure = mysql_query(handle, *sql); if (failure) { return scope.Close(False()); } MYSQL_RES *result = mysql_store_result(handle); if (!result) { return scope.Close(False()); } int num_fields = mysql_num_fields(result); MYSQL_FIELD *fields = mysql_fetch_fields(result); int types[num_fields]; char *names[num_fields]; for (int n = 0; n < num_fields; n++) { // names[n] = String::New(fields[n].name); types[n] = fields[n].type; names[n] = fields[n].name; } string json = "[";; unsigned long rowNdx = 0; MYSQL_ROW row; while ((row = mysql_fetch_row(result))) { if (rowNdx++) { json += ","; } json += "{"; for (int i = 0; i < num_fields; i++) { if (i) { json += ","; } if (row[i] == NULL) { json += "\""; json += names[i]; json += "\":null"; } else { switch (types[i]) { case MYSQL_TYPE_NULL: json += "\""; json += names[i]; json += "\":null"; break; case MYSQL_TYPE_TINY: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONG: case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_LONGLONG: case MYSQL_TYPE_INT24: json += "\"" ; json += names[i]; json += "\":"; json += row[i]; break; default: json += "\""; json += names[i]; json += "\":\""; json += row[i]; json += "\""; // break; } } } json += "}"; // printf("%s\n", json.c_str()); } json += "]"; mysql_free_result(result); // for (int i=0; i<num_fields; i++) { // delete[] names[i]; // } // printf("%s\n", json.c_str()); // printf("%s\n", json.GetBuffer()); return scope.Close(String::New(json.c_str(), json.size())); }
MYSQL * STDCALL mysql_real_connect(MYSQL *mysql,const char *host, const char *user, const char *passwd, const char *db, uint port, const char *unix_socket,ulong client_flag) { char name_buff[USERNAME_LENGTH]; DBUG_ENTER("mysql_real_connect"); DBUG_PRINT("enter",("host: %s db: %s user: %s (libmysqld)", host ? host : "(Null)", db ? db : "(Null)", user ? user : "******")); /* Test whether we're already connected */ if (mysql->server_version) { set_mysql_error(mysql, CR_ALREADY_CONNECTED, unknown_sqlstate); DBUG_RETURN(0); } if (!host || !host[0]) host= mysql->options.host; if (mysql->options.methods_to_use == MYSQL_OPT_USE_REMOTE_CONNECTION || (mysql->options.methods_to_use == MYSQL_OPT_GUESS_CONNECTION && host && *host && strcmp(host,LOCAL_HOST))) DBUG_RETURN(cli_mysql_real_connect(mysql, host, user, passwd, db, port, unix_socket, client_flag)); mysql->methods= &embedded_methods; /* use default options */ if (mysql->options.my_cnf_file || mysql->options.my_cnf_group) { mysql_read_default_options(&mysql->options, (mysql->options.my_cnf_file ? mysql->options.my_cnf_file : "my"), mysql->options.my_cnf_group); my_free(mysql->options.my_cnf_file); my_free(mysql->options.my_cnf_group); mysql->options.my_cnf_file=mysql->options.my_cnf_group=0; } if (!db || !db[0]) db=mysql->options.db; if (!user || !user[0]) user=mysql->options.user; #ifndef NO_EMBEDDED_ACCESS_CHECKS if (!passwd) { passwd=mysql->options.password; #if !defined(DONT_USE_MYSQL_PWD) if (!passwd) passwd=getenv("MYSQL_PWD"); /* get it from environment */ #endif } mysql->passwd= passwd ? my_strdup(passwd,MYF(0)) : NULL; #endif /*!NO_EMBEDDED_ACCESS_CHECKS*/ if (!user || !user[0]) { read_user_name(name_buff); if (name_buff[0]) user= name_buff; } if (!user) user= ""; /* We need to alloc some space for mysql->info but don't want to put extra 'my_free's in mysql_close. So we alloc it with the 'user' string to be freed at once */ mysql->user= my_strdup(user, MYF(0)); port=0; unix_socket=0; client_flag|=mysql->options.client_flag; /* Send client information for access check */ client_flag|=CLIENT_CAPABILITIES; if (client_flag & CLIENT_MULTI_STATEMENTS) client_flag|= CLIENT_MULTI_RESULTS; /* no compression in embedded as we don't send any data, and no pluggable auth, as we cannot do a client-server dialog */ client_flag&= ~(CLIENT_COMPRESS | CLIENT_PLUGIN_AUTH); if (db) client_flag|=CLIENT_CONNECT_WITH_DB; mysql->info_buffer= my_malloc(MYSQL_ERRMSG_SIZE, MYF(0)); mysql->thd= create_embedded_thd(client_flag); init_embedded_mysql(mysql, client_flag); if (mysql_init_character_set(mysql)) goto error; if (check_embedded_connection(mysql, db)) goto error; mysql->server_status= SERVER_STATUS_AUTOCOMMIT; if (mysql->options.init_commands) { DYNAMIC_ARRAY *init_commands= mysql->options.init_commands; char **ptr= (char**)init_commands->buffer; char **end= ptr + init_commands->elements; for (; ptr<end; ptr++) { MYSQL_RES *res; if (mysql_query(mysql,*ptr)) goto error; if (mysql->fields) { if (!(res= (*mysql->methods->use_result)(mysql))) goto error; mysql_free_result(res); } } } DBUG_PRINT("exit",("Mysql handler: 0x%lx", (long) mysql)); DBUG_RETURN(mysql); error: DBUG_PRINT("error",("message: %u (%s)", mysql->net.last_errno, mysql->net.last_error)); { /* Free alloced memory */ my_bool free_me=mysql->free_me; free_old_query(mysql); mysql->free_me=0; mysql_close(mysql); mysql->free_me=free_me; } DBUG_RETURN(0); }
void database::execute_1( std::string query, std::vector <std::vector <std::string>>& result_set, std::vector <std::vector<bool>> *null_fields_ptr, unsigned int& num_rows, unsigned int& num_cols, MYSQL_RES *&result) { MYSQL_ROW row; // We need to be connected to a database to continue. if (!db_connected) throw std::runtime_error("No database connection"); // Execute the SQL query. if (mysql_query(db_connection, query.c_str()) != 0) throw std::runtime_error(mysql_error(db_connection)); // If the query produced a result set, then num_cols will be non-zero. num_cols = mysql_field_count(db_connection); if (num_cols == 0) { // No result set was sent from the database server, but that is what should happen for // most non-SELECT queries that alter the database (such as INSERT, UPDATE, DELETE). // In this case, set num_rows to the number of rows that were changed (affected). num_rows = (unsigned int) mysql_affected_rows(db_connection); } else { // Get the result set from the database server. result = mysql_store_result(db_connection); if (result == NULL) throw std::runtime_error(mysql_error(db_connection)); // Get the number of rows in the result set. num_rows = (int)mysql_num_rows(result); // If there are no rows in the result set, then just return. if (num_rows == 0) return; // Resize the data arrays to hold the correct number of rows. if (null_fields_ptr != nullptr) (*null_fields_ptr).resize(num_rows); result_set.resize(num_rows); // Copy the data in the result set to where it should go. for (unsigned int i = 0; i < num_rows; i++) { // Get one row of data from the result set. row = mysql_fetch_row(result); if (row == NULL) throw std::runtime_error(mysql_error(db_connection)); // Resize the data arrays to hold the correct number of columns. if (null_fields_ptr != nullptr) (*null_fields_ptr)[i].resize(num_cols); result_set[i].resize(num_cols); // Copy the data to the final location. for (unsigned int j = 0; j < num_cols; j++) { if (row[j] == nullptr) { if (null_fields_ptr != nullptr) (*null_fields_ptr)[i][j] = true; } else { if (null_fields_ptr != nullptr) (*null_fields_ptr)[i][j] = false; result_set[i][j] = row[j]; } } } } }
int main(int argc, char *argv[], char *envp[]) { int i; int res; int status; const char *userp = getenv("USER"); /* vem är inloggad? */ char databas[25]="olfix"; char usr[21]; /* userid 20070214 utökat från 15 till 21 tecken */ /* for(i=0;i<=argc;i++){ fprintf(stderr,"argv[%d]=%s\n",i,argv[i]); } */ char temp1a[]="SELECT KTONR, BENAMNING FROM KTOPLAN WHERE ARID=\""; char temp1b[]=" ORDER BY KTONR"; char temp2[]="\""; char temp5[200]=""; char arid[3]=""; /* ================================================================================ */ /* Val av databas, START */ /* ================================================================================ */ status = which_database(envp); if (status != 0) exit(status); strncpy(usr,userp,sizeof(usr)); /* Den inloggades userid 20070214 */ /* fprintf(stderr,"status=%d ANTARG=%d len(database)=%d\n",status,ANTARG,strlen(database)); */ if (argc < ANTARG+1){ if (strlen(database)!= 0){ strncpy(databas,database,15); }else{ strncpy(databas,"olfixtst",15); /* olfixtst = testföretag */ } }else{ if (strlen(argv[ANTARG]) != 0){ if (strncmp(argv[ANTARG],"99",2)==0){ strncpy(databas,"olfixtst",15); }else{ strncpy(databas,argv[ANTARG],15); } } } /* fprintf(stderr,"ANTARG=%d,argv[ANTARG]=%s\n",ANTARG,argv[ANTARG]); */ /* Om usr (userid) börjar på 'test' eller 'prov' använd databas 'olfixtst' */ if (strncmp(usr,"test",4)==0 || strncmp(usr,"prov",4)==0 ) { strncpy(databas,"olfixtst",15); } /* fprintf(stderr,"Databas=%s\n",databas); */ /* ================================================================================ */ /* Val av databas, END! */ /* ================================================================================ */ if (argv[1] != NULL){ strncpy(arid,argv[1],sizeof(arid)); /* 2005-02-24 */ } else{ fprintf(stderr,"Error: KTOVIEW ARID Ange årtal!\n"); exit(-1); } strncpy(temp5,temp1a,strlen(temp1a)); /* SELECT KTONR, BENAMNING FROM KTOPLAN WHERA ARID=" */ strncat(temp5,arid,strlen(arid)); /* 2002 */ /* SELECT KTONR, BENAMNING FROM KTOPLAN WHERA ARID="2002 */ strncat(temp5,temp2,strlen(temp2)); /* " */ /* SELECT KTONR, BENAMNING FROM KTOPLAN WHERA ARID="2002" */ strncat(temp5,temp1b,strlen(temp1b)); /* SELECT KTONR, BENAMNING FROM KTOPLAN WHERA ARID="2002" ORDER BY KTONR */ // fprintf(stderr,"KTOVIEWmain: temp5 = %s\n",temp5); mysql_init(&my_connection); if (mysql_real_connect(&my_connection, "localhost", "olfix", "olfix", databas, 0, NULL, 0)){ /* fprintf(stderr,"KTOVIEW:Connection success\n"); */ res = mysql_query(&my_connection,temp5); if (res){ fprintf(stderr,"Error: KTOVIEW SELECT error: %s\n",mysql_error(&my_connection)); }else{ res_ptr=mysql_store_result(&my_connection); if (res_ptr){ i=1; /* fprintf(stderr,"KTOVIEW:Retrieved %lu rows\n",(unsigned long)mysql_num_rows(res_ptr)); */ if ( (unsigned long)mysql_num_rows(res_ptr) > 0){ fprintf(stdout,"NR_%lu_:",(unsigned long)mysql_num_rows(res_ptr)); while ((sqlrow=mysql_fetch_row(res_ptr))) { /* fprintf(stderr,"KTOVIEW:Fetched data....}"); */ display_row(); i++; } }else{ if ((unsigned long)mysql_num_rows(res_ptr) == 0){ fprintf(stdout,"VARNING: KTOVIEW. Det finns inga poster!\n"); }else{ fprintf(stderr,"Error: KTOVIEW Felaktigt årtal!\n"); } } if (mysql_errno(&my_connection)) { fprintf(stderr,"Error: KTOVIEW Retriev error: %s\n", mysql_error(&my_connection)); } } mysql_free_result(res_ptr); } mysql_close(&my_connection); } else { fprintf(stderr,"Error: KTOVIEW Connection failed\n"); if (mysql_errno(&my_connection)) { fprintf(stderr,"Error: KTOVIEW Connection error %d: %s\n", mysql_errno(&my_connection), mysql_error(&my_connection)); } } fprintf(stdout,"\n"); return EXIT_SUCCESS; }
//---------------------------------------------------------------------- //!\brief On affecte chaque jour du planning avec les paramètres caractéristiques du type de jour et saison //!\return 1 si erreur, 0 sinon //---------------------------------------------------------------------- int affectation_jour_planning(void){ //pour chaque jour de l'année, défini par un l'Id=1 à l'Id=nNbJour (365) for(stJourTraite.nIdJour = 1; stJourTraite.nIdJour <= nNbJour ; stJourTraite.nIdJour++){ //récupérer le type de jour et saison recup_info_jour(stJourTraite.nIdJour); //A partir de la saison , on récupére la température de chauffe read_consigne_chauffe(stJourTraite.inf_saison); unsigned int nPrio = 1; // Maintenant, on va traiter chaque créneau de chauffe du type de jour , puis remplir la table planning en conséquence (température de consigne à mettre à jour dans les créneau concernés) // Preparation de la requete MySQL // on ne récupère que les infos du jour en cours sprintf(query, "SELECT `heure_debut`, `heure_fin`, `priorite` FROM `calendrier_type_jour` WHERE `type_jour` = '%s'", stJourTraite.inf_type_jour); // envoi de la requete printf("\n\nEnvoi de la requete : %s", query); if (mysql_query(conn, query)) { // si la requete echoue on retourne 1 fprintf(stderr, "%s\n", mysql_error(conn)); return(1); } // la requête s'est bien passée, on rend le jeu de résultats disponible via le pointeur result printf("\nRecuperation des donnees pour le type de jour"); result = mysql_store_result(conn); while ((row = mysql_fetch_row(result))) { // on stocke la taille dans le pointeur lengths = mysql_fetch_lengths(result); // on récupère l'heure de début du créneau de l'action a effectuer sprintf(stJourTraite.stheure_debut,"%.*s", (char) lengths[ROW_HEURE_DEBUT], row[ROW_HEURE_DEBUT]); // on récupère l'heure de fin du créneau de l'action a effectuer sprintf(stJourTraite.stheure_fin,"%.*s", (char) lengths[ROW_HEURE_FIN], row[ROW_HEURE_FIN]); // on récupère la priorité sprintf(stJourTraite.stheure_priorite,"%.*s", (char) lengths[ROW_PRIORITE], row[ROW_PRIORITE]); // send SQL query // Exemple , ajout condition AND addtime( `date` , `heure_fin` ) > addtime( `date` , `heure_debut` ) pour éviter que le créneau 23:30:00 - 00:00:00 soit compté (minuit étant plus petit que 23:30, on écrirait une consigne de température!) // SELECT `id` , `date` , `heure_debut` , `heure_fin` // FROM `calendrier_30min` // WHERE `date` = '2012-11-05' // AND `heure_debut` >= '18:00:00' // AND `heure_fin` <= '22:00:00' // AND addtime( `date` , `heure_fin` ) > addtime( `date` , `heure_debut` ) sprintf(query, "SELECT `id` FROM `calendrier_30min` WHERE `date` = FROM_UNIXTIME( %d, '%%Y-%%m-%%d' ) AND `heure_debut` >= '%s' AND `heure_fin` <= '%s' AND addtime( `date` , `heure_fin` ) > addtime( `date` , `heure_debut` );", stJourTraite.nUnixTime, stJourTraite.stheure_debut, stJourTraite.stheure_fin); // envoi de la requete printf("\nEnvoi de la requete : %s", query); if (mysql_query(conn, query)) { // si la requete echoue on retourne 1 fprintf(stderr, "%s\n", mysql_error(conn)); return(1); } // la requête s'est bien passée, on rend le jeu de résultats disponible via le pointeur result2 printf("\nRecuperation de l'id pour le creneau"); result2 = mysql_store_result(conn); unsigned int nIdCreneau = 0; while ((row2 = mysql_fetch_row(result2))) { // on récupère l'id du créneau horaire nIdCreneau = atoi(row2[0]); // send SQL query sprintf(query, "UPDATE `domotique`.`calendrier_30min` SET `temperature` = '%.1f', `priorite` = '%d' WHERE `calendrier_30min`.`id` = %d;", stJourTraite.fconsigne_temperature, nPrio, nIdCreneau); printf("\n\nMise à jour de la temperature pour l'id : %s", query); if (mysql_query(conn, query)) { fprintf(stderr, "%s\n", mysql_error(conn)); return(1); } } // on libère la requête mysql_free_result(result2); nPrio++; } // on libère la requête mysql_free_result(result); } //l'affectation s'est bien passé, on retourne 0 return(0); }
int oph_odb_get_uncompleted_job_number(int parent_idjob, int *number, ophidiadb * oDB) { if (!oDB || !number) { pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Null input parameter\n"); return OPH_ODB_NULL_PARAM; } *number = 0; if (oph_odb_check_connection_to_ophidiadb(oDB)) { pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Unable to reconnect to OphidiaDB.\n"); return OPH_ODB_MYSQL_ERROR; } char query[MYSQL_BUFLEN]; int n = snprintf(query, MYSQL_BUFLEN, MYSQL_RETRIEVE_UNCOMPLETED_JOB_NUMBER, parent_idjob); if (n >= MYSQL_BUFLEN) { pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Size of query exceed query limit.\n"); return OPH_ODB_STR_BUFF_OVERFLOW; } pmesg_safe(&global_flag, LOG_DEBUG, __FILE__, __LINE__, "Extract number of pending children using: %s.\n", query); if (mysql_query(oDB->conn, query)) { pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "MySQL query error: %s\n", mysql_error(oDB->conn)); return OPH_ODB_MYSQL_ERROR; } MYSQL_RES *res; MYSQL_ROW row; res = mysql_store_result(oDB->conn); if (mysql_num_rows(res) < 1) { pmesg_safe(&global_flag, LOG_DEBUG, __FILE__, __LINE__, "No row found by query\n"); mysql_free_result(res); return OPH_ODB_NO_ROW_FOUND; } if (mysql_num_rows(res) > 1) { pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "More than one row found by query\n"); mysql_free_result(res); return OPH_ODB_TOO_MANY_ROWS; } if (mysql_field_count(oDB->conn) != 1) { pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Not enough fields found by query\n"); mysql_free_result(res); return OPH_ODB_TOO_MANY_ROWS; } if ((row = mysql_fetch_row(res)) != NULL) { if (!row[0]) { pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "No parent job found\n"); mysql_free_result(res); return OPH_ODB_ERROR; } *number = (int) strtol(row[0], NULL, 10); } mysql_free_result(res); return OPH_ODB_SUCCESS; }
/** * Monitor an individual server * * @param handle The MySQL Monitor object * @param database The database to probe */ static void monitorDatabase(MONITOR *mon, MONITOR_SERVERS *database) { GALERA_MONITOR* handle = (GALERA_MONITOR*)mon->handle; MYSQL_ROW row; MYSQL_RES *result,*result2; int isjoined = 0; char *uname = mon->user; char *passwd = mon->password; unsigned long int server_version = 0; char *server_string; if (database->server->monuser != NULL) { uname = database->server->monuser; passwd = database->server->monpw; } if (uname == NULL) return; /* Don't even probe server flagged as in maintenance */ if (SERVER_IN_MAINT(database->server)) return; /** Store previous status */ database->mon_prev_status = database->server->status; if (database->con == NULL || mysql_ping(database->con) != 0) { char *dpwd = decryptPassword(passwd); int connect_timeout = mon->connect_timeout; int read_timeout = mon->read_timeout; int write_timeout = mon->write_timeout; if(database->con) mysql_close(database->con); database->con = mysql_init(NULL); mysql_options(database->con, MYSQL_OPT_CONNECT_TIMEOUT, (void *)&connect_timeout); mysql_options(database->con, MYSQL_OPT_READ_TIMEOUT, (void *)&read_timeout); mysql_options(database->con, MYSQL_OPT_WRITE_TIMEOUT, (void *)&write_timeout); if (mysql_real_connect(database->con, database->server->name, uname, dpwd, NULL, database->server->port, NULL, 0) == NULL) { free(dpwd); server_clear_status(database->server, SERVER_RUNNING); /* Also clear Joined, M/S and Stickiness bits */ server_clear_status(database->server, SERVER_JOINED); server_clear_status(database->server, SERVER_SLAVE); server_clear_status(database->server, SERVER_MASTER); server_clear_status(database->server, SERVER_MASTER_STICKINESS); if (mysql_errno(database->con) == ER_ACCESS_DENIED_ERROR) { server_set_status(database->server, SERVER_AUTH_ERROR); } database->server->node_id = -1; if (mon_status_changed(database) && mon_print_fail_status(database)) { LOGIF(LE, (skygw_log_write_flush( LOGFILE_ERROR, "Error : Monitor was unable to connect to " "server %s:%d : \"%s\"", database->server->name, database->server->port, mysql_error(database->con)))); } return; } else { server_clear_status(database->server, SERVER_AUTH_ERROR); } free(dpwd); } /* If we get this far then we have a working connection */ server_set_status(database->server, SERVER_RUNNING); /* get server version string */ server_string = (char *)mysql_get_server_info(database->con); if (server_string) { database->server->server_string = realloc(database->server->server_string, strlen(server_string)+1); if (database->server->server_string) strcpy(database->server->server_string, server_string); } /* Check if the the Galera FSM shows this node is joined to the cluster */ if (mysql_query(database->con, "SHOW STATUS LIKE 'wsrep_local_state'") == 0 && (result = mysql_store_result(database->con)) != NULL) { if(mysql_field_count(database->con) < 2) { mysql_free_result(result); skygw_log_write(LE,"Error: Unexpected result for \"SHOW STATUS LIKE 'wsrep_local_state'\". Expected 2 columns." " MySQL Version: %s",version_str); return; } while ((row = mysql_fetch_row(result))) { if (strcmp(row[1], "4") == 0) isjoined = 1; /* Check if the node is a donor and is using xtrabackup, in this case it can stay alive */ else if (strcmp(row[1], "2") == 0 && handle->availableWhenDonor == 1) { if (mysql_query(database->con, "SHOW VARIABLES LIKE 'wsrep_sst_method'") == 0 && (result2 = mysql_store_result(database->con)) != NULL) { if(mysql_field_count(database->con) < 2) { mysql_free_result(result); mysql_free_result(result2); skygw_log_write(LE,"Error: Unexpected result for \"SHOW VARIABLES LIKE 'wsrep_sst_method'\". Expected 2 columns." " MySQL Version: %s",version_str); return; } while ((row = mysql_fetch_row(result2))) { if (strncmp(row[1], "xtrabackup", 10) == 0) isjoined = 1; } mysql_free_result(result2); } } } mysql_free_result(result); } /* Check the the Galera node index in the cluster */ if (mysql_query(database->con, "SHOW STATUS LIKE 'wsrep_local_index'") == 0 && (result = mysql_store_result(database->con)) != NULL) { long local_index = -1; if(mysql_field_count(database->con) < 2) { mysql_free_result(result); skygw_log_write(LE,"Error: Unexpected result for \"SHOW STATUS LIKE 'wsrep_local_index'\". Expected 2 columns." " MySQL Version: %s",version_str); return; } while ((row = mysql_fetch_row(result))) { local_index = strtol(row[1], NULL, 10); if ((errno == ERANGE && (local_index == LONG_MAX || local_index == LONG_MIN)) || (errno != 0 && local_index == 0)) { local_index = -1; } database->server->node_id = local_index; } mysql_free_result(result); } if (isjoined) server_set_status(database->server, SERVER_JOINED); else server_clear_status(database->server, SERVER_JOINED); }
int OGRMySQLDataSource::Open( const char * pszNewName, char** papszOpenOptionsIn, int bUpdate ) { CPLAssert( nLayers == 0 ); /* -------------------------------------------------------------------- */ /* Use options process to get .my.cnf file contents. */ /* -------------------------------------------------------------------- */ int nPort = 0; char **papszTableNames=NULL; std::string oHost, oPassword, oUser, oDB; CPLString osNewName(pszNewName); const char* apszOpenOptions[] = { "dbname", "port", "user", "password", "host", "tables" }; for(int i=0; i <(int)(sizeof(apszOpenOptions)/sizeof(char*)); i++) { const char* pszVal = CSLFetchNameValue(papszOpenOptionsIn, apszOpenOptions[i]); if( pszVal ) { if( osNewName[osNewName.size()-1] != ':' ) osNewName += ","; if( i > 0 ) { osNewName += apszOpenOptions[i]; osNewName += "="; } if( EQUAL(apszOpenOptions[i], "tables") ) { for( ; *pszVal; ++pszVal ) { if( *pszVal == ',' ) osNewName += ";"; else osNewName += *pszVal; } } else osNewName += pszVal; } } /* -------------------------------------------------------------------- */ /* Parse out connection information. */ /* -------------------------------------------------------------------- */ char **papszItems = CSLTokenizeString2( osNewName+6, ",", CSLT_HONOURSTRINGS ); if( CSLCount(papszItems) < 1 ) { CSLDestroy( papszItems ); CPLError( CE_Failure, CPLE_AppDefined, "MYSQL: request missing databasename." ); return FALSE; } oDB = papszItems[0]; for( int i = 1; papszItems[i] != NULL; i++ ) { if( STARTS_WITH_CI(papszItems[i], "user="******"password="******"host=") ) oHost = papszItems[i] + 5; else if( STARTS_WITH_CI(papszItems[i], "port=") ) nPort = atoi(papszItems[i] + 5); else if( STARTS_WITH_CI(papszItems[i], "tables=") ) { CSLDestroy(papszTableNames); papszTableNames = CSLTokenizeStringComplex( papszItems[i] + 7, ";", FALSE, FALSE ); } else CPLError( CE_Warning, CPLE_AppDefined, "'%s' in MYSQL datasource definition not recognised and ignored.", papszItems[i] ); } CSLDestroy( papszItems ); /* -------------------------------------------------------------------- */ /* Try to establish connection. */ /* -------------------------------------------------------------------- */ hConn = mysql_init( NULL ); if( hConn == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "mysql_init() failed." ); } /* -------------------------------------------------------------------- */ /* Set desired options on the connection: charset and timeout. */ /* -------------------------------------------------------------------- */ if( hConn ) { const char *pszTimeoutLength = CPLGetConfigOption( "MYSQL_TIMEOUT", "0" ); unsigned int timeout = atoi(pszTimeoutLength); mysql_options(hConn, MYSQL_OPT_CONNECT_TIMEOUT, (char*)&timeout); mysql_options(hConn, MYSQL_SET_CHARSET_NAME, "utf8" ); } /* -------------------------------------------------------------------- */ /* Perform connection. */ /* -------------------------------------------------------------------- */ if( hConn && mysql_real_connect( hConn, oHost.length() ? oHost.c_str() : NULL, oUser.length() ? oUser.c_str() : NULL, oPassword.length() ? oPassword.c_str() : NULL, oDB.length() ? oDB.c_str() : NULL, nPort, NULL, CLIENT_INTERACTIVE ) == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "MySQL connect failed for: %s\n%s", pszNewName + 6, mysql_error( hConn ) ); mysql_close( hConn ); hConn = NULL; } if( hConn == NULL ) { CSLDestroy( papszTableNames ); return FALSE; } else { // Enable automatic reconnection // Must be called after mysql_real_connect() on MySQL < 5.0.19 // and at any point on more recent versions. my_bool reconnect = 1; mysql_options(hConn, MYSQL_OPT_RECONNECT, &reconnect); } pszName = CPLStrdup( pszNewName ); bDSUpdate = bUpdate; /* -------------------------------------------------------------------- */ /* Get a list of available tables. */ /* -------------------------------------------------------------------- */ if( papszTableNames == NULL ) { MYSQL_RES *hResultSet; MYSQL_ROW papszRow; if( mysql_query( hConn, "SHOW TABLES" ) ) { ReportError( "SHOW TABLES Failed" ); return FALSE; } hResultSet = mysql_store_result( hConn ); if( hResultSet == NULL ) { ReportError( "mysql_store_result() failed on SHOW TABLES result."); return FALSE; } while( (papszRow = mysql_fetch_row( hResultSet )) != NULL ) { if( papszRow[0] == NULL ) continue; if( EQUAL(papszRow[0],"spatial_ref_sys") || EQUAL(papszRow[0],"geometry_columns") ) continue; papszTableNames = CSLAddString(papszTableNames, papszRow[0] ); } mysql_free_result( hResultSet ); } /* -------------------------------------------------------------------- */ /* Get the schema of the available tables. */ /* -------------------------------------------------------------------- */ int iRecord; for( iRecord = 0; papszTableNames != NULL && papszTableNames[iRecord] != NULL; iRecord++ ) { // FIXME: This should be fixed to deal with tables // for which we can't open because the name is bad/ OpenTable( papszTableNames[iRecord], bUpdate ); } CSLDestroy( papszTableNames ); return nLayers > 0 || bUpdate; }
bool kGUIDBRecord::Save(void) { unsigned int i; unsigned int e; int numchanged; bool changed; bool where; bool uselimit; kGUIString update; kGUIString field; kGUIDBRecordEntry *re; const char *errormsg; assert(m_tablename.GetLen()!=0,"Name not defined for table, call SetTableName(name)!"); /* locate using old key */ /* make sure all fields at the same as before changed */ /* if any are diffent, then return changed by other user error code, unlock table */ /* update fields that are different */ /* unlock table */ update.Alloc(8192); field.Alloc(1024); for(e=0; e<m_numentries; ++e) { re=m_entries.GetEntry(e); if(re->m_delete==true) { uselimit=true; where=true; changed=true; update.SetString("DELETE FROM "); update.Append(m_tablename.GetString()); } else if(re->m_new==true) { where=false; uselimit=false; update.SetString("INSERT "); update.Append(m_tablename.GetString()); update.Append(" SET "); changed=false; for(i=0; i<m_numfields; ++i) { if(changed==true) update.Append(", "); update.Append(GetFieldName(i)); update.Append("='"); m_db->EncodeField(&re->m_newfieldvalues[i],&field); update.Append(field.GetString()); update.Append("'"); changed=true; } } else /* update an existing record */ { update.SetString("UPDATE "); update.Append(m_tablename.GetString()); where=true; uselimit=true; update.Append(" SET "); changed=false; for(i=0; i<m_numfields; ++i) { if(strcmp(re->m_newfieldvalues[i].GetString(),re->m_fieldvalues[i].GetString())) { if(changed==true) update.Append(", "); update.Append(GetFieldName(i)); update.Append("='"); m_db->EncodeField(&re->m_newfieldvalues[i],&field); update.Append(field.GetString()); update.Append("'"); changed=true; } } } if(changed==true) { /* does this table have a unique primary key? */ if(where==true) { update.Append(" WHERE "); if(m_numprikeyfields) { unsigned int f; for(i=0; i<m_numprikeyfields; ++i) { f=m_prikey.GetEntry(i); if(i) update.Append("AND "); update.Append(GetFieldName(f)); update.Append("='"); m_db->EncodeField(&re->m_fieldvalues[f],&field); update.Append(field.GetString()); update.Append("' "); } } #if 0 if(m_unique==true) { update.Append(m_keyname.GetString()); update.Append("='"); update.Append(m_key.GetString()); update.Append("'"); } #endif else { for(i=0; i<m_numfields; ++i) { if(i) update.Append("AND "); update.Append(GetFieldName(i)); update.Append("='"); m_db->EncodeField(&re->m_fieldvalues[i],&field); update.Append(field.GetString()); update.Append("' "); } } } /* this is necessary as there could be multiple matches */ if(uselimit==true) update.Append(" LIMIT 1"); /* lock table */ LockTable(); m_db->UpdateLocks(); mysql_query(m_db->GetConn(),update.GetString()); if(m_db->GetTrace()) m_db->GetTrace()->ASprintf("->%s\n",update.GetString()); errormsg=mysql_error(m_db->GetConn()); if(errormsg[0]) assert(false,errormsg); numchanged=(int)mysql_affected_rows(m_db->GetConn()); assert(numchanged==1,"Error,number of records changed should have been one!"); /* fields were sucessfully written, copy new fields over previous ones */ /* hmmm, deleted entries? */ for(i=0; i<m_numfields; ++i) { re->m_new=false; if(strcmp(re->m_newfieldvalues[i].GetString(),re->m_fieldvalues[i].GetString())) re->m_fieldvalues[i].SetString(re->m_newfieldvalues[i].GetString()); } /* remove lock from this table */ UnLockTable(); m_db->UpdateLocks(); } } /* delete all entries that are flagged for deletion */ i=0; for(e=0; e<m_numentries; ++e) { re=m_entries.GetEntry(e-i); if(re->m_delete) { delete re; m_entries.DeleteEntry(e-i); ++i; /* ajust for scrolling entries */ } } m_numentries-=i; /* update number of entries */ return(true); /* ok! */ }
OGRSpatialReference *OGRMySQLDataSource::FetchSRS( int nId ) { char szCommand[128]; char **papszRow; MYSQL_RES *hResult; if( nId < 0 ) return NULL; /* -------------------------------------------------------------------- */ /* First, we look through our SRID cache, is it there? */ /* -------------------------------------------------------------------- */ int i; for( i = 0; i < nKnownSRID; i++ ) { if( panSRID[i] == nId ) return papoSRS[i]; } OGRSpatialReference *poSRS = NULL; // make sure to attempt to free any old results hResult = mysql_store_result( GetConn() ); if( hResult != NULL ) mysql_free_result( hResult ); hResult = NULL; snprintf( szCommand, sizeof(szCommand), "SELECT srtext FROM spatial_ref_sys WHERE srid = %d", nId ); if( !mysql_query( GetConn(), szCommand ) ) hResult = mysql_store_result( GetConn() ); char *pszWKT = NULL; papszRow = NULL; if( hResult != NULL ) papszRow = mysql_fetch_row( hResult ); if( papszRow != NULL && papszRow[0] != NULL ) { pszWKT = CPLStrdup(papszRow[0]); } if( hResult != NULL ) mysql_free_result( hResult ); hResult = NULL; poSRS = new OGRSpatialReference(); char* pszWKTOri = pszWKT; if( pszWKT == NULL || poSRS->importFromWkt( &pszWKT ) != OGRERR_NONE ) { delete poSRS; poSRS = NULL; } CPLFree(pszWKTOri); /* -------------------------------------------------------------------- */ /* Add to the cache. */ /* -------------------------------------------------------------------- */ panSRID = (int *) CPLRealloc(panSRID,sizeof(int) * (nKnownSRID+1) ); papoSRS = (OGRSpatialReference **) CPLRealloc(papoSRS, sizeof(void*) * (nKnownSRID + 1) ); panSRID[nKnownSRID] = nId; papoSRS[nKnownSRID] = poSRS; nKnownSRID ++; return poSRS; }
/************************************************************************** Loads a user from the database. **************************************************************************/ static enum authdb_status auth_db_load(struct connection *pconn) { #ifdef HAVE_AUTH char buffer[512] = ""; const int bufsize = sizeof(buffer); int num_rows = 0; MYSQL *sock, mysql; MYSQL_RES *res; MYSQL_ROW row; char *name_buffer; int str_result; mysql_init(&mysql); /* attempt to connect to the server */ if (!(sock = mysql_real_connect(&mysql, auth_config.host.value, auth_config.user.value, auth_config.password.value, auth_config.database.value, atoi(auth_config.port.value), NULL, 0))) { freelog(LOG_ERROR, "Can't connect to server! (%s)", mysql_error(&mysql)); return AUTH_DB_ERROR; } name_buffer = alloc_escaped_string(&mysql, pconn->username); if (name_buffer != NULL) { /* select the password from the entry */ str_result = my_snprintf(buffer, bufsize, "select password from %s where name = '%s'", auth_config.table.value, name_buffer); if (str_result < 0 || str_result >= bufsize || mysql_query(sock, buffer)) { freelog(LOG_ERROR, "db_load query failed for user: %s (%s)", pconn->username, mysql_error(sock)); free_escaped_string(name_buffer); mysql_close(sock); return AUTH_DB_ERROR; } res = mysql_store_result(sock); num_rows = mysql_num_rows(res); /* if num_rows = 0, then we could find no such user */ if (num_rows < 1) { mysql_free_result(res); free_escaped_string(name_buffer); mysql_close(sock); return AUTH_DB_NOT_FOUND; } /* if there are more than one row that matches this name, it's an error * continue anyway though */ if (num_rows > 1) { freelog(LOG_ERROR, "db_load query found multiple entries (%d) for user: %s", num_rows, pconn->username); } /* if there are rows, then fetch them and use the first one */ row = mysql_fetch_row(res); mystrlcpy(pconn->server.password, row[0], sizeof(pconn->server.password)); mysql_free_result(res); /* update the access time for this user */ memset(buffer, 0, bufsize); str_result = my_snprintf(buffer, bufsize, "update %s set accesstime=unix_timestamp(), " "address='%s', logincount=logincount+1 " "where strcmp(name, '%s') = 0", auth_config.table.value, pconn->server.ipaddr, name_buffer); free_escaped_string(name_buffer); name_buffer = NULL; if (str_result < 0 || str_result >= bufsize || mysql_query(sock, buffer)) { freelog(LOG_ERROR, "db_load update accesstime failed for user: %s (%s)", pconn->username, mysql_error(sock)); } } mysql_close(sock); #endif return AUTH_DB_SUCCESS; }