int db_select () { lyricDb = db_connect ("lyricDb", "error"); mediaDb = db_connect ("mediaDb", "error"); bibleDb = db_connect ("bibleDb", "error"); return TRUE; }
word db_row_count(void) { // Returns number of rows affected by preceding DELETE or UPDATE. // Doesn't work after a SELECT. MYSQL_RES * result; MYSQL_ROW row; if(db_connect()) return 9; if (mysql_query(mysql_object, "SELECT row_count()")) { char zs[1024]; sprintf(zs, "db_row_count(): mysql_query() Error %u: %s", mysql_errno(mysql_object), mysql_error(mysql_object)); _log(CRITICAL, zs); db_disconnect(); return 3; } result = mysql_store_result(mysql_object); row = mysql_fetch_row(result); mysql_free_result(result); return atoi(row[0]); }
word db_query(const char * const query) { char zs[2048]; if(strlen(query) > 2000) { _log(MAJOR, "db_query() called with overlong query."); return 99; } sprintf(zs, "db_query(\"%s\")", query); _log(PROC, zs); if(db_connect()) return 9; if(mysql_query(mysql_object, query)) { sprintf(zs, "db_query(): mysql_query() Error %u: %s Query:", mysql_errno(mysql_object), mysql_error(mysql_object)); _log(CRITICAL, zs); char report[128]; strncpy(report, query, 96); report[96] = 0; if(strlen(query) > 96) { strcat(report, "..."); } sprintf(zs,"\"%s\"", report); _log(CRITICAL, zs); db_disconnect(); return 3; } return 0; }
void connect_to_db(void) { redisReply *reply; options *globaloptions; struct timeval timeout = { 1, 500000 }; if (options_init_from_boxrc() < 0) { LOG_ERROR("Reading config failed--see warnings above. " "For usage, try -h."); return; } globaloptions = options_get(); /* connect to database */ assert_int_equal(0, db_connect( fmt_addr(&globaloptions->RedisDatabaseListenAddr), globaloptions->RedisDatabaseListenPort, timeout, globaloptions->RedisDatabaseAuth)); reply = redisCommand(rc, "FLUSHALL"); freeReplyObject(reply); options_free(globaloptions); }
static void detect_dbs(void) { const char *cstr = make_connstr(cf.initial_database); db_template = db_create(detect_handler, NULL); db_connect(db_template, cstr); free(cstr); }
int main(void) { curmudgeon_t * app = NULL; event_t * event = NULL; char * test = "/hello_world/arg1/arg2"; if ( cur_init(&app,1) == CUR_OK) { app->schema_version_file = "schema.version"; adapter_t * a = NULL; db_mysql(app,&a,"{ 'host': 'localhost', 'user': '******', 'pass': '******' }"); db_connect( a ); db_select_db( a ,"curmudgeon"); printf("Schema version is: %d\n",_get_num_from_file(app->schema_version_file)); _set_num_in_file(app->schema_version_file,1); printf("Schema version is: %d\n",_get_num_from_file(app->schema_version_file)); if ( schema_database(a,"test_table",NULL,NULL) == CUR_OK ) { printf("migrated\n"); } else { printf("did not migrate\n"); } _set_num_in_file(app->schema_version_file,0); if ( schema_database( a ,"test_table",NULL,NULL) == CUR_OK ) { printf("migrated\n"); } else { printf("did not migrate\n"); } schema_database( a ,"test_table","latin1","latin1_general_ci"); cur_done(&app); } else { Puts("Could not init"); } return 0; }
/* * Check to see if the connection is still valid. If not, attempt to * reconnect. */ static isc_result_t maybe_reconnect(struct dbinfo *dbi) { if (PQstatus(dbi->conn) == CONNECTION_OK) return (ISC_R_SUCCESS); return (db_connect(dbi)); }
/*---------------------------------------------------------------- main -----------------------------------------------------------------*/ int main(int argc, char **argv) { RETCODE retcode = -1; int rc; GET_LOGIN_VARS() retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HENV, &EnvHandle); if (retcode != SQL_SUCCESS) { printf("Unable to allocate ODBC environment handle!\n"); return -1; } retcode = SQLSetEnvAttr(EnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER); if (retcode != SQL_SUCCESS) { printf("Unable to set version of ODBC environment handle!\n"); LogODBCError(retcode, SQL_HANDLE_ENV, EnvHandle); return -2; } rc = db_connect(); if (rc >= 0) { rc = print_columns("SOME_NUMERIC_TYPES"); } return rc; }
int URL_put_data_mysql_url ( const URL *url, const PKI_MEM *data ) { #ifdef HAVE_MYSQL MYSQL * sql = NULL; char * query = NULL; if( !url ) return (PKI_ERR); if((query = parse_url_put_query( url, data )) == NULL ) { return( PKI_ERR ); } if((sql = db_connect ( url )) == NULL ) { PKI_Free( query ); return(PKI_ERR); } if(mysql_query(sql, query ) != 0 ) { PKI_Free ( query ); db_close( sql ); return( PKI_ERR ); } PKI_Free (query); db_close ( sql ); return ( PKI_OK ); #else return ( PKI_ERR ); #endif }
int main(int argc, char *argv[]) { int i, foreground, port; void (*timeseal_init)(const char * ) = chessd_function("timeseal_init"); int (*net_init)(int ) = chessd_function("net_init"); void (*initial_load)(void ) = chessd_function("initial_load"); void (*db_connect)(void ) = chessd_function("db_connect"); void (*db_disconnect)(void ) = chessd_function("db_disconnect"); port = DEFAULT_PORT; foreground = 0; /* enable malloc checking in libc */ setenv("MALLOC_CHECK_", "2", 1); while((i = getopt(argc, argv, "p:fR:T:")) != -1) { switch(i) { case 'p': port = atoi(optarg); break; case 'f': foreground = 1; break; case 'T': timeseal_init(optarg); break; case 'R': do_chroot(optarg); break; default: usage(); } } if (!foreground && daemonize()){ printf("Problem with Daemonization - Aborting\n"); exit(1); } signal(SIGTERM, TerminateServer); signal(SIGSEGV, segv_handler); signal(SIGBUS, segv_handler); signal(SIGINT, TerminateServer); signal(SIGPIPE, BrokenPipe); if (net_init(port)) { fprintf(stderr, "CHESSD: Network initialize failed on port %d.\n", port); exit(1); } fprintf(stderr, "CHESSD: Initialized on port %d\n", port); initial_load(); db_connect(); main_event_loop(); db_disconnect(); /* will never get here - uses TerminateServer */ return 0; }
static void main_event_loop(void) { void (*select_loop)(void ) = chessd_function("select_loop"); while (1) { select_loop(); /* check the reload flag */ if (chessd_reload_flag) { void (*reload_close)(void ) = chessd_function("reload_close"); void (*reload_open)(void ); void (*db_disconnect)(void ) = chessd_function("db_disconnect"); db_disconnect(); chessd_reload_flag = 0; fprintf(stderr, "CHESSD: Reloading server code!\n"); /* free up local vars */ reload_close(); /* close the handle to the shared lib */ dlclose(chessd_so_handle); chessd_so_handle = NULL; /* re-initialise local variables */ reload_open = chessd_function("reload_open"); reload_open(); select_loop = chessd_function("select_loop"); void (*db_connect)(void ) = chessd_function("db_connect"); db_connect(); } } }
/* * Create a connection to the database and save any necessary information * in dbdata. * * argv[0] is the name of the database file * argv[1] is the name of the table */ static isc_result_t sqlitedb_create(const char *zone, int argc, char **argv, void *driverdata, void **dbdata) { dbinfo_t *dbi; isc_result_t result; UNUSED(zone); UNUSED(driverdata); if (argc < 2) return (ISC_R_FAILURE); dbi = isc_mem_get(ns_g_mctx, sizeof(dbinfo_t)); if (dbi == NULL) return (ISC_R_NOMEMORY); dbi->db = NULL; dbi->filename = NULL; dbi->table = NULL; STRDUP_OR_FAIL(dbi->filename, argv[0]); STRDUP_OR_FAIL(dbi->table, argv[1]); result = db_connect(dbi); if (result != ISC_R_SUCCESS) goto cleanup; *dbdata = dbi; return (ISC_R_SUCCESS); cleanup: sqlitedb_destroy(zone, driverdata, (void **)&dbi); return (result); }
static void chk_prog_stat(void) { sqlite *db_id; int x=0; db_id=db_connect(DB_NAME); db_query(db_id,"select service_dhcp.stat,service_ftp.stat,service_ssh.stat,auth_ad.stat,service_ddns.stat,pptp_vpn.stat,service_snmp.stat,service_https.stat from service_dhcp,service_ftp,service_ssh,auth_ad,service_ddns,pptp_vpn,service_snmp,service_https"); if(SQL_NUMROWS!=0) { for(x=0;x<SQL_NUMROWS;x++) { if(!strcmp(SQL_RESULT[x].name,"service_dhcp.stat") && atoi(SQL_RESULT[x].value)==1) dhcp_stat=1; if(!strcmp(SQL_RESULT[x].name,"service_ftp.stat") && atoi(SQL_RESULT[x].value)==1) ftp_stat=1; if(!strcmp(SQL_RESULT[x].name,"service_ssh.stat") && atoi(SQL_RESULT[x].value)==1) ssh_stat=1; if(!strcmp(SQL_RESULT[x].name,"auth_ad.stat") && atoi(SQL_RESULT[x].value)==1) auth_ad=1; if(!strcmp(SQL_RESULT[x].name,"service_ddns.stat") && atoi(SQL_RESULT[x].value)==1) ddns_stat=1; if(!strcmp(SQL_RESULT[x].name,"pptp_vpn.stat") && atoi(SQL_RESULT[x].value)==1) pptp_stat=1; if(!strcmp(SQL_RESULT[x].name,"service_snmp.stat") && atoi(SQL_RESULT[x].value)==1) snmp_stat=1; if(!strcmp(SQL_RESULT[x].name,"service_https.stat") && atoi(SQL_RESULT[x].value)==1) https_stat=1; } } db_clean_buffer(); db_query(db_id,"select * from htb_client"); if(SQL_NUMROWS!=0) shaper_stat=1; db_clean_buffer(); db_query(db_id,"select val from misc where name='ids_stat'"); if(SQL_NUMROWS!=0) { ips_stat=atoi(SQL_RESULT[0].value); } db_close(db_id); }
downloader *easy_downloader_init() { int ret; sqlite3 *db_key; snprintf(download_tmp_path, PATH_MAX, "%s/%s/", getenv("HOME"), TMP_DIR); ret = mkdir(download_tmp_path, S_IRWXU); if (ret != 0 && errno != EEXIST) return NULL; chdir(download_tmp_path); if ((ret = db_connect(DB_FILE_NAME, &db_key, SQL_CREATE_TABLE)) != 0) return NULL; d_manager_t *manager = (d_manager_t *)malloc(sizeof(d_manager_t)); manager->tp = easy_thread_pool_init(5, 60); manager->db_key = db_key; if (file_saved_def_path[0] == '\0') { strcpy(file_saved_def_path, getenv("HOME")); strcat(file_saved_def_path, "/"); } return (downloader *)manager; }
extern unsigned int db_d2char_delete(char const * db_table,char const * account, char const * charname, char const * realmname) { MYSQL mysql = {0}; /* MySQL headers aren't correct initialized */ char * sql; /* This shall allow us to reconnect, after a disconnected MySQL link */ if (!db_connect(&mysql)) return 0; if (!strlen(realmname)) { eventlog(eventlog_level_error, __FUNCTION__, "got no realm name "); return 0; } if (!(sql = malloc(strlen("DELETE FROM WHERE accname=\'\' AND charname=\'\' AND realm=\'\' AND recage=0")+strlen(db_table)+strlen(account)+strlen(charname)+strlen(realmname)+1))) { eventlog(eventlog_level_error, __FUNCTION__, "unable to allocate memory for query"); free(sql); return 0; } sprintf(sql, "DELETE FROM %s WHERE accname=\'%s\' AND charname=\'%s\' AND realm=\'%s\' AND recage=0",db_table,account,charname,realmname); if(mysql_query(&mysql,sql)) { eventlog(eventlog_level_error, __FUNCTION__, "error deleting character \"%s(*%s)@%s\" (%d:%s)",charname,account,realmname,mysql_errno(&mysql),mysql_error(&mysql)); free(sql); return 0; } free(sql); if(mysql_affected_rows(&mysql)!=0) { eventlog(eventlog_level_error, __FUNCTION__,"zero data records for \"%s(*%s)@%s\" deleted (%d:%s)",charname,account,realmname,mysql_errno(&mysql),mysql_error(&mysql)); return 0; } eventlog(eventlog_level_trace, __FUNCTION__, "successfully deleted record \"%s(*%s)@%s\"",charname,account,realmname); return 1; }
int db_list_contains(brain_t brain, enum list type, word_t word) { PGresult *res; const char *param[3]; char tmp[3][32]; if (brain == 0 || word == 0) return -EINVAL; if (db_connect()) return -EDB; SET_PARAM(param, tmp, 0, brain); SET_PARAM(param, tmp, 1, type); SET_PARAM(param, tmp, 2, word); res = PQexecPrepared(conn, "list_get", 3, param, NULL, NULL, 0); if (PQresultStatus(res) != PGRES_TUPLES_OK) goto fail; if (PQntuples(res) == 0) goto not_found; PQclear(res); return OK; fail: log_error("db_list_contains", PQresultStatus(res), PQresultErrorMessage(res)); PQclear(res); return -EDB; not_found: PQclear(res); return -ENOTFOUND; }
void setup(void) { configure_debug(255,0); config_read(configFile); GetDBParams(); db_connect(); }
void db_remove_file(int file_id) { char *query = NULL; char query_outline[] = "DELETE FROM files WHERE file_id = "; int query_length = 0; int rc = SQLITE_ERROR; /* return code of sqlite operation */ int written = 0; /* number of characters written */ sqlite3 *conn = NULL; sqlite3_stmt *res = NULL; DEBUG(ENTRY); assert(file_id > 0); DEBUG("Removing file ID %d", file_id); /* prepare query */ query_length = strlen(query_outline) + num_digits(file_id); query = malloc(query_length * sizeof(*query) + 1); assert(query != NULL); written = snprintf(query, query_length + 1, "DELETE FROM files WHERE file_id = %d", file_id); assert(written == query_length); /* connect to database */ conn = db_connect(); assert(conn != NULL); rc = db_execute_statement(conn, query, &res); db_finalize_statement(conn, query, res); db_disconnect(conn); free_single_ptr((void **)&query); DEBUG("Removing file ID %d was %ssuccessful", file_id, rc == SQLITE_DONE ? "" : "not "); DEBUG(EXIT); } /* db_remove_file */
void db_delete_tag(int tag_id) { char *query = NULL; char query_outline[] = "DELETE FROM tags WHERE tag_id = \"\""; int query_length = 0; int rc = SQLITE_ERROR; /* return code of sqlite operation */ int written = 0; /* number of characters written */ sqlite3 *conn = NULL; sqlite3_stmt *res = NULL; DEBUG(ENTRY); assert(tag_id > 0); DEBUG("Deleting tag with tag ID %d", tag_id); /* prepare query */ query_length = strlen(query_outline) + num_digits(tag_id); query = malloc(query_length * sizeof(*query) + 1); assert(query != NULL); written = snprintf(query, query_length + 1, "DELETE FROM tags WHERE tag_id = \"%d\"", tag_id); assert(written == query_length); /* connect to database */ conn = db_connect(); assert(conn != NULL); rc = db_execute_statement(conn, query, &res); db_finalize_statement(conn, query, res); db_disconnect(conn); free_single_ptr((void **)&query); DEBUG("File with ID %d was %sdeleted successfully.", tag_id, rc == 0 ? "" : "not ") DEBUG(EXIT); } /* db_delete_tag */
void db_add_tag_to_file(int tag_id, int file_id) { char *query = NULL; char query_outline[] = "INSERT INTO file_has_tag VALUES(, )"; int query_length = 0; int rc = SQLITE_ERROR; /* return code of sqlite operation */ int written = 0; /* number of characters written */ sqlite3 *conn = NULL; sqlite3_stmt *res = NULL; DEBUG(ENTRY); assert(tag_id >= 0); assert(file_id > 0); /* prepare query */ query_length = strlen(query_outline) + num_digits(tag_id) + num_digits(file_id); query = malloc(query_length * sizeof(*query) + 1); assert(query != NULL); written = snprintf(query, query_length + 1, "INSERT INTO file_has_tag VALUES(%d, %d)", file_id, tag_id); assert(written == query_length); /* connect to database */ conn = db_connect(); assert(conn != NULL); rc = db_execute_statement(conn, query, &res); db_finalize_statement(conn, query, res); db_disconnect(conn); free_single_ptr((void **)&query); DEBUG("Adding tag ID %d to file ID %d was %ssuccessful", tag_id, file_id, rc == SQLITE_DONE ? "" : "not "); DEBUG(EXIT); } /* db_add_tag_to_file */
extern void db_d2char_acccharlist (char const * db_table,char const * account,char const * realmname,t_db_result * myresult) { /* This shall allow us to reconnect, after a disconnected MySQL link */ if (!db_connect(&myresult->mysql)) return; if (!(myresult->sql = malloc(strlen("SELECT charname FROM WHERE accname=\'\' AND realm=\'\' AND recage=0")+strlen(db_table)+strlen(account)+strlen(realmname)+1))) { eventlog(eventlog_level_error, __FUNCTION__, "unable to allocate memory for query"); free(myresult->sql); return; } sprintf(myresult->sql, "SELECT charname FROM %s WHERE accname=\'%s\' AND realm=\'%s\' AND recage=0",db_table,account,realmname); if(mysql_query(&myresult->mysql,myresult->sql)) { eventlog(eventlog_level_error, __FUNCTION__, "error selecting characters for \"*%s@%s\" (%d:%s)",account,realmname,mysql_errno(&myresult->mysql),mysql_error(&myresult->mysql)); free(myresult->sql); return; } free(myresult->sql); if(!(myresult->res = mysql_store_result(&myresult->mysql))) { eventlog(eventlog_level_error, __FUNCTION__, "result error in selecting characters for \"*%s@%s\" (%d:%s)",account,realmname,mysql_errno(&myresult->mysql),mysql_error(&myresult->mysql)); return; } eventlog(eventlog_level_trace, __FUNCTION__, "got a query result of %lu characters for \"*%s@%s\"", (unsigned long) mysql_num_rows(myresult->res),account,realmname); }
PAM_VISIBLE int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc, const char *argv[]) { modopt_t *options = NULL; const char *user, *rhost; int rc; PGresult *res; PGconn *conn; user = NULL; rhost = NULL; if ((options = mod_options(argc, argv)) != NULL) { if (options->query_session_close) { if ((rc = pam_get_item(pamh, PAM_RHOST, (const void **)&rhost)) == PAM_SUCCESS) { if ((rc = pam_get_user(pamh, &user, NULL)) == PAM_SUCCESS) { DBGLOG("Session opened for user: %s", user); if ((conn = db_connect(options))) { pg_execParam(conn, &res, options->query_session_close, pam_get_service(pamh), user, NULL, rhost); PQclear(res); PQfinish(conn); } } } } //free_module_options(options); } return (PAM_SUCCESS); }
/* public: check if account has expired, or needs new password */ PAM_VISIBLE int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv) { modopt_t *options = NULL; const char *user, *rhost; int rc = PAM_AUTH_ERR; PGconn *conn; PGresult *res; user = NULL; rhost = NULL; if ((options = mod_options(argc, argv)) != NULL) { /* query not specified, just succeed. */ if (options->query_acct == NULL) { //free_module_options(options); return PAM_SUCCESS; } if ((rc = pam_get_item(pamh, PAM_RHOST, (const void **)&rhost)) == PAM_SUCCESS) { if((rc = pam_get_user(pamh, &user, NULL)) == PAM_SUCCESS) { if(!(conn = db_connect(options))) { rc = PAM_AUTH_ERR; } else { DBGLOG("query: %s", options->query_acct); rc = PAM_AUTH_ERR; if(pg_execParam(conn, &res, options->query_acct, pam_get_service(pamh), user, NULL, rhost) == PAM_SUCCESS) { if (PQntuples(res) == 1 && PQnfields(res) >= 2 && PQnfields(res) <= 3) { char *expired_db = PQgetvalue(res, 0, 0); char *newtok_db = PQgetvalue(res, 0, 1); rc = PAM_SUCCESS; if (PQnfields(res)>=3) { char *nulltok_db = PQgetvalue(res, 0, 2); if ((!strcmp(nulltok_db, "t")) && (flags & PAM_DISALLOW_NULL_AUTHTOK)) rc = PAM_NEW_AUTHTOK_REQD; } if (!strcmp(newtok_db, "t")) rc = PAM_NEW_AUTHTOK_REQD; if (!strcmp(expired_db, "t")) rc = PAM_ACCT_EXPIRED; } else { DBGLOG("query_acct should return one row and two or three columns"); rc = PAM_PERM_DENIED; } PQclear(res); } PQfinish(conn); } } } } //free_module_options(options); return rc; }
void launch_ticker(struct PgDatabase *db) { const char *cstr = make_connstr(db->name); log_debug("%s: launch_ticker", db->name); if (!db->c_ticker) db->c_ticker = db_create(tick_handler, db); db_connect(db->c_ticker, cstr); free(cstr); }
END_TEST START_TEST(test_db_connect) { int res; db_disconnect(); res = db_connect(); fail_unless(res==0, "Unable to connect to db"); }
int main() { start_log("log"); db_connect("ouroboros","ouroboros", "ouroboros_development"); db_exec_query("SELECT * FROM users", 10); db_disconnect(); return 1; }
int batch_si(int conn, char *command) { char instance[63] = ""; int business = 0; char *sql; int rowc; row_t *rows = NULL; if (sscanf(command, "SI %[^.].%i\n", instance, &business) != 2) { chat(conn, "ERROR: Invalid syntax\n"); return 0; } chat(conn, "Performing SalesInvoice batch run for instance '%s', business '%i' ... ", instance, business); db_connect(config->dbs); /* verify instance and business exist */ asprintf(&sql, "SELECT * FROM instance WHERE id='%s';", instance); rowc = batch_fetch_rows(NULL, 0, sql, &rows); free(sql); if (rowc == 0) { chat(conn, "ERROR: instance '%s' does not exist\n", instance); db_disconnect(config->dbs); return 0; } rows = NULL; asprintf(&sql, "SELECT * FROM business WHERE id='%i';", business); rowc = batch_fetch_rows(instance, 0, sql, &rows); free(sql); if (rowc == 0) { chat(conn, "ERROR: business '%s.%i' does not exist\n", instance, business); db_disconnect(config->dbs); return 0; } rows = NULL; chat(conn, CLERK_RESP_OK); /* lock salesinvoice table */ batch_exec_sql(instance, business, "BEGIN WORK; LOCK TABLE salesinvoice IN EXCLUSIVE MODE"); /* generate salesinvoices */ batch_exec_sql(instance, business, "SELECT process_salesorders();"); /* commit changes and release lock */ batch_exec_sql(instance, business, "COMMIT WORK;"); db_disconnect(config->dbs); chat(conn, CLERK_RESP_OK); return 0; }
void setup(void) { configure_debug(511,0); config_read(configFile); GetDBParams(); db_connect(); auth_connect(); g_mime_init(0); init_testuser1(); }
/* * * the test fixtures * */ void setup(void) { reallyquiet = 1; configure_debug(255,0); config_read(configFile); GetDBParams(); db_connect(); auth_connect(); do_add("testfailuser","testpass","md5-hash",0,0,NULL,NULL); }
//检测数据库连接,断开则重连 void DbServer::checkConn() { if(!mysql_ping(&conn)){ printf("mysql connecting normal!\n"); return ; }else{ printf("mysql conn have been close!\n"); db_connect(); } }