Esempio n. 1
0
//*****************************************************************************
//*************************   MAIN-FUNCTION   *********************************
//*****************************************************************************
int main () {


	//Connect to the database
	mysql_connect();

	//gets min_rv en RV[]
	get_stuff();

	//disconnect from the database
	mysql_disconnect();


	//check for a too low value and send mail
	for(int i = 0; i < 3600; i++){
		if((RV[i] < min_rv) && (RV[i] > 0)){
			//exec command
			//snprintf(temp, 100, "cat /usr/share/nginx/mail/humidity_low.txt | mail -s \"Test Subject\" [email protected]");
			//echo "<b>HTML Message goes here</b>" | mail -s "$(echo -e "This is the subject\nContent-Type: text/html")" [email protected]
			snprintf(temp, 200, "cat /usr/share/nginx/mail/humidity_low.txt | mail -s \"$(echo \"[TerraPi] Too low humidity detected.\nContent-Type: text/html\")\" [email protected]");
			system(temp);

			printf("Error: Too low humidity - mail has been sent.\n\n");
			break;
		}
	}

}
Esempio n. 2
0
//---------------------------------------------------------------------------
bool WCConnect(void)
{
   if (mysql!=NULL) return true;

   mysql = NULL;
   mysql = mysql_init(NULL);//new MYSQL;
   if ( !mysql )
   {
     return false;
   }
   mysql_options(mysql, MYSQL_SET_CHARSET_DIR, "C:/mysql5/share/charsets/");
   mysql_options(mysql, MYSQL_SET_CHARSET_NAME, "cp1251");
   if (mysql_connect(mysql,opts.DBHost.c_str(),opts.DBLogin.c_str(),opts.DBPasswd.c_str()))
   {
     mysql_select_db(mysql,opts.DBName.c_str());
     if (0!=mysql_errno(mysql))
     {
       return false;
     }
   }
   else
   {
     return false;
   }
   return true;
}
Esempio n. 3
0
File: ints.c Progetto: javigf/smRPi
int updateStatus (int port, bool portStatus){
	
	//6 = HUMO - 21/22
	//5 = PRTA - 23 - NC - LOW
	//2 = TALT - 24
	
	//  DETECTA VALOR -10 => PUERTA ABIERTA	0
	// 	DETECTA VALOR -20 => PUERTA CERRADA 1
	
	
	if (!mysql_connect ()){
		
		if (portStatus){
			db_insert (5,0,puerta_abierta);
			printf ("PA\n");
		}
		else {
			db_insert (5,0,puerta_cerrada);
			printf ("PC\n");
		}
		db_update (5,0,0);
		mysql_disconnect ();
	}

	return 0;
}
Esempio n. 4
0
int DbConn::connect(char *db_name, char *user_name, char *authen)
{
	#ifdef OLD_MYSQL
	if( !mysql_connect(&my_sql, NULL, user_name, authen))
	{
		DbConn::error();
		return -1;
	}
	/* dahee 이라는 db를 선택 */
	if( mysql_select_db(&my_sql, db_name)) 
	{
		DbConn::error();
		return -1;
	}
	#else
	mysql_init(&my_sql);
	mysql_options(&my_sql, MYSQL_READ_DEFAULT_GROUP, "mysql");

	/* host 부분이 NULL이면 localhost입니다. */
	if( !mysql_real_connect(&my_sql, NULL, user_name, authen, db_name, 0, NULL, 0))
	{
		DbConn::error();
		return -1;
	}
	#endif
	isConnected = 1; // set the flag TRUE. connection success.
	return 0;
}
Esempio n. 5
0
//--------------------------------------------------------------------------
bool Connection::real_connect (cchar *db, cchar *host, cchar *user,
			       cchar *passwd, uint port, my_bool compress,
			       unsigned int connect_timeout,
			       const char *socket_name)
{
  if (socket_name && socket_name[0])
    mysql.options.unix_socket = (char *)socket_name;
  else
    mysql.options.unix_socket=NULL;
  mysql.options.port = port;
  mysql.options.compress = compress;
  mysql.options.connect_timeout=connect_timeout;
  locked = true;
  if (mysql_connect(&mysql, host, user, passwd))
  {
    locked = false;
    Success = is_connected = true;
  }
  else
  {
    locked = false; Success = is_connected = false;
    if (throw_exceptions) throw BadQuery(error());
  }
  if (!Success) return Success;
  if (db[0]) // if db is not empty
    Success = select_db(db);
  return Success;
}
Esempio n. 6
0
/*
 * mysql_get_connection:
 * 			Get a connection which can be used to execute queries on
 * the remote MySQL server with the user's authorization. A new connection
 * is established if we don't already have a suitable one.
 */
MYSQL*
mysql_get_connection(ForeignServer *server, UserMapping *user, mysql_opt *opt)
{
	bool found;
	ConnCacheEntry *entry;
	ConnCacheKey key;

	/* First time through, initialize connection cache hashtable */
	if (ConnectionHash == NULL)
	{
		HASHCTL	ctl;
		MemSet(&ctl, 0, sizeof(ctl));
		ctl.keysize = sizeof(ConnCacheKey);
		ctl.entrysize = sizeof(ConnCacheEntry);
		ctl.hash = tag_hash;

		/* allocate ConnectionHash in the cache context */
		ctl.hcxt = CacheMemoryContext;
		ConnectionHash = hash_create("mysql_fdw connections", 8,
									&ctl,
									HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
	}

	/* Create hash key for the entry.  Assume no pad bytes in key struct */
	key.serverid = server->serverid;
	key.userid = user->userid;

	/*
	 * Find or create cached entry for requested connection.
	 */
	entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
	if (!found)
	{
		/* initialize new hashtable entry (key is already filled in) */
		entry->conn = NULL;
	}
	if (entry->conn == NULL)
	{
		entry->conn = mysql_connect(
			opt->svr_address,
			opt->svr_username,
			opt->svr_password,
			opt->svr_database,
			opt->svr_port,
			opt->svr_sa,
			opt->svr_init_command,
			opt->ssl_key,
			opt->ssl_cert,
			opt->ssl_ca,
			opt->ssl_capath,
			opt->ssl_cipher
		);
		elog(DEBUG3, "new mysql_fdw connection %p for server \"%s\"",
			 entry->conn, server->servername);
	}
	return entry->conn;
}
int main(int argc, char **argv) {
   MYSQL mysql;
   char optchar;
   char *target, *user, *password, *attackuser, *action;

   target = user = password = action = attackuser= NULL;

   while ( (optchar = getopt(argc, argv, "ht:u:p:a:e:")) != EOF ) {
       switch(optchar) { 
           case 'h': printf("hoagie_mysql.c\n");
                     printf("-t ... mysql server (default localhost)\n");
      		     printf("-u ... username (default empty)\n");
                     printf("-p ... password (default empty)\n");
                     printf("-a ... attack user (default root)\n");
                     printf("-e ... action\n");
                     printf("-h ... this screen\n");
                     exit(0);
           case 't': target = optarg;
                     break;
           case 'u': user = optarg;
                     break;
           case 'p': password = optarg;
                     break;
           case 'a': attackuser = optarg;
                     break;
           case 'e': action = optarg;
       }
   }

   if (!target) target = "localhost";
   if (!user) user = "";
   if (!password) password = "";
   if (!attackuser) attackuser = "******";
   if (!action) action = "dumpuser";

   printf("connecting to [%s] as [%s] ... ", target, user);
   fflush(stdin);

   if (!mysql_connect(&mysql, target, user, password)) {
       printf("failed\n");
       return 0;
   } else {
       printf("ok\n");
   }

   printf("sending one byte requests with user [%s] ... \n", attackuser);
   if (!do_attack(&mysql, attackuser)) {
       do_action(&mysql, action, user);
   } else {
       printf("attack failed\n");
   }
   mysql_close(&mysql);

   return 0;
}
Esempio n. 8
0
int main() 
{
    mysql_connect(); 

    list_drivers();
    list_data_sources();
    list_driver_information();
    list_tables();

    execute_query("select * from junk");
    execute_query("select count(*), sum(a) from junk");
    execute_query("select a, a+3, 3.141592654 from junk");
    execute_query("select j1.a, j2.a from junk j1 natural join junk j2");

    mysql_disconnect();
}
Esempio n. 9
0
//--------------------------------------------------------------------------
bool Connection::connect (cchar *db, cchar *host, cchar *user, cchar *passwd)
{
  locked = true;
  if (mysql_connect(&mysql, host, user, passwd)) {
    locked = false;
    Success = is_connected = true;
  } else {
    locked = false;
    if (throw_exceptions) throw BadQuery(error());
    Success = is_connected = false;
  }
  if (!Success) return Success;
  if (db[0]) // if db is not empty
    Success = select_db(db);
  return Success;
}
Esempio n. 10
0
int main(int argc, char **argv){

 uint8_t data_array[4];
 uint8_t tx_address[5] = { 0xE7, 0xE7, 0xE7, 0xE7, 0xE7 };
 uint8_t rx_address[5] = { 0xD7, 0xD7, 0xD7, 0xD7, 0xD7 };

 if (!bcm2835_init())
  return 1;

 mysql_connect();

 /* init hardware pins */
 nrf24_init();

 /* Channel #2 , payload length: 4 */
 nrf24_config(2, 4);

 /* Set the device addresses */
 nrf24_tx_address(tx_address);
 nrf24_rx_address(rx_address);

 printf("Configured\n");

 while (1){
  if (nrf24_dataReady()) {
   nrf24_getData(data_array);
   printf("> %d %d %d %d \n",
    data_array[0],
    data_array[1],
    data_array[2],
    data_array[3]);
  if (argc>1) {
   if (argv[1][0]=='1') {
    writeCpm(
     data_array[0],
     data_array[1],
     data_array[2],
     data_array[3]);
    }
   }
  }
 }
 mysql_disconnect();
 bcm2835_close();
 return 0;
}
Esempio n. 11
0
int main(int argc, char **argv)
{
  int	count, num;
  MYSQL mysql,*sock;
  MYSQL_RES *res;
  char	qbuf[160];

  if (argc != 2)
  {
    fprintf(stderr,"usage : select_test <dbname>\n\n");
    exit(1);
  }

  if (!(sock = mysql_connect(&mysql,NULL,0,0)))
  {
    fprintf(stderr,"Couldn't connect to engine!\n%s\n\n",mysql_error(&mysql));
    perror("");
    exit(1);
  }
  mysql.reconnect= 1;

  if (mysql_select_db(sock,argv[1]) < 0)
  {
    fprintf(stderr,"Couldn't select database %s!\n%s\n",argv[1],
	    mysql_error(sock));
    exit(1);
  }

  if (!(res=mysql_list_dbs(sock,NULL)))
  {
    fprintf(stderr,"Couldn't list dbs!\n%s\n",mysql_error(sock));
    exit(1);
  }
  mysql_free_result(res);
  if (!(res=mysql_list_tables(sock,NULL)))
  {
    fprintf(stderr,"Couldn't list tables!\n%s\n",mysql_error(sock));
    exit(1);
  }
  mysql_free_result(res);

  mysql_close(sock);
  exit(0);
  return 0;
}
Esempio n. 12
0
main() {

    struct tm tm;
    struct timeval t0, t1;
    char mdate[20];
    char mtime[20];
    time_t t;
    suseconds_t	ut0, ut1;

    /* Get current time */
    gettimeofday(&t0, NULL);
    t=t0.tv_sec;
    ut0=t0.tv_usec;
    localtime_r(&t, &tm);
    strftime(mdate, 128, DATE_FORMAT, &tm);
    strftime(mtime, 128, TIME_FORMAT, &tm);

    printf("\n\n%s %s - Start of MOR Auto-Dialer Cron script.\n", mdate, mtime);    
    
    read_config();

    if (!mysql_connect()) 
	return 0;
    
    if ((get_campaigns(mtime) < 0) || (total_campaigns == 0))
	return 0;
	
    get_numbers();

    execute_numbers();        

    mysql_close(&mysql);    

    gettimeofday(&t1, NULL);
    ut1=t1.tv_usec;
    printf("End of MOR Auto-Dialer Cron script.\nTotal campaigns: %i, total numbers: %i\nExecution time: %f s\n\n", total_campaigns, total_numbers, (float) (ut1-ut0)/1000000);    
					      
    //gets(NULL);

}
Esempio n. 13
0
void *
dbio_mysql_connect (char *name, char *user, char *pwd, char *host)
{
    MYSQL_CONNECT_CTX
        *handle = NULL;
    MYSQL
        *mysql;


    mysql = mysql_connect (NULL, host, user, pwd);
    if (mysql)
      {
        if (mysql_select_db (mysql, name) != 0)
          {
            mysql_close (mysql);
            mysql = NULL;
          }
      }
    if (mysql)
      {
        handle = mem_alloc (sizeof (MYSQL_CONNECT_CTX));
        memset (handle, 0,  sizeof (MYSQL_CONNECT_CTX));
        handle-> db_handle = mysql;
        handle-> port      = MYSQL_PORT;
        strcpy (handle-> dbname, name);
        if (user && strused (user))
            strcpy (handle-> user,     user);
        if (pwd  && strused (pwd))
            strcpy (handle-> password, pwd);
        if (host && strused (host))
            strcpy (handle-> host,     host);
      }
    else
        coprintf ("Error on Connect to %s in MySql", name);
    
    return ((void *)handle);
}
Esempio n. 14
0
//---------------------------------------------------------------------------
bool WCConnect(void)
{
   if (mysql!=NULL) return true;

   mysql=NULL;
   mysql=new MYSQL;
   if ( !mysql )
   {
     return false;
   }
   if (mysql_connect(mysql,opts.DBHost.c_str(),opts.DBLogin.c_str(),opts.DBPasswd.c_str()))
   {
     mysql_select_db(mysql,opts.DBName.c_str());
     if (0!=mysql_errno(mysql))
     {
       return false;
     }
   }
   else
   {
     return false;
   }
   return true;
}
main(int argc, char *argv[]) {

    struct tm tm;
    struct timeval t0, t1;
    char mdate[20];
    char mtime[20];
    time_t t;
    suseconds_t	ut0, ut1;
//    FILE *file;
//    char size_file_name[40] = "";

    /* Get current time */
    gettimeofday(&t0, NULL);
    t=t0.tv_sec;
    ut0=t0.tv_usec;
    localtime_r(&t, &tm);
    strftime(mdate, 128, DATE_FORMAT, &tm);
    strftime(mtime, 128, TIME_FORMAT, &tm);

    char buff[2048] = "";

    // assign variables

    if (argv[1])
        strcpy(src, argv[1]);
//    if (argv[2])
//        strcpy(dst, argv[2]);

    // info to log file
    //my_debug("");
    sprintf(buff, "Date: %s %s, src/file name/uniqueid: %s", mdate, mtime, src);
    my_debug(buff);


    // check for errors

    if (!strlen(src)) {
        my_debug("No source provided, aborting...");
        return 0;
    }


    sprintf(full_filename_wav, "/tmp/%s.wav", src);
    my_debug(full_filename_wav);

    sprintf(mp3_in_tmp, "/tmp/%s.mp3", src);
    my_debug(mp3_in_tmp);


    if (!file_exists(full_filename_wav)){
        sprintf(buff, "No source WAV file %s found, aborting...", full_filename_wav);
	my_debug(buff);
        return 0;
    }



    sprintf(final_dst, "%s%s.mp3", final_folder, src);
    my_debug(final_dst);

    // convert file

    sprintf(buff, "/usr/local/bin/lame --resample 44.1 -b 32 -a %s %s", full_filename_wav, mp3_in_tmp);
    my_debug(buff);
    system(buff);


    if (!file_exists(mp3_in_tmp)){
        my_debug("Error converting WAV to MP3");
        return 0;
    } else {
        // move to correct location
        sprintf(buff, "mv %s %s", mp3_in_tmp, final_folder);
        my_debug(buff);
        system(buff);
    }

    mp3_size = file_size(final_dst);
    sprintf(buff, "MP3 size: %li", mp3_size);
    my_debug(buff);


    // delete uploaded wav file
    sprintf(buff, "rm %s", full_filename_wav);
    my_debug(buff);
    system(buff);

/*
    sprintf(size_file_name, "/tmp/%s", src);
    file = fopen(size_file_name,"a+");
    fprintf(file,"%li", mp3_size);
    fclose(file);
*/


    // connect to db

    read_config();

    if (!mysql_connect()) {
        my_debug("Cannot connect to DB, aborting...");
	return 0;
    }

    // update size of recording
    sprintf(buff,"UPDATE recordings SET size = '%li' WHERE uniqueid = '%s';", mp3_size, src);
    my_debug(buff);
    mysql_query(&mysql,buff);


    // rec sending/deleting over email script
    my_debug("Executing recording email/deleting control script");
    sprintf(buff, "/usr/local/mor/mor_record_control %s 0", src);
    my_debug(buff);
    system(buff);


    gettimeofday(&t1, NULL);
    ut1=t1.tv_usec;

    mysql_close(&mysql);

    my_debug("Script completed.\n\n");


}
Esempio n. 16
0
/**
* Open a connection to a MySQL Server
*/
static int Lmysql_connect (lua_State *L) {
    lua_mysql_conn *my_conn = (lua_mysql_conn *)lua_newuserdata(L, sizeof(lua_mysql_conn));
    luaM_setmeta (L, LUA_MYSQL_CONN);

    char *host = NULL, *socket=NULL, *tmp=NULL, *host_and_port;
    const char *host_and_port_tmp = luaL_optstring(L, 1, NULL);
    const char *user = luaL_optstring(L, 2, NULL);
    const char *passwd = luaL_optstring(L, 3, NULL);

    int port = MYSQL_PORT;
    
    MYSQL *conn;

    conn = mysql_init(NULL);  
    if ( ! conn) {  
        return luaM_msg (L, 0, "Error: mysql_init failed !");
    }

	host_and_port = strdup(host_and_port_tmp); // const char to char
	// parser : hostname:port:/path/to/socket or hostname:port or hostname:/path/to/socket or :/path/to/socket
    if (host_and_port && (strchr(host_and_port, ':'))) {
		tmp = strtok(host_and_port, ":");

		if (host_and_port[0] != ':') {
			host = tmp;
			tmp = strtok(NULL, ":");
		}

		if (tmp[0] != '/') {
			port = atoi(tmp);
			if ((tmp=strtok(NULL, ":"))) {
				socket = tmp;
			}
		} else {
			socket = tmp;
		}
	}
	else {
        host = host_and_port;
	}
	
#if MYSQL_VERSION_ID < 32200
    mysql_port = port;
#endif

#if MYSQL_VERSION_ID > 32199 /* this lets us set the port number */
    if ( ! mysql_real_connect(conn, host, user, passwd, NULL, port, socket, 0)) {
#else
    if ( ! mysql_connect(conn, host, user, passwd)) {
#endif

        mysql_close (conn); /* Close conn if connect failed */
        return luaM_msg (L, 0, mysql_error(conn));
    }

    /* fill in structure */
    my_conn->closed = 0;
    my_conn->env = LUA_NOREF;
    my_conn->conn = conn;

	/* free memory */
	free(host_and_port);
    return 1;
}

/**
* Select a MySQL database
*/
static int Lmysql_select_db (lua_State *L) {
    lua_mysql_conn *my_conn = Mget_conn (L);
    const char *db = luaL_checkstring (L, 2);

    if (mysql_select_db(my_conn->conn, db) != 0) {
        return luaM_msg (L, 0, mysql_error(my_conn->conn));
    }
    else {
		lua_pushboolean(L, 1);
		return 1;
    }
}
Esempio n. 17
0
void BuildDataBase (art *articles, int num_of_articles, char *newsgroup) {
   MYSQL mysql, *con;
   MYSQL_RES *res;
   MYSQL_ROW row;
   char query[MAX_QUERY];
   int x;
   char *table_name;

   table_name = (char *) malloc (1024);
   strcpy (table_name, newsgroup);
   Substitute (&table_name, ".", "", 1, 1);
   Substitute (&table_name, "/", "", 1, 1);

   /* printf ("(((%s))))", table_name); */

   /* ---- Connect to database server. ---- */
   if( !(con = mysql_connect(&mysql, HOSTNAME, USERNAME,PASSWORD)) ) {
      error("Could not connect.");
   }
	
   /* ---- Select DataBase. ---- */
   if (mysql_select_db(con, DATABASE)){
      error("Could not select DataBase.");
   }

   /* ---- Drop the students table ----<<<<<<<<<<<<<<<<<< DELETE */
   strcpy (query, "drop table ");
   strcat (query, table_name);
	
   if(mysql_query(con,query)) {
   }

   /* ----- Form Query for creating table --- */
   clrstr (query);
   strcat (query, "create table ");
   strcat (query, table_name);
   strcat (query, " (");
   strcat (query, "filename char(10),");
   strcat (query, "threadposn int,");
   strcat (query, "messageid char(100) not null,");
   strcat (query, "reference char(100),");
   strcat (query, "date char(40),");
   strcat (query, "subject char(100),");
   strcat (query, "msg_from char(100),");
   strcat (query, "nlines int,");
   strcat (query, "primary key(messageid) )");
	
   /* ----- Create table. ----- */
   if(mysql_query(con, query)){
      error("could not create table");
   }
	
   /* ----- insert records into the table --- */
   for (x = 0; x < num_of_articles; x++) {
      clrstr(query);
      if (articles[x].reference_field == NULL) {
         strcat (query, BuildInsertQuerySpecial (articles, x, table_name));
      } else {
         strcat (query, BuildInsertQuery (articles, x, table_name));
      }

      if (mysql_query (con, query)) {
         printf ("Could not insert record!!!! ");
         printf ("Failure to insert: %s\n", query);
      }
   }
	
   /* ---- Let us look at what we inserted ---- */
   clrstr(query);
   strcpy(query, "select * from ");
   strcat(query, table_name);
   strcat(query, " where threadposn = 1 order by messageid");
	
   if(mysql_query(con, query)) {
      error("! select 1");
   }	

   /* ---- Store results from query into res structure. ---- */
   if (!(res = mysql_store_result(con))){
      error("! store 1");
   }
   while ((row = mysql_fetch_row(res))) {
      printf("%s %s %s %s\n", row[2], row[4], row[5], row[6]);
   }

   /* ---- Drop the students table ---- */
   strcpy (query, "drop table ");
   strcat (query, table_name);

   /* ================== dropping table ===================== 	
   if(mysql_query(con,query)) {
      error("! drop 1");
   }
   =================== dropping table ===================== */
	
   /* ---- Finally close connection to server ---- */
   mysql_close(con);
}
Esempio n. 18
0
int wn_db_connect (wn_db_t *db) {
	int i = 0;

	if (!db) {
		wn_report_error (WE_PARAM, "wn_db_connect: invalid db connection");
		return 0;
	}

	if (db->connected)
		return 1;

	while (i < MAX_RETRY) {
#if MYSQL_VERSION_ID >= 32200
	  if (mysql_real_connect (&(db->conn), NULL, cfg_DB_USER, cfg_DB_PASS, cfg_DB_NAME, 0, NULL, 0)) {
#else
 	 if (mysql_connect (&(db->conn), NULL, cfg_DB_USER, cfg_DB_PASS) && !mysql_select_db (&(db->conn), cfg_DB_NAME)) {
#endif
			db->connected = 1;
			return 1;
		}

		sleep (1);
		i++;
	}

	wn_report_error (WE_DB, "wn_db_connect: %s\n", mysql_error (&(db->conn)));
	return 0;
}

int wn_db_query (wn_db_t *db, int res_idx, char *sql, ...) {
	char buf[MAX_SIZE];
	va_list ap;

	if (!db || !sql) {
		wn_report_error (WE_PARAM, "wn_db_query: database or query not given");
		return 0;
	}

	if ((res_idx < 0) || (res_idx >= MAX_RES)) {
		wn_report_error (WE_PARAM, "wn_db_query: result index out of bounds");
		return 0;
	}

	if (!db->connected) 
		wn_db_connect (db);

	if (!db->connected) {
		wn_report_error (WE_DB, "wn_db_query: database is not connected");
		return 0;
	}
		
	wn_db_release (db, res_idx);

	va_start (ap, sql);
	vsprintf (buf, sql, ap);
	va_end (ap);

	if (mysql_query (&(db->conn), buf)) {
		if (strstr (mysql_error (&(db->conn)), "away") ||
			  strstr (mysql_error (&(db->conn)), "connect")) {
			mysql_close (&(db->conn));
			db->connected = 0;
			if (!wn_db_connect (db) || (mysql_query (&(db->conn), buf))) {
				wn_report_error (WE_DB, "wn_db_query: %s", mysql_error (&(db->conn)));
				return 0;
			}
		} else {
			wn_report_error (WE_DB, "wn_db_query: %s", mysql_error (&(db->conn)));
			return 0;
		}
	}
	
	if ((!strncmp (buf, "update", 6)) || (!strncmp (buf, "insert", 6)) ||
	    (!strncmp (buf, "delete", 6))) 
		return 1;

	if (!(db->res[res_idx] = mysql_store_result (&(db->conn)))) {
		if (mysql_num_fields (&(db->conn))) {
			wn_report_error (WE_DB, "%s", mysql_error (&(db->conn)));
			return 0;
		} else
			return 0;  /* however, here it is not an error.. (hm?) */
	}

	db->has_result[res_idx] = 1;
	return 1;
}
Esempio n. 19
0
int update_mysql(dp_species_t sessType, dp_uid_t uid, int score, int won)
{
	MYSQL *mysql;
	MYSQL_RES *res;
	MYSQL_FIELD *field;
	MYSQL_ROW row;
	char tablename[16];
	char query[2048];
	char *errormsg;
	long score_sum;
	long score_max;
	int err;
	int i;

	mysql = mysql_connect(mysql, "localhost", "dank", "");
	if (!mysql) {
		errormsg = mysql_error(mysql);
		DPRINT(("wmq2mysql: connect error: %s\n", errormsg));
		return 1;
	}

	err = mysql_select_db(mysql, "alink");
	if (err) {
		errormsg = mysql_error(mysql);
		printf("select_db(alink) error: %d %s\n", err, errormsg);
		return 1;
	}

	sprintf(tablename, "score_%d", sessType);
	sprintf(query, "select score_sum, score_max from %s where uid=%d", tablename, uid);
	err = mysql_query(mysql, query);
	if (err) {
		errormsg = mysql_error(mysql);
		DPRINT(("wmq2mysql: query: %s\n    error: %d %s\n", query, err, errormsg));
		return 1;
	}

	res = mysql_store_result(mysql);
	if (res == NULL) {
		errormsg = mysql_error(mysql);
		if (errormsg) {
			DPRINT(("wmq2mysql: store_result error: %s\n", errormsg));
			return 1;
		}
		DPRINT(("wmq2mysql: No results\n"));
		return 0;
	}

	row = mysql_fetch_row(res);
	assert(row != NULL);
	score_sum = atol(row[0]);
	score_max = atol(row[1]);
	assert(NULL == mysql_fetch_row(res));

	DPRINT(("wmq2mysql: old score_sum:%d score_max:%d\n", score_sum, score_max));
	score_sum += score;
	if (score > score_max)
		score_max = score;

	sprintf(query, "update %s set score_sum=%d, score_max=%d where uid=%d", tablename, score_sum, score_max, uid);
	err = mysql_query(mysql, query);
	if (err) {
		errormsg = mysql_error(mysql);
		DPRINT(("wmq2mysql: query: %s\n    error: %d %s\n", query, err, errormsg));
		return 1;
	}
	assert(1 == mysql_affected_rows(mysql));

	mysql_close(mysql);
	return 0;
}
Esempio n. 20
0
int main(int argc, char *argv[])
{
    char buff[100];
    char str[100];
    int i;

    time_t now;

    MYSQL_RES   *result;
    MYSQL_ROW   row;

    char *variable;
    char *value;

    // variables

    int accountcode;
    char extension[50];

    // initial values
    strcpy(extension, "");




//	strcpy(datetime,"");

    AGITool_Init(&agi);

    AGITool_verbose(&agi, &res, "", 0);
    AGITool_verbose(&agi, &res, "MOR Acc2User AGI script started.", 0);


    // DB connection
    read_config();

//	sprintf(str, "Host: %s, dbname: %s, user: %s, psw: %s, port: %i", dbhost, dbname, dbuser, dbpass, dbport);
//	AGITool_verbose(&agi, &res, str, 0);


    if (!mysql_connect()) {

        AGITool_verbose(&agi, &res, "ERROR! Not connected to database.", 0);
        AGITool_Destroy(&agi);
        return 0;
    } else {
        AGITool_verbose(&agi, &res, "Successfully connected to database.", 0);
    }


    accountcode = atoi(AGITool_ListGetVal(agi.agi_vars, "agi_accountcode"));

    sprintf(str, "Accountcode: %i", accountcode);
    AGITool_verbose(&agi, &res, str, 0);


    // ------- get user details -----

    sprintf(sqlcmd, "SELECT devices.extension FROM devices WHERE devices.id = '%i';", accountcode);

    if (mysql_query(&mysql,sqlcmd)) {
        // error
        //res = -1;
    } else {
        // query succeeded, process any data returned by it
        result = mysql_store_result(&mysql);
        if (result) {
            // there are rows
            //i = 0;
            while ((row = mysql_fetch_row(result))) {
                if (row[0]) strcpy(extension, row[0]);
            }
            mysql_free_result(result);
        }
    }

    AGITool_set_variable(&agi, &res, "BLA", extension);

    sprintf(str, "Extension: %s", extension);
    AGITool_verbose(&agi, &res, str, 0);


//	strcpy(variable, "MOR_DEVICE_EXT");
    //strcpy(value, extension);

//	sprintf(value, "%s", extension);

    AGITool_set_variable(&agi, &res, "MOR_EXT", extension);



    AGITool_verbose(&agi, &res, "MOR Acc2User AGI script stopped.", 0);
    AGITool_verbose(&agi, &res, "", 0);

    AGITool_Destroy(&agi);
    mysql_close(&mysql);

    return 0;
}
Esempio n. 21
0
int msMySQLJoinConnect(layerObj *layer, joinObj *join) 
{
   
#ifndef USE_MYSQL
  msSetError(MS_QUERYERR, "MySQL support not available (compile with --with-mysql)", "msMySQLJoinConnect()");
  return(MS_FAILURE);
#else
  int i;
  char qbuf[4000];
  char *conn_decrypted;
  msMySQLJoinInfo *joininfo;

  MYDEBUG if (setvbuf(stdout, NULL, _IONBF , 0)){printf("Whoops...");};
  if(join->joininfo) return(MS_SUCCESS); /* already open */
    
  /* allocate a msMySQLJoinInfo struct */
  joininfo = (msMySQLJoinInfo *) malloc(sizeof(msMySQLJoinInfo));
  if(!joininfo) {
    msSetError(MS_MEMERR, "Error allocating mysql table info structure.", "msMySQLJoinConnect()");
    return(MS_FAILURE);
  }

  /* initialize any members that won't get set later on in this function */
  joininfo->qresult = NULL;
  joininfo->target = NULL;
  joininfo->nextrecord = 0;

  join->joininfo = joininfo;

  /* open the mysql connection */

  if( join->connection == NULL ) {
      msSetError(MS_QUERYERR, "Error parsing MYSQL JOIN: nothing specified in CONNECTION statement.",
      "msMySQLJoinConnect()");

        return(MS_FAILURE);
    }
  
    conn_decrypted = msDecryptStringTokens(layer->map, join->connection);
    if (conn_decrypted == NULL) {
      msSetError(MS_QUERYERR, "Error parsing MYSQL JOIN: unable to decrypt CONNECTION statement.",
                 "msMySQLJoinConnect()");
      return(MS_FAILURE);
    }
  
    delim = msStrdup(":");
    DB_HOST = msStrdup(strtok(conn_decrypted, delim));
    DB_USER = msStrdup(strtok(NULL, delim));
    DB_PASSWD = msStrdup(strtok(NULL, delim));
    DB_DATABASE = msStrdup(strtok(NULL, delim));
    free(conn_decrypted);

    if (DB_HOST == NULL || DB_USER == NULL || DB_PASSWD == NULL || DB_DATABASE == NULL)
    {
      msSetError(MS_QUERYERR, "DB param error: at least one of HOST, USER, PASSWD or DATABASE is null!", "msMySQLJoinConnect()");
      return MS_FAILURE;
    }
    if (strcmp(DB_PASSWD, "none") == 0) strcpy(DB_PASSWD, "");

#if MYSQL_VERSION_ID >= 40000
    mysql_init(&(joininfo->mysql));
    if (!(joininfo->conn = mysql_real_connect(&(joininfo->mysql),DB_HOST,DB_USER,DB_PASSWD,NULL, 0, NULL, 0)))
#else
    if (!(joininfo->conn = mysql_connect(&(joininfo->mysql),DB_HOST,DB_USER,DB_PASSWD)))
#endif
    {
        char tmp[4000];
        snprintf( tmp, sizeof(tmp), "Failed to connect to SQL server: Error: %s\nHost: %s\nUsername:%s\nPassword:%s\n", mysql_error(joininfo->conn), DB_HOST, DB_USER, DB_PASSWD);
        msSetError(MS_QUERYERR, tmp,
           "msMYSQLLayerOpen()");
        free(joininfo);
        return MS_FAILURE;
    }

    MYDEBUG printf("msMYSQLLayerOpen2 called<br>\n");
    if (mysql_select_db(joininfo->conn,DB_DATABASE) < 0)
    {
      mysql_close(joininfo->conn);
		}
    MYDEBUG printf("msMYSQLLayerOpen3 called<br>\n");
		if (joininfo->qresult != NULL) /* query leftover */
		{
    	MYDEBUG printf("msMYSQLLayerOpen4 called<br>\n");
			mysql_free_result(joininfo->qresult);
		}
    MYDEBUG printf("msMYSQLLayerOpen5 called<br>\n");
               snprintf(qbuf, sizeof(qbuf), "SELECT count(%s) FROM %s", join->to, join->table);
		MYDEBUG printf("%s<br>\n", qbuf);
   	if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) /* There were some rows found, write 'em out for debug */
		{
	  		int numrows = mysql_affected_rows(joininfo->conn);
				MYDEBUG printf("%d rows<br>\n", numrows);
        for(i=0;i<numrows;i++)
        {
            MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
            MYDEBUG printf("(%s)<BR>\n",row[0]);
						joininfo->rows = atoi(row[0]);
        }
		} else { 
    	msSetError(MS_DBFERR, "Item %s not found in table %s.", "msMySQLJoinConnect()", join->to, join->table); 
	    return(MS_FAILURE);
		}
		snprintf(qbuf, sizeof(qbuf), "EXPLAIN %s", join->table);
   	if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) /* There were some rows found, write 'em out for debug */
		{
	  		join->numitems = mysql_affected_rows(joininfo->conn);
			  if((join->items = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
				    msSetError(MS_MEMERR, NULL, "msMySQLJoinConnect()");
		  		  return(MS_FAILURE);
			  }
				MYDEBUG printf("%d rows<br>\n", join->numitems);
        for(i=0;i<join->numitems;i++)
        {
            MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
            MYDEBUG printf("(%s)<BR>\n",row[0]);
						join->items[i] = msStrdup(row[0]);
        }
		} else {
    	msSetError(MS_DBFERR, "Item %s not found in table %s.", "msMySQLJoinConnect()", join->to, join->table); 
	    return(MS_FAILURE);
		}
		joininfo->tocolumn = msStrdup(join->to);

	

  /* get "from" item index   */
  for(i=0; i<layer->numitems; i++) {
    if(strcasecmp(layer->items[i],join->from) == 0) { /* found it */
      joininfo->fromindex = i;
      break;
    }
  }

  if(i == layer->numitems) {
    msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msMySQLJoinConnect()", join->from, layer->name); 
    return(MS_FAILURE);
  }

  /* finally store away the item names in the XBase table */
  if(!join->items) return(MS_FAILURE);  

  return(MS_SUCCESS);
#endif
}
Esempio n. 22
0
int TLib_DB_SetDB(TLIB_DB_LINK *pstDBLink, char *sHostAddress, char *sUserName, char *sPassword, char *sDBName, char *sErrMsg)
{
    int iSelectDB;


    iSelectDB = 0;

    //判断是否设置了只要一个mysql的连接
    if (pstDBLink->iMultiDBConn==0)
    {
        //如果要连接的地址和当前的地址不是同一台机器则先close当前的连接,再重新建立连接
        if (strcmp(pstDBLink->pstCurMysqlConn->sHostAddress, sHostAddress) != 0)
        {
            if (pstDBLink->pstCurMysqlConn->iDBConnect==1)
            {
                TLib_DB_CloseDatabase(pstDBLink);
            }

            if (mysql_connect(&(pstDBLink->pstCurMysqlConn->stMysql), sHostAddress, sUserName, sPassword) == 0)
            {
                snprintf(sErrMsg,1024, "Fail To Connect To Mysql: %s", mysql_error(&(pstDBLink->pstCurMysqlConn->stMysql)));
                return -1;
            }
            pstDBLink->pstCurMysqlConn->iDBConnect=1;
            iSelectDB = 1;
        }
        else  //如果当前没有连接,则连接mysql ?? cyril:  如果当前地址和要联接的地址是同一台机器
        {
            if (pstDBLink->pstCurMysqlConn->iDBConnect==0) {
                if (mysql_connect(&(pstDBLink->pstCurMysqlConn->stMysql), sHostAddress, sUserName, sPassword) == 0) {
                    snprintf(sErrMsg,1024, "Fail To Connect To Mysql: %s", mysql_error(&(pstDBLink->pstCurMysqlConn->stMysql)));
                    return -1;
                }
                pstDBLink->pstCurMysqlConn->iDBConnect=1;
            }
            else {
                if(mysql_ping(&(pstDBLink->pstCurMysqlConn->stMysql)) != 0) {
                    snprintf(sErrMsg,1024, "Fail To ping To Mysql: %s", mysql_error(&(pstDBLink->pstCurMysqlConn->stMysql)));
                    return -1;
                }
            }
        }
    }
    //多个mysql连接的
    else
    {
        //如果要连接的地址和当前的地址不同
        if (strcmp(pstDBLink->pstCurMysqlConn->sHostAddress, sHostAddress) != 0) {

            TLIB_MYSQL_CONN *pstMysqlConn;
            TLIB_MYSQL_CONN *pstMysqlConnTail;//pstMysqlConnTail是尾指针

            //先释放现在的Res
            if (pstDBLink->iResNotNull == 1) {
                mysql_free_result(pstDBLink->pstRes);
                pstDBLink->iResNotNull=0;
            }

            //先寻找有没有已经连上这台HOST上的数据库
            pstMysqlConn=&(pstDBLink->stMysqlConn);
            pstMysqlConnTail=&(pstDBLink->stMysqlConn);

            while (pstMysqlConn!=NULL) {
                if (strcmp(pstMysqlConn->sHostAddress,sHostAddress) == 0) {
                    pstDBLink -> pstCurMysqlConn = pstMysqlConn;
                    if(mysql_ping(&(pstDBLink->pstCurMysqlConn->stMysql)) != 0) {
                        snprintf(sErrMsg,1024,"Fail To ping Mysql: %s",mysql_error(&(pstDBLink->pstCurMysqlConn->stMysql)));
                        return -1;
                    }
                    break;
                }
                pstMysqlConnTail=pstMysqlConn;
                pstMysqlConn = pstMysqlConn->pstNext;
                iSelectDB = 1;
            }

            //没有相同的则创建一个新的连接
            if(pstMysqlConn == NULL) {
                pstMysqlConn = (TLIB_MYSQL_CONN *)malloc(sizeof(TLIB_MYSQL_CONN));
                memset(pstMysqlConn, 0, sizeof(TLIB_MYSQL_CONN));
                mysql_init(&(pstMysqlConn->stMysql));
                pstMysqlConnTail -> pstNext=pstMysqlConn;
                pstMysqlConn -> pstNext = NULL;
            }

            pstDBLink -> pstCurMysqlConn = pstMysqlConn;

            if (pstDBLink -> pstCurMysqlConn -> iDBConnect == 0) {
                if (mysql_connect(&(pstDBLink->pstCurMysqlConn->stMysql), sHostAddress, sUserName, sPassword) == 0) {
                    snprintf(sErrMsg,1024, "Fail To Connect To Mysql: %s", mysql_error(&(pstDBLink->pstCurMysqlConn->stMysql)));
                    return -1;
                }

                //设置当前连接指针
                strncpy(pstDBLink->pstCurMysqlConn->sHostAddress, sHostAddress,strlen(sHostAddress)+1);
                pstDBLink->pstCurMysqlConn->iDBConnect=1;
                iSelectDB = 1;
            }
        }
        else if (pstDBLink->pstCurMysqlConn->iDBConnect==0)
        {
            if (mysql_connect(&(pstDBLink->pstCurMysqlConn->stMysql), sHostAddress, sUserName, sPassword) == 0) {
                snprintf(sErrMsg,1024, "Fail To Connect To Mysql: %s", mysql_error(&(pstDBLink->pstCurMysqlConn->stMysql)));
                return -1;
            }
            strncpy(pstDBLink->pstCurMysqlConn->sHostAddress, sHostAddress,strlen(sHostAddress)+1);
            pstDBLink->pstCurMysqlConn->iDBConnect=1;
            iSelectDB = 1;
        }
    }

//	if ((iSelectDB != 0) || (strcmp(pstDBLink->pstCurMysqlConn->sDBName, sDBName) != 0))
//	{
    if (mysql_select_db(&(pstDBLink->pstCurMysqlConn->stMysql), sDBName) < 0) {
        //TLib_DB_CloseDatabase(pstDBLink);
        snprintf(sErrMsg,1024, "Cannot Select Database %s: %s", sDBName, mysql_error(&(pstDBLink->pstCurMysqlConn->stMysql)));
        return -1;
    }
    strncpy(pstDBLink->pstCurMysqlConn->sDBName, sDBName,strlen(sDBName)+1);
//	}

    snprintf(sErrMsg,1024, "");

    return 0;
}
Esempio n. 23
0
File: debug.c Progetto: javigf/smRPi
/////////////////////////////////////////////////////////////////////////////////
//++++++++++++++++++++++ START READ PORTS FUNCTION ++++++++++++++++++++++++++++++
/////////////////////////////////////////////////////////////////////////////////
int readActivePorts (void){
	
	int size = sizeof (activePorts)/ sizeof (int);
	int result; 
	int lcontador = 0;
	
	if (!mysql_connect ()){
								
		if (!digitalRead (24))
			volts = 0;
		
		db_insert (2,0,volts);
		db_update (2,0,0);
		
		if (!digitalRead (21))	
			humo = 70;
		
		db_insert (6,0,humo);
		db_update (6,0,0);
		humo = 20;
		
		if (!digitalRead (22))
			humo = 70;
		
		db_insert (6,1,humo);
		db_update (6,1,0);

		fileRead ();

		for  (int i=0 ; ((i < MAXPORTS) && (i < size)) ; i++){ 
			
			result = displayDHTData (activePorts[i]);
			if(!result){
	
				db_insert (0,i,temperature);
				db_update (0,i,0);
				fprintf(fr, "%2.1f\t", temperature);

				db_insert (1,i,humidity);
				db_update (1,i,0);
				fprintf(fr, "%2.1f\t", humidity);

				db_insert (4,i,dewPoint);
				db_update (4,i,0);
				fprintf(fr, "%2.1f\n", dewPoint);
				//lcontador = 0;
					
			}
			//else {
				//if ((result == 20) && (lcontador < MAX_ERRORS)){
				//	++lcontador;
				//	--i;
				//}
			else if (result == 20){
				
				for (int j = 1; j < i;  j++){					
					fscanf(fr, "%*f %*f %*f");
					//printf ("J:%d\n",j);
					//printf ("I:%d\n",i);
				}
					
				fscanf(fr, "%f %f %f", &temperature, &humidity, &dewPoint);

				fprintf(stderr, "New value T %2.1f\n", temperature);
				fprintf(stderr, "New value H %2.1f\n", humidity);
				fprintf(stderr, "New value D %2.1f\n", dewPoint);
					
				db_insert (0,i,temperature);
				db_update (0,i,0);
					
				db_insert (1,i,humidity);
				db_update (1,i,0);
				
				db_insert (4,i,dewPoint);
				db_update (4,i,0);
				//	lcontador = 0;
			}
			else if (result == 10){
					db_update (0,i,result);
					db_update (1,i,result);
					db_update (4,i,result);
					//lcontador = 0;
			}
		}
		//fflush (fr);
		fclose (fr);
		printf("File Closed\n");
		mysql_disconnect ();
	}

	return 0;
}
Esempio n. 24
0
static int do_connect()
{
const	char *server;
const	char *userid;
const	char *password;
const	char *database;
const	char *server_socket=0;
unsigned int server_port=0;
unsigned int server_opt=0;
const	char *p;

const	char *sslkey;
const	char *sslcert;
const	char *sslcacert;
const	char *sslcapath;
const	char *sslcipher;
unsigned int  use_ssl=0;

/*
** Periodically detect dead connections.
*/
	if (mysql)
	{
		static time_t last_time=0;
		time_t t_check;

		time(&t_check);

		if (t_check < last_time)
			last_time=t_check;	/* System clock changed */

		if (t_check < last_time + 60)
			return (0);

		last_time=t_check;
			
		if (mysql_ping(mysql) == 0) return (0);

		DPRINTF("authmysqllib: mysql_ping failed, connection lost");
		mysql_close(mysql);
		mysql=0;
	}

	server=read_env("MYSQL_SERVER");
	userid=read_env("MYSQL_USERNAME");
	password=read_env("MYSQL_PASSWORD");
	database=read_env("MYSQL_DATABASE");

#if MYSQL_VERSION_ID >= 32200
	sslkey=read_env("MYSQL_SSL_KEY");
	sslcert=read_env("MYSQL_SSL_CERT");
	sslcacert=read_env("MYSQL_SSL_CACERT");
	sslcapath=read_env("MYSQL_SSL_CAPATH");
	sslcipher=read_env("MYSQL_SSL_CIPHER");

	if ((sslcert != NULL) && ((sslcacert != NULL) || (sslcapath != NULL)))
	{
		use_ssl=1;
	}
#endif

	server_socket=(char *) read_env("MYSQL_SOCKET");

	if ((p=read_env("MYSQL_PORT")) != 0)
	{
		server_port=(unsigned int) atoi(p);
	}

	if ((p=read_env("MYSQL_OPT")) != 0)
	{
		server_opt=(unsigned int) atol(p);
	}

	if (!server && !server_socket)
	{
		err("authmysql: MYSQL_SERVER nor MYSQL_SOCKET set in"
			AUTHMYSQLRC ".");
		return (-1);
	}

	if (!userid)
	{
		err("authmysql: MYSQL_USERNAME not set in "
			AUTHMYSQLRC ".");
		return (-1);
	}

	if (!database)
	{
		err("authmysql: MYSQL_DATABASE not set in "
			AUTHMYSQLRC ".");
		return (-1);
	}

#if MYSQL_VERSION_ID >= 32200
	mysql_init(&mysql_buf);
	if (use_ssl)
	{
		mysql_ssl_set(&mysql_buf, sslkey, sslcert, sslcacert,
			      sslcapath, sslcipher);
	}
	mysql=mysql_real_connect(&mysql_buf, server, userid, password,
				 NULL,
				 server_port,
				 server_socket,
				 server_opt);
#else
	mysql=mysql_connect(&mysql_buf, server, userid, password);
#endif
	if (!mysql)
	{
		err("failed to connect to mysql server (server=%s, userid=%s): %s",
			server ? server : "<null>",
			userid ? userid : "<null>",
			mysql_error(&mysql_buf));
		return (-1);
	}

	if (mysql_select_db(mysql, database))
	{
		err("authmysql: mysql_select_db(%s) error: %s",
			database, mysql_error(mysql));
		mysql_close(mysql);
		mysql=0;
		return (-1);
	}
	
	DPRINTF("authmysqllib: connected. Versions: "
		"header %lu, "
		"client %lu, "
		"server %lu",
		(long)MYSQL_VERSION_ID,
		mysql_get_client_version(),
		mysql_get_server_version(mysql));

	set_session_options();	
	return (0);
}