コード例 #1
0
ファイル: my_con.c プロジェクト: BackupTheBerlios/ser
int my_con_connect(db_con_t* con)
{
	struct my_con* mcon;
	struct my_uri* muri;
	
	mcon = DB_GET_PAYLOAD(con);
	muri = DB_GET_PAYLOAD(con->uri);
	
	/* Do not reconnect already connected connections */
	if (mcon->flags & MY_CONNECTED) return 0;

	DBG("mysql: Connecting to %.*s:%.*s\n",
		con->uri->scheme.len, ZSW(con->uri->scheme.s),
		con->uri->body.len, ZSW(con->uri->body.s));

	if (my_connect_to) {
		if (mysql_options(mcon->con, MYSQL_OPT_CONNECT_TIMEOUT, 
						  (char*)&my_connect_to))
			WARN("mysql: failed to set MYSQL_OPT_CONNECT_TIMEOUT\n");
	}

#if MYSQL_VERSION_ID >= 40101 
	if ((my_client_ver >= 50025) || 
		((my_client_ver >= 40122) && 
		 (my_client_ver < 50000))) {
		if (my_send_to) {
			if (mysql_options(mcon->con, MYSQL_OPT_WRITE_TIMEOUT , 
							  (char*)&my_send_to))
				WARN("mysql: failed to set MYSQL_OPT_WRITE_TIMEOUT\n");
		}
		if (my_recv_to){
			if (mysql_options(mcon->con, MYSQL_OPT_READ_TIMEOUT , 
							  (char*)&my_recv_to))
				WARN("mysql: failed to set MYSQL_OPT_READ_TIMEOUT\n");
		}
	}
#endif
	
	if (!mysql_real_connect(mcon->con, muri->host, muri->username, 
							muri->password, muri->database, muri->port, 0, 0)) {
		LOG(L_ERR, "mysql: %s\n", mysql_error(mcon->con));
		return -1;
	}
	
	DBG("mysql: Connection type is %s\n", mysql_get_host_info(mcon->con));
	DBG("mysql: Protocol version is %d\n", mysql_get_proto_info(mcon->con));
	DBG("mysql: Server version is %s\n", mysql_get_server_info(mcon->con));

	mcon->flags |= MY_CONNECTED;

	/* Increase the variable that keeps track of number of connects performed
	 * on this connection. The mysql module uses the variable to determine
	 * when a pre-compiled command needs to be uploaded to the server again.
	 * If the number in the my_con structure is large than the number kept
	 * in my_cmd then it means that we have to upload the command to the server
	 * again because the connection was reconnected meanwhile.
	 */
	mcon->resets++;
	return 0;
}
コード例 #2
0
ファイル: my_con.c プロジェクト: 4N7HR4X/kamailio
int my_con_connect(db_con_t* con)
{
	struct my_con* mcon;
	struct my_uri* muri;
	
	mcon = DB_GET_PAYLOAD(con);
	muri = DB_GET_PAYLOAD(con->uri);
	
	/* Do not reconnect already connected connections */
	if (mcon->flags & MY_CONNECTED) return 0;

	DBG("mysql: Connecting to %.*s:%.*s\n",
		con->uri->scheme.len, ZSW(con->uri->scheme.s),
		con->uri->body.len, ZSW(con->uri->body.s));

	if (my_connect_to) {
		if (mysql_options(mcon->con, MYSQL_OPT_CONNECT_TIMEOUT, 
						  (char*)&my_connect_to))
			WARN("mysql: failed to set MYSQL_OPT_CONNECT_TIMEOUT\n");
	}

#if MYSQL_VERSION_ID >= 40101 
	if ((my_client_ver >= 50025) || 
		((my_client_ver >= 40122) && 
		 (my_client_ver < 50000))) {
		if (my_send_to) {
			if (mysql_options(mcon->con, MYSQL_OPT_WRITE_TIMEOUT , 
							  (char*)&my_send_to))
				WARN("mysql: failed to set MYSQL_OPT_WRITE_TIMEOUT\n");
		}
		if (my_recv_to){
			if (mysql_options(mcon->con, MYSQL_OPT_READ_TIMEOUT , 
							  (char*)&my_recv_to))
				WARN("mysql: failed to set MYSQL_OPT_READ_TIMEOUT\n");
		}
	}
#endif
	
	if (!mysql_real_connect(mcon->con, muri->host, muri->username, 
							muri->password, muri->database, muri->port, 0, 0)) {
		LOG(L_ERR, "mysql: %s\n", mysql_error(mcon->con));
		return -1;
	}
	
	DBG("mysql: Connection type is %s\n", mysql_get_host_info(mcon->con));
	DBG("mysql: Protocol version is %d\n", mysql_get_proto_info(mcon->con));
	DBG("mysql: Server version is %s\n", mysql_get_server_info(mcon->con));

	mcon->flags |= MY_CONNECTED;
	return 0;
}
コード例 #3
0
ファイル: mysql.c プロジェクト: gnosek/collectd
static MYSQL *getconnection (mysql_database_t *db)
{
	if (db->state != 0)
	{
		int err;
		if ((err = mysql_ping (db->con)) != 0)
		{
			/* Assured by "mysql_config_database" */
			assert (db->instance != NULL);
			WARNING ("mysql_ping failed for instance \"%s\": %s",
					db->instance,
					mysql_error (db->con));
			db->state = 0;
		}
		else
		{
			db->state = 1;
			return (db->con);
		}
	}

	if ((db->con = mysql_init (db->con)) == NULL)
	{
		ERROR ("mysql_init failed: %s", mysql_error (db->con));
		db->state = 0;
		return (NULL);
	}

	if (mysql_real_connect (db->con, db->host, db->user, db->pass,
				db->database, db->port, db->socket, 0) == NULL)
	{
		ERROR ("mysql plugin: Failed to connect to database %s "
				"at server %s: %s",
				(db->database != NULL) ? db->database : "<none>",
				(db->host != NULL) ? db->host : "localhost",
				mysql_error (db->con));
		db->state = 0;
		return (NULL);
	}
	else
	{
		INFO ("mysql plugin: Successfully connected to database %s "
				"at server %s (server version: %s, protocol version: %d)",
				(db->database != NULL) ? db->database : "<none>",
				mysql_get_host_info (db->con),
				mysql_get_server_info (db->con),
				mysql_get_proto_info (db->con));
		db->state = 1;
		return (db->con);
	}
} /* static MYSQL *getconnection (mysql_database_t *db) */
コード例 #4
0
ファイル: mysql.c プロジェクト: brd/collectd
static MYSQL *getconnection (mysql_database_t *db)
{
    if (db->is_connected)
    {
        int status;

        status = mysql_ping (db->con);
        if (status == 0)
            return (db->con);

        WARNING ("mysql plugin: Lost connection to instance \"%s\": %s",
                 db->instance, mysql_error (db->con));
    }
    db->is_connected = 0;

    if (db->con == NULL)
    {
        db->con = mysql_init (NULL);
        if (db->con == NULL)
        {
            ERROR ("mysql plugin: mysql_init failed: %s",
                   mysql_error (db->con));
            return (NULL);
        }
    }

    /* Configure TCP connect timeout (default: 0) */
    db->con->options.connect_timeout = db->timeout;

    if (mysql_real_connect (db->con, db->host, db->user, db->pass,
                            db->database, db->port, db->socket, 0) == NULL)
    {
        ERROR ("mysql plugin: Failed to connect to database %s "
               "at server %s: %s",
               (db->database != NULL) ? db->database : "<none>",
               (db->host != NULL) ? db->host : "localhost",
               mysql_error (db->con));
        return (NULL);
    }

    INFO ("mysql plugin: Successfully connected to database %s "
          "at server %s (server version: %s, protocol version: %d)",
          (db->database != NULL) ? db->database : "<none>",
          mysql_get_host_info (db->con),
          mysql_get_server_info (db->con),
          mysql_get_proto_info (db->con));

    db->is_connected = 1;
    return (db->con);
} /* static MYSQL *getconnection (mysql_database_t *db) */
コード例 #5
0
ファイル: mysql_ser.c プロジェクト: AmesianX/restund
static int myconnect(void)
{
	mysql_init(&my.mysql);

	if (!mysql_real_connect(&my.mysql, my.host, my.user, my.pass, my.db,
				0, NULL, 0))
		return(ECONNREFUSED);

	restund_debug("mysql: connected (server %s at %s)\n",
		      mysql_get_server_info(&my.mysql),
		      mysql_get_host_info(&my.mysql));

	return 0;
}
コード例 #6
0
ファイル: AMySQLServer.cpp プロジェクト: achacha/AOS
void AMySQLServer::emit(AXmlElement& target) const
{
  if (target.useName().isEmpty())
    target.useName().assign("AMySQLServer", 12);

  ADatabase::emitXml(target);

  target.addElement(ASW("client",6)).addData(mysql_get_client_info());
  if (mp_mydata)
  {
    target.addElement(ASW("stat",4)).addData(mysql_stat(mp_mydata)); 
    target.addElement(ASW("server",6)).addData(mysql_get_server_info(mp_mydata)); 
    target.addElement(ASW("host",4)).addData(mysql_get_host_info(mp_mydata)); 
  }
}
コード例 #7
0
ファイル: Database.cpp プロジェクト: 100acrebb/MySQLOO
/* Thread that connects to the database, on success it continues to handle queries in the run method.
 */
void Database::connectRun()
{
	LOG_CURRENT_FUNCTIONCALL
	mysql_thread_init();
	auto threadEnd = finally([&] { mysql_thread_end(); });
	{
		auto connectionSignaliser = finally([&] { m_connectWakeupVariable.notify_one(); });
		std::lock_guard<std::mutex>(this->m_connectMutex);
		this->m_sql = mysql_init(nullptr);
		if (this->m_sql == nullptr)
		{
			m_success = false;
			m_connection_err = "Out of memory";
			m_connectionDone = true;
			m_status = DATABASE_CONNECTION_FAILED;
			return;
		}
		if (this->shouldAutoReconnect)
		{
			my_bool reconnect = 1;
			mysql_options(this->m_sql, MYSQL_OPT_RECONNECT, &reconnect);
		}
		const char* socket = (this->socket.length() == 0) ? nullptr : this->socket.c_str();
		unsigned long clientFlag = (this->useMultiStatements) ? CLIENT_MULTI_STATEMENTS : 0;
		if (mysql_real_connect(this->m_sql, this->host.c_str(), this->username.c_str(), this->pw.c_str(), 
			this->database.c_str(), this->port, socket, clientFlag) != this->m_sql)
		{
			m_success = false;
			m_connection_err = mysql_error(this->m_sql);
			m_connectionDone = true;
			m_status = DATABASE_CONNECTION_FAILED;
			return;
		}
		m_success = true;
		m_connection_err = "";
		m_connectionDone = true;
		m_status = DATABASE_CONNECTED;
		m_serverVersion = mysql_get_server_version(this->m_sql);
		m_serverInfo = mysql_get_server_info(this->m_sql);
		m_hostInfo = mysql_get_host_info(this->m_sql);
	}
	auto closeConnection = finally([&] { mysql_close(this->m_sql); this->m_sql = nullptr;  });
	if (m_success)
	{
		run();
	}
}
コード例 #8
0
	EErrorType CDatabaseConnectionMySql::DoConnect( String & connectionString )
	{
		EErrorType ret = EErrorType_NONE;

		try
		{
			_connection = mysql_init( NULL );

			if ( !_connection )
			{
				DB_EXCEPT( EDatabaseExceptionCodes_ConnectionError, ERROR_MYSQL_CONNECTION );
			}

			uint32_t timeout = 180;

			if ( mysql_options( _connection, MYSQL_OPT_CONNECT_TIMEOUT, &timeout ) )
			{
				CLogger::LogWarning( WARNING_MYSQL_UNKNOWN_OPTION + WARNING_MYSQL_OPT_CONNECT_TIMEOUT );
			}

			if ( !mysql_real_connect( _connection,
									  _server.c_str(),
									  _userName.c_str(),
									  _password.c_str(),
									  NULL,
									  0,
									  NULL,
									  CLIENT_REMEMBER_OPTIONS | CLIENT_MULTI_RESULTS ) )
			{
				StringStream error( ERROR_MYSQL_CONNECT );
				error << mysql_error( _connection );
				DB_EXCEPT( EDatabaseExceptionCodes_ConnectionError, error.str() );
			}

			MySQLCheck( mysql_set_character_set( _connection, MYSQL_OPTION_UTF8 ), INFO_MYSQL_SETTING_CHARSET, EDatabaseExceptionCodes_ConnectionError, _connection );

			CLogger::LogDebug( StringStream() << DEBUG_MYSQL_CONNECTED );
			CLogger::LogDebug( StringStream() << DEBUG_MYSQL_CLIENT_VERSION << mysql_get_client_info() );
			CLogger::LogDebug( StringStream() << DEBUG_MYSQL_SERVER_HOST << mysql_get_host_info( _connection ) );
			CLogger::LogDebug( StringStream() << DEBUG_MYSQL_SERVER_VERSION << mysql_get_server_info( _connection ) );
			DoSetConnected( true );
		}
		COMMON_CATCH( ERROR_MYSQL_CONNECTION )

		return ret;
	}
コード例 #9
0
static int test_bind_address(MYSQL *my)
{
  MYSQL *mysql;
  char *bind_addr= getenv("MYSQL_TEST_BINDADDR");
  char query[128];
  int rc;

  if (!hostname || !strcmp(hostname, "localhost"))
  {
    diag("test doesn't work with unix sockets");
    return SKIP;
  }

  sprintf(query, "DROP USER '%s'@'%s'", username, bind_addr);
  rc= mysql_query(my, query);

  sprintf(query, "CREATE USER '%s'@'%s'", username, bind_addr);
  rc= mysql_query(my, query);
  check_mysql_rc(rc, my);

  sprintf(query, "GRANT ALL ON %s.* TO '%s'@'%s'", schema, username, bind_addr);
  rc= mysql_query(my, query);
  check_mysql_rc(rc, my);

  if (!bind_addr)
  {
    diag("No bind address specified");
    return SKIP;
  }

  mysql= mysql_init(NULL);
  mysql_options(mysql, MYSQL_OPT_BIND, bind_addr);

  if (!mysql_real_connect(mysql, bind_addr, username,
                             password, schema, port, socketname, 0))
  {
    diag("Error: %s\n", mysql_error(mysql));
    mysql_close(mysql);
    return FAIL;
  }
  diag("%s", mysql_get_host_info(mysql));
  mysql_close(mysql);
  return OK;
}
コード例 #10
0
ファイル: AMySQLServer.cpp プロジェクト: achacha/AOS
void AMySQLServer::debugDump(std::ostream& os, int indent) const
{
  ADebugDumpable::indent(os, indent) << "(" << typeid(*this).name() << " @ " << std::hex << this << std::dec << ") {" << std::endl;
  ADebugDumpable::indent(os, indent+1) << "m_urlConnection=" << std::endl;
  m_urlConnection.debugDump(os,indent+2);
  
  ADebugDumpable::indent(os, indent+1) << "client: " << mysql_get_client_info() << std::endl;
  
  if (mbool_Initialized && mp_mydata)
  {
    ADebugDumpable::indent(os, indent+1) << mysql_stat(mp_mydata) << std::endl;
    ADebugDumpable::indent(os, indent+1) << "server: " << mysql_get_server_info(mp_mydata) << std::endl;
    ADebugDumpable::indent(os, indent+1) << "host  : " << mysql_get_host_info(mp_mydata) << std::endl;
    ADebugDumpable::indent(os, indent+1) << "mp_mydata=0x" << std::hex << (void*)mp_mydata << std::dec << std::endl;
  }
  else
    ADebugDumpable::indent(os, indent+1) << "mp_mydata=NULL" << std::endl;

  ADebugDumpable::indent(os, indent) << "}" << std::endl;
}
コード例 #11
0
int Database::hostInfo()
{
  if (!m_connectionThread ||
       m_connectionThread->isRunning() ||
      !m_connectionThread->wasSuccessful() )
  {
    m_luaInterface->PushNil();
    return 1;
  }

  m_sqlMutex.lock();
  const char* info = mysql_get_host_info(m_sql);
  if (info)
    m_luaInterface->Push( info );
  else
    m_luaInterface->PushNil();
  m_sqlMutex.unLock();

  return 1;
}
コード例 #12
0
ファイル: my_con.c プロジェクト: Gaoithe/openimscore_ims
/*
 * Create a new connection structure,
 * open the MySQL connection and set reference count to 1
 */
struct my_con* new_connection(struct db_id* id)
{
	struct my_con* ptr;

	if (!id) {
		LOG(L_ERR, "new_connection: Invalid parameter value\n");
		return 0;
	}

	ptr = (struct my_con*)pkg_malloc(sizeof(struct my_con));
	if (!ptr) {
		LOG(L_ERR, "new_connection: No memory left\n");
		return 0;
	}

	memset(ptr, 0, sizeof(struct my_con));
	ptr->ref = 1;
	
	ptr->con = (MYSQL*)pkg_malloc(sizeof(MYSQL));
	if (!ptr->con) {
		LOG(L_ERR, "new_connection: No enough memory\n");
		goto err;
	}

	mysql_init(ptr->con);

	if (id->port) {
		DBG("new_connection: Opening MySQL connection: %s://%s:%s@%s:%d/%s\n",
		    ZSW(id->scheme),
		    ZSW(id->username),
		    ZSW(id->password),
		    ZSW(id->host),
		    id->port,
		    ZSW(id->database)
		    );
	} else {
		DBG("new_connection: Opening MySQL connection: %s://%s:%s@%s/%s\n",
		    ZSW(id->scheme),
		    ZSW(id->username),
		    ZSW(id->password),
		    ZSW(id->host),
		    ZSW(id->database)
		    );
	}

	if (!mysql_real_connect(ptr->con, id->host, id->username, id->password, id->database, id->port, 0, 0)) {
		LOG(L_ERR, "new_connection: %s\n", mysql_error(ptr->con));
		mysql_close(ptr->con);
		goto err;
	}

	     /* Enable reconnection explicitly */
	ptr->con->reconnect = 1;

	DBG("new_connection: Connection type is %s\n", mysql_get_host_info(ptr->con));
	DBG("new_connection: Protocol version is %d\n", mysql_get_proto_info(ptr->con));
	DBG("new_connection: Server version is %s\n", mysql_get_server_info(ptr->con));


	ptr->timestamp = time(0);
	ptr->id = id;
	return ptr;

 err:
	if (ptr && ptr->con) pkg_free(ptr->con);
	if (ptr) pkg_free(ptr);
	return 0;
}
コード例 #13
0
ファイル: ext_mysql.cpp プロジェクト: Bluarggag/hhvm
Variant f_mysql_get_host_info(CVarRef link_identifier /* = uninit_null() */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (!conn) return false;
  return String(mysql_get_host_info(conn), CopyString);
}
コード例 #14
0
ファイル: ext_mysql.cpp プロジェクト: 191919/hhvm
Variant HHVM_FUNCTION(mysql_get_host_info,
                      const Variant& link_identifier /* = uninit_null() */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (!conn) return false;
  return String(mysql_get_host_info(conn), CopyString);
}
コード例 #15
0
ファイル: mysql_server.c プロジェクト: cuiwm/oceanbase
#include "sql_ob_init.h"

TEST_F(ObWithoutInit, 01_get_host_info)
{
    int ret;

    ret = mysql_library_init(0, NULL, NULL);
    EXPECT_EQ(ret,0);

    MYSQL my_;
    EXPECT_TRUE(NULL != mysql_init(&my_));

    EXPECT_TRUE(NULL != mysql_real_connect(&my_, HOST, "admin", "admin", "test", PORT, NULL, 0));

    const char*host_info = NULL;
    host_info = mysql_get_host_info(&my_);
    printf("host info : %s\n",host_info);
    EXPECT_TRUE( host_info != NULL);

    mysql_close(&my_);
    mysql_library_end();
}

TEST_F(ObWithoutInit, 02_get_server_version)
{
    int ret;

    ret = mysql_library_init(0, NULL, NULL);
    EXPECT_EQ(ret,0);

    MYSQL my_;
コード例 #16
0
ファイル: mysql_driver.c プロジェクト: mdesign83/php-src
/* {{{ pdo_mysql_get_attribute */
static int pdo_mysql_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *return_value)
{
	pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data;

	PDO_DBG_ENTER("pdo_mysql_get_attribute");
	PDO_DBG_INF_FMT("dbh=%p", dbh);
	PDO_DBG_INF_FMT("attr=%l", attr);
	switch (attr) {
		case PDO_ATTR_CLIENT_VERSION:
			ZVAL_STRING(return_value, (char *)mysql_get_client_info());
			break;

		case PDO_ATTR_SERVER_VERSION:
			ZVAL_STRING(return_value, (char *)mysql_get_server_info(H->server));
			break;

		case PDO_ATTR_CONNECTION_STATUS:
			ZVAL_STRING(return_value, (char *)mysql_get_host_info(H->server));
			break;
		case PDO_ATTR_SERVER_INFO: {
#if defined(PDO_USE_MYSQLND)
			zend_string *tmp;

			if (mysqlnd_stat(H->server, &tmp) == PASS) {
				ZVAL_STR(return_value, tmp);
#else
			char *tmp;
			if ((tmp = (char *)mysql_stat(H->server))) {
				ZVAL_STRING(return_value, tmp);
#endif
			} else {
				pdo_mysql_error(dbh);
				PDO_DBG_RETURN(-1);
			}
		}
			break;
		case PDO_ATTR_AUTOCOMMIT:
			ZVAL_LONG(return_value, dbh->auto_commit);
			break;

		case PDO_MYSQL_ATTR_USE_BUFFERED_QUERY:
			ZVAL_LONG(return_value, H->buffered);
			break;

		case PDO_ATTR_EMULATE_PREPARES:
		case PDO_MYSQL_ATTR_DIRECT_QUERY:
			ZVAL_LONG(return_value, H->emulate_prepare);
			break;

#ifndef PDO_USE_MYSQLND
		case PDO_MYSQL_ATTR_MAX_BUFFER_SIZE:
			ZVAL_LONG(return_value, H->max_buffer_size);
			break;
#endif

		default:
			PDO_DBG_RETURN(0);
	}

	PDO_DBG_RETURN(1);
}
/* }}} */

/* {{{ pdo_mysql_check_liveness */
static int pdo_mysql_check_liveness(pdo_dbh_t *dbh)
{
	pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data;
#if MYSQL_VERSION_ID <= 32230
	void (*handler) (int);
	unsigned int my_errno;
#endif

	PDO_DBG_ENTER("pdo_mysql_check_liveness");
	PDO_DBG_INF_FMT("dbh=%p", dbh);

#if MYSQL_VERSION_ID > 32230
	if (mysql_ping(H->server)) {
		PDO_DBG_RETURN(FAILURE);
	}
#else /* no mysql_ping() */
	handler = signal(SIGPIPE, SIG_IGN);
	mysql_stat(H->server);
	switch (mysql_errno(H->server)) {
		case CR_SERVER_GONE_ERROR:
		case CR_SERVER_LOST:
			signal(SIGPIPE, handler);
			PDO_DBG_RETURN(FAILURE);
		default:
			break;
	}
	signal(SIGPIPE, handler);
#endif /* end mysql_ping() */
	PDO_DBG_RETURN(SUCCESS);
}
コード例 #17
0
ファイル: socketServer9.c プロジェクト: thinus00/socketServer
int main(void)
{
    int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr_storage their_addr; // connector's address information
    socklen_t sin_size;
    struct sigaction sa;
    int yes=1;
    char s[INET6_ADDRSTRLEN];
    int rv;

    // Connect to the database

    MYSQL      *MySQLConRet;
    MYSQL      *MySQLConnection = NULL;

    const char *hostName = "localhost";
    const char *userId   = "espuser";
    const char *password = "******";
    const char *DB       = "tanklevels";

    MySQLConnection = mysql_init( NULL );

//    try
//    {
        MySQLConRet = mysql_real_connect( MySQLConnection,hostName,userId,password,DB,0,NULL,0 );

        if ( MySQLConRet == NULL )
        {
            printf("error connecting to SQL");
            printf(mysql_error(MySQLConnection));
            exit;
        }
        printf("MySQL Connection Info: %s \n", mysql_get_host_info(MySQLConnection));
        printf("MySQL Client Info: %s \n", mysql_get_client_info());
        printf("MySQL Server Info: %s \n", mysql_get_server_info(MySQLConnection));
//    }
//    catch ( FFError e )
//    {
//        printf("%s\n",e.Label.c_str());
//        return 1;
//    }


    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("server: socket");
            continue;
        }

        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
                sizeof(int)) == -1) {
            perror("setsockopt");
            exit(1);
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("server: bind");
            continue;
        }

        break;
    }

    freeaddrinfo(servinfo); // all done with this structure

    if (p == NULL)  {
        fprintf(stderr, "server: failed to bind\n");
        exit(1);
    }

    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }

    printf("server: waiting for connections...\n");

    while(1) {  // main accept() loop
        sin_size = sizeof their_addr;
        new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
        if (new_fd == -1) {
            perror("accept");
            continue;
        }

        inet_ntop(their_addr.ss_family,
            get_in_addr((struct sockaddr *)&their_addr),
            s, sizeof s);
        printf("server: got connection from %s\n", s);

        if (!fork()) { // this is the child process
            close(sockfd); // child doesn't need the listener
            //const char *filename1 = "data.log";
            //const char *filename2 = "data2.log";
            char buf[MAXDATASIZE];
            int numbytes = 0;
            int done = 0;
            while(done == 0) {
                if ((numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) {
                    perror("recv");
                    break;
                }

                if (numbytes == 0) {
                    printf("\nConnection closed by client\n");
                    break;
                }
                buf[numbytes] = '\0';

                printf("%s: received '%s'\n",s,buf);

                char buffer [500];
                if ((strncmp(buf, "GET", 3) == 0) || (strncmp(buf, "q", 1) == 0)){
                    sprintf(buffer, "SELECT * FROM tanklevel_rt\0");
                    printf(buffer);
                    printf("\n");

                    if (mysql_query(MySQLConnection, buffer))
                    {
                        printf("Error %u: %s\n", mysql_errno(MySQLConnection), mysql_error(MySQLConnection));
                    }
                    else
                    {
                        char sbuffer [5000];
			char sbuf [500];
                        printf("selected tanklevel_rt\n");
                        MYSQL_RES *res; /* holds the result set */
			res = mysql_store_result(MySQLConnection);

			// get the number of the columns
                        int num_fields = mysql_num_fields(res);

                        MYSQL_ROW row;
                        sbuffer[0] = '\0';
                        // Fetch all rows from the result
                        while ((row = mysql_fetch_row(res)))
                        {
                           sbuf[0] = '\0';
                           // Print all columns
                           int i = 0;
                           for(i = 0; i < num_fields; i++)
                           {
                               // Make sure row[i] is valid!
                               if(row[i] != NULL)
                               {
                                    sprintf(sbuf, "%s%s,", sbuf, row[i]);
                               }
                               else
                               {
                                    sprintf(sbuf, "%sNULL,", sbuf);
                               }
                               // Also, you can use ternary operator here instead of if-else
                               // cout << row[i] ? row[i] : "NULL" << endl;
                           }
                           sprintf(sbuffer, "%s%s\n\0", sbuffer, sbuf);
                           sprintf(sbuf,"%s\0", sbuf);
                           printf("%s\n", sbuf);
                        }
                        //if (send(new_fd, "<h1>Hello, world!</h1>", 22, 0) == -1) {
                        char sbuffer2 [5000];
			if (strncmp(buf, "GET", 3) == 0) {
                           printf("%s\n", sbuffer);
                           sprintf(sbuffer2, "<html><body>%s</body></html>\0", sbuffer);
                        }
                        else {
                           printf("%s\n", sbuffer);
                           sprintf(sbuffer2, "%s\0", sbuffer);
                        }
                        if (send(new_fd, sbuffer2, strlen(sbuffer2), 0) == -1) {
                           printf("Error sending");
                        }
                        else {
                           printf("Sent: %s\n",sbuffer2);
                        }
                        done = 1;
                    }
                }
                else {
                    struct tm *current;
                    time_t now;
                    time(&now);
                    current = localtime(&now);
                    char id;
                    id = s[strlen(s)-1];
                    sprintf(buffer, "%i-%i-%i %i:%i:%i,%s,%s-%c\n\0", current->tm_year+1900, current->tm_mon+1, current->tm_mday, current->tm_hour, current->tm_min, current->tm_sec, s, buf, id);

                    printf("%s", buffer);
                    //FILE *file1;
                    //file1 = fopen(filename1, "a");
                    //if (file1) {
                    //    fwrite(buffer, sizeof(char), strlen(buffer), file1);
                    //    fclose (file1);
                    //}

                    int buf_int = atoi(buf);
                    if ((buf_int < 20000) && (buf_int > 0)) {

struct timeval tv;
    gettimeofday(&tv, NULL);

uint64 start = tv.tv_usec;
start /= 1000;
start += (tv.tv_sec * 1000);
                        sprintf(buffer, "UPDATE tanklevel_rt SET value=%s, timestamp=\"%i-%i-%i %i:%i:%i\" WHERE tankid = %c\0", buf, current->tm_year+1900, current->tm_mon+1, current->tm_mday, current->tm_hour, current->tm_min, current->tm_sec, id);
                        printf("%c-%s",id,buffer);
                        printf("\n");

                        if (mysql_query(MySQLConnection, buffer))
                        {
                            printf("%c-Error %u: %s\n", id,mysql_errno(MySQLConnection), mysql_error(MySQLConnection));
                        }
                        else
                        {
gettimeofday(&tv, NULL);
uint64 end = tv.tv_usec;
end /= 1000;
end += (tv.tv_sec * 1000);

                                printf("%c-Updated DB (%dms)\n", id, end-start);

                        }
                    } else {
                        printf("Invalid value %d\n", buf_int);
                    }
                }
            }

            close(new_fd);
            exit(0);
        }
        close(new_fd);  // parent doesn't need this
    }

    return 0;
}
コード例 #18
0
ファイル: mysql.c プロジェクト: BackupTheBerlios/dryon-svn
/*	host_info()	*/
static VALUE host_info(VALUE obj)
{
    return rb_tainted_str_new2(mysql_get_host_info(GetHandler(obj)));
}
コード例 #19
0
ファイル: km_my_con.c プロジェクト: SipCoSystems/hush
/*! \brief
 * Create a new connection structure,
 * open the MySQL connection and set reference count to 1
 */
struct my_con* db_mysql_new_connection(const struct db_id* id)
{
	struct my_con* ptr;
	char *host, *grp, *egrp;

	if (!id) {
		LM_ERR("invalid parameter value\n");
		return 0;
	}

	ptr = (struct my_con*)pkg_malloc(sizeof(struct my_con));
	if (!ptr) {
		LM_ERR("no private memory left\n");
		return 0;
	}

	egrp = 0;
	memset(ptr, 0, sizeof(struct my_con));
	ptr->ref = 1;
	
	ptr->con = (MYSQL*)pkg_malloc(sizeof(MYSQL));
	if (!ptr->con) {
		LM_ERR("no private memory left\n");
		goto err;
	}

	mysql_init(ptr->con);

	if (id->host[0] == '[' && (egrp = strchr(id->host, ']')) != NULL) {
		grp = id->host + 1;
		*egrp = '\0';
		host = egrp;
		if (host != id->host + strlen(id->host)-1) {
			host += 1; // host found after closing bracket
		}
		else {
			// let mysql read host info from my.cnf
			// (defaults to "localhost")
			host = NULL;
		}
		// read [client] and [<grp>] sections in the order
		// given in my.cnf
		mysql_options(ptr->con, MYSQL_READ_DEFAULT_GROUP, grp);
	}
	else {
		host = id->host;
	}

	if (id->port) {
		LM_DBG("opening connection: mysql://xxxx:xxxx@%s:%d/%s\n", ZSW(host),
			id->port, ZSW(id->database));
	} else {
		LM_DBG("opening connection: mysql://xxxx:xxxx@%s/%s\n", ZSW(host),
			ZSW(id->database));
	}

	// set connect, read and write timeout, the value counts three times
	mysql_options(ptr->con, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&db_mysql_timeout_interval);
	mysql_options(ptr->con, MYSQL_OPT_READ_TIMEOUT, (const char *)&db_mysql_timeout_interval);
	mysql_options(ptr->con, MYSQL_OPT_WRITE_TIMEOUT, (const char *)&db_mysql_timeout_interval);

#if (MYSQL_VERSION_ID >= 40100)
	if (!mysql_real_connect(ptr->con, host, id->username, id->password,
				id->database, id->port, 0, CLIENT_MULTI_STATEMENTS)) {
#else
	if (!mysql_real_connect(ptr->con, host, id->username, id->password,
				id->database, id->port, 0, 0)) {
#endif
		LM_ERR("driver error: %s\n", mysql_error(ptr->con));
		/* increase error counter */
		counter_inc(mysql_cnts_h.driver_err);
		mysql_close(ptr->con);
		goto err;
	}
	/* force reconnection if enabled */
	if (db_mysql_auto_reconnect)
		ptr->con->reconnect = 1;
	else 
		ptr->con->reconnect = 0;

	LM_DBG("connection type is %s\n", mysql_get_host_info(ptr->con));
	LM_DBG("protocol version is %d\n", mysql_get_proto_info(ptr->con));
	LM_DBG("server version is %s\n", mysql_get_server_info(ptr->con));

	ptr->timestamp = time(0);
	ptr->id = (struct db_id*)id;
	if(egrp) *egrp = ']';
	return ptr;

 err:
	if (ptr && ptr->con) pkg_free(ptr->con);
	if (ptr) pkg_free(ptr);
	if(egrp) *egrp = ']';
	return 0;
}


/*! \brief
 * Close the connection and release memory
 */
void db_mysql_free_connection(struct pool_con* con)
{
	struct my_con * _c;
	
	if (!con) return;

	_c = (struct my_con*) con;

	if (_c->id) free_db_id(_c->id);
	if (_c->con) {
		mysql_close(_c->con);
		pkg_free(_c->con);
	}
	pkg_free(_c);
}
コード例 #20
0
ファイル: mg_mysql.c プロジェクト: adam-erickson/mglib
// const char *mysql_get_host_info(MYSQL *mysql)
static IDL_VPTR IDL_mg_mysql_get_host_info(int argc, IDL_VPTR *argv) {
    const char *info = mysql_get_host_info((MYSQL *)argv[0]->value.ptrint);
    return IDL_StrToSTRING(info);
}
コード例 #21
0
/* 主要功能:得到主机信息 */
const char * CppMySQL3DB::getHostInfo()
{
	return mysql_get_host_info(_db_ptr);
}
コード例 #22
0
ファイル: myTest.c プロジェクト: laiello/athletica
int
main( int argc, char * argv[] )
{

  char		szSQL[ 200 ], aszFlds[ 25 ][ 25 ],  szDB[ 50 ] ;
  const char * pszT;
  int			i, j, k, l, x ;
  MYSQL		* myData ;
  MYSQL_RES	* res ;
  MYSQL_FIELD	* fd ;
  MYSQL_ROW	row ;

  //....just curious....
  printf( "sizeof( MYSQL ) == %d\n", sizeof( MYSQL ) ) ;
  if ( argc == 2 )
    {
      strcpy( szDB, argv[ 1 ] ) ;
      strcpy( szSQL, DEFALT_SQL_STMT ) ;
      if (!strcmp(szDB,"--debug"))
      {
	strcpy( szDB, "mysql" ) ;
	printf("Some mysql struct information (size and offset):\n");
	printf("net:\t%3d %3d\n",sizeof(myData->net),offsetof(MYSQL,net));
	printf("host:\t%3d %3d\n",sizeof(myData->host),offsetof(MYSQL,host));
	printf("port:\t%3d %3d\n",sizeof(myData->port),offsetof(MYSQL,port));
	printf("protocol_version:\t%3d %3d\n",sizeof(myData->protocol_version),
	       offsetof(MYSQL,protocol_version));
	printf("thread_id:\t%3d %3d\n",sizeof(myData->thread_id),
	       offsetof(MYSQL,thread_id));
	printf("affected_rows:\t%3d %3d\n",sizeof(myData->affected_rows),
	       offsetof(MYSQL,affected_rows));
	printf("packet_length:\t%3d %3d\n",sizeof(myData->packet_length),
	       offsetof(MYSQL,packet_length));
	printf("status:\t%3d %3d\n",sizeof(myData->status),
	       offsetof(MYSQL,status));
	printf("fields:\t%3d %3d\n",sizeof(myData->fields),
	       offsetof(MYSQL,fields));
	printf("field_alloc:\t%3d %3d\n",sizeof(myData->field_alloc),
	       offsetof(MYSQL,field_alloc));
	printf("free_me:\t%3d %3d\n",sizeof(myData->free_me),
	       offsetof(MYSQL,free_me));
	printf("options:\t%3d %3d\n",sizeof(myData->options),
	       offsetof(MYSQL,options));
	puts("");
      }
    }		
  else if ( argc > 2 ) {
    strcpy( szDB, argv[ 1 ] ) ;
    strcpy( szSQL, argv[ 2 ] ) ;
  }
  else {
    strcpy( szDB, "mysql" ) ;
    strcpy( szSQL, DEFALT_SQL_STMT ) ;
  }
  //....
		  
  if ( (myData = mysql_init((MYSQL*) 0)) && 
       mysql_real_connect( myData, NULL, NULL, NULL, NULL, MYSQL_PORT,
			   NULL, 0 ) )
    {
      if ( mysql_select_db( myData, szDB ) < 0 ) {
	printf( "Can't select the %s database !\n", szDB ) ;
	mysql_close( myData ) ;
	return 2 ;
      }
    }
  else {
    printf( "Can't connect to the mysql server on port %d !\n",
	    MYSQL_PORT ) ;
    mysql_close( myData ) ;
    return 1 ;
  }
  //....
  if ( ! mysql_query( myData, szSQL ) ) {
    res = mysql_store_result( myData ) ;
    i = (int) mysql_num_rows( res ) ; l = 1 ;
    printf( "Query:  %s\nNumber of records found:  %ld\n", szSQL, i ) ;
    //....we can get the field-specific characteristics here....
    for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ )
      strcpy( aszFlds[ x ], fd->name ) ;
    //....
    while ( row = mysql_fetch_row( res ) ) {
      j = mysql_num_fields( res ) ;
      printf( "Record #%ld:-\n", l++ ) ;
      for ( k = 0 ; k < j ; k++ )
	printf( "  Fld #%d (%s): %s\n", k + 1, aszFlds[ k ],
		(((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ;
      puts( "==============================\n" ) ;
    }
    mysql_free_result( res ) ;
  }
  else printf( "Couldn't execute %s on the server !\n", szSQL ) ;
  //....
  puts( "====  Diagnostic info  ====" ) ;
  pszT = mysql_get_client_info() ;
  printf( "Client info: %s\n", pszT ) ;
  //....
  pszT = mysql_get_host_info( myData ) ;
  printf( "Host info: %s\n", pszT ) ;
  //....
  pszT = mysql_get_server_info( myData ) ;
  printf( "Server info: %s\n", pszT ) ;
  //....
  res = mysql_list_processes( myData ) ; l = 1 ;
  if (res)
    {
      for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ )
	strcpy( aszFlds[ x ], fd->name ) ;
      while ( row = mysql_fetch_row( res ) ) {
	j = mysql_num_fields( res ) ;
	printf( "Process #%ld:-\n", l++ ) ;
	for ( k = 0 ; k < j ; k++ )
	  printf( "  Fld #%d (%s): %s\n", k + 1, aszFlds[ k ],
		  (((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ;
	puts( "==============================\n" ) ;
      }
    }
  else
    {
      printf("Got error %s when retreiving processlist\n",mysql_error(myData));
    }
  //....
  res = mysql_list_tables( myData, "%" ) ; l = 1 ;
  for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ )
    strcpy( aszFlds[ x ], fd->name ) ;
  while ( row = mysql_fetch_row( res ) ) {
    j = mysql_num_fields( res ) ;
    printf( "Table #%ld:-\n", l++ ) ;
    for ( k = 0 ; k < j ; k++ )
      printf( "  Fld #%d (%s): %s\n", k + 1, aszFlds[ k ],
	      (((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ;
    puts( "==============================\n" ) ;
  }
  //....
  pszT = mysql_stat( myData ) ;
  puts( pszT ) ;
  //....
  mysql_close( myData ) ;
  return 0 ;

}
コード例 #23
0
ファイル: mysql.cpp プロジェクト: sequoiar/SilkJS
static JSVAL get_host_info(JSARGS args) {
	HandleScope scope;
	MYSQL *handle = (MYSQL *) args[0]->IntegerValue();
	return scope.Close(String::New(mysql_get_host_info(handle)));
}
コード例 #24
0
ファイル: connection.c プロジェクト: kepkin/wsql
static PyObject* wsql_connection_get_host_info(wsql_connection *self, void* closure)
{
    CHECK_CONNECTION(self, NULL);
    return PyString_FromString(mysql_get_host_info(&(self->connection)));
}
コード例 #25
0
ファイル: database.c プロジェクト: MalaGaM/nxscripts
/*++

ConnectionOpen

    Opens a server connection.

Arguments:
    context - Opaque context passed to <PoolCreate>.

    data    - Pointer to a pointer that receives the DB_CONTEXT structure.

Return Values:
    If the function succeeds, the return value is nonzero (true).

    If the function fails, the return value is zero (false).

--*/
static BOOL FCALL ConnectionOpen(VOID *context, VOID **data)
{
    DB_CONTEXT          *db;
    DB_CONFIG_SERVER    *server;
    DWORD               error;
    DWORD               i;
    INT                 attempt;
    INT                 attemptMax;
    LONG                serverIndex;
    LONG                serverNextIndex;
    MYSQL               *connection;
    my_bool             optReconnect;
    UINT                optTimeout;

    UNREFERENCED_PARAMETER(context);
    ASSERT(data != NULL);
    TRACE("context=%p data=%p", context, data);

    db = MemAllocate(sizeof(DB_CONTEXT));
    if (db == NULL) {
        LOG_ERROR("Unable to allocate memory for database context.");

        error = ERROR_NOT_ENOUGH_MEMORY;
        goto failed;
    }
    ZeroMemory(db, sizeof(DB_CONTEXT));

    //
    // Have the MySQL client library allocate the handle structure for us. This is
    // in case the MYSQL structure changes in a future version of the client library.
    //
    db->handle = mysql_init(NULL);
    if (db->handle == NULL) {
        LOG_ERROR("Unable to allocate memory for MySQL handle.");

        error = ERROR_NOT_ENOUGH_MEMORY;
        goto failed;
    }

    // If the maximum number of attempts were not specified, try all servers
    if (dbConfigGlobal.connAttempts > 0) {
        attemptMax = dbConfigGlobal.connAttempts;
    } else {
        attemptMax = dbConfigServerCount;
    }

    for (attempt = 0; attempt < attemptMax; attempt++) {
        // Use the most recent server for the connection attempt
        serverIndex = dbIndex;
        server      = &dbConfigServers[serverIndex];

        TRACE("Connecting to server #%d [%s] on attempt %lu/%lu.",
            serverIndex, server->name, attempt+1, attemptMax);

        // Set connection options
        optTimeout = (UINT)dbConfigGlobal.connTimeout;
        if (mysql_options(db->handle, MYSQL_OPT_CONNECT_TIMEOUT, &optTimeout) != 0) {
            TRACE("Failed to set connection timeout option.");
        }

        optReconnect = FALSE;
        if (mysql_options(db->handle, MYSQL_OPT_RECONNECT, &optReconnect) != 0) {
            TRACE("Failed to set reconnection option.");
        }

        if (server->compression) {
            if (mysql_options(db->handle, MYSQL_OPT_COMPRESS, 0) != 0) {
                TRACE("Failed to set compression option.");
            }
        }

        if (server->sslEnable) {
            //
            // This function always returns 0. If the SSL setup is incorrect,
            // the call to mysql_real_connect() will return an error.
            //
            mysql_ssl_set(db->handle, server->sslKeyFile, server->sslCertFile,
                server->sslCAFile, server->sslCAPath, server->sslCiphers);
        }

        // Attempt connection with server
        connection = mysql_real_connect(db->handle,
            server->host, server->user, server->password,
            server->database, server->port, NULL, CLIENT_INTERACTIVE);

        if (connection == NULL) {
            LOG_ERROR("Unable to connect to server [%s]: %s",
                server->name, mysql_error(db->handle));

        } else if (mysql_get_server_version(db->handle) < 50019) {
            LOG_ERROR("Unsupported version of MySQL Server [%s]: running v%s, must be v5.0.19 or newer.",
                server->name, mysql_get_server_info(db->handle));

        } else {
            // Pointer values should be the same as from mysql_init()
            ASSERT(connection == db->handle);

            // Allocate pre-compiled statement structures
            for (i = 0; i < ELEMENT_COUNT(db->stmt); i++) {
                db->stmt[i] = mysql_stmt_init(db->handle);
                if (db->stmt[i] == NULL) {
                    LOG_ERROR("Unable to allocate memory for statement structure.");

                    error = ERROR_NOT_ENOUGH_MEMORY;
                    goto failed;
                }
            }

            // Successfully connected, set the global server index
            InterlockedExchange(&dbIndex, serverIndex);

            // Update context's server index and time stamps
            db->index = serverIndex;
            GetSystemTimeAsFileTime(&db->created.fileTime);
            db->used.value = db->created.value;

            LOG_INFO("Connected to %s [%s], running MySQL Server v%s.",
                mysql_get_host_info(db->handle), server->name,
                mysql_get_server_info(db->handle));

            *data = db;
            return TRUE;
        }

        // Unsuccessful connection, continue to the next server
        serverNextIndex = serverIndex + 1;
        if (serverNextIndex >= (LONG)dbConfigServerCount) {
            serverNextIndex = 0;
        }

        //
        // Compare the current server index before swapping values in the
        // event that another thread has already changed the index.
        //
        InterlockedCompareExchange(&dbIndex, serverNextIndex, serverIndex);
    }

    // Unable to connect to any servers
    error = ERROR_CONNECTION_REFUSED;

failed:
    if (db != NULL) {
        ConnectionClose(NULL, db);
    }
    SetLastError(error);
    return FALSE;
}
コード例 #26
0
GString	GSqlDatabase::GetHostInformation(void)
{
	return (mysql_get_host_info(&(this->_mysql)));
}
コード例 #27
0
ファイル: mysql_driver.c プロジェクト: bishopb/php-src
/* {{{ pdo_mysql_get_attribute */
static int pdo_mysql_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *return_value)
{
	pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data;

	PDO_DBG_ENTER("pdo_mysql_get_attribute");
	PDO_DBG_INF_FMT("dbh=%p", dbh);
	PDO_DBG_INF_FMT("attr=%l", attr);
	switch (attr) {
		case PDO_ATTR_CLIENT_VERSION:
			ZVAL_STRING(return_value, (char *)mysql_get_client_info());
			break;

		case PDO_ATTR_SERVER_VERSION:
			ZVAL_STRING(return_value, (char *)mysql_get_server_info(H->server));
			break;

		case PDO_ATTR_CONNECTION_STATUS:
			ZVAL_STRING(return_value, (char *)mysql_get_host_info(H->server));
			break;
		case PDO_ATTR_SERVER_INFO: {
#if defined(PDO_USE_MYSQLND)
			zend_string *tmp;

			if (mysqlnd_stat(H->server, &tmp) == PASS) {
				ZVAL_STR(return_value, tmp);
#else
			char *tmp;
			if ((tmp = (char *)mysql_stat(H->server))) {
				ZVAL_STRING(return_value, tmp);
#endif
			} else {
				pdo_mysql_error(dbh);
				PDO_DBG_RETURN(-1);
			}
		}
			break;

		case PDO_ATTR_AUTOCOMMIT:
			ZVAL_LONG(return_value, dbh->auto_commit);
			break;

		case PDO_ATTR_DEFAULT_STR_PARAM:
			ZVAL_LONG(return_value, H->assume_national_character_set_strings ? PDO_PARAM_STR_NATL : PDO_PARAM_STR_CHAR);
			break;

		case PDO_MYSQL_ATTR_USE_BUFFERED_QUERY:
			ZVAL_LONG(return_value, H->buffered);
			break;

		case PDO_ATTR_EMULATE_PREPARES:
		case PDO_MYSQL_ATTR_DIRECT_QUERY:
			ZVAL_LONG(return_value, H->emulate_prepare);
			break;

#ifndef PDO_USE_MYSQLND
		case PDO_MYSQL_ATTR_MAX_BUFFER_SIZE:
			ZVAL_LONG(return_value, H->max_buffer_size);
			break;
#endif

		default:
			PDO_DBG_RETURN(0);
	}

	PDO_DBG_RETURN(1);
}
/* }}} */

/* {{{ pdo_mysql_check_liveness */
static int pdo_mysql_check_liveness(pdo_dbh_t *dbh)
{
	pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data;

	PDO_DBG_ENTER("pdo_mysql_check_liveness");
	PDO_DBG_INF_FMT("dbh=%p", dbh);

	if (mysql_ping(H->server)) {
		PDO_DBG_RETURN(FAILURE);
	}
	PDO_DBG_RETURN(SUCCESS);
}
コード例 #28
0
ファイル: main.c プロジェクト: kewang/mysql-example
int main(){
  MYSQL *MySQLConRet;
  MYSQL *MySQLConnection = NULL;

  char *hostname = "localhost";
  char *user = "******";
  char password[20];
  char *db = "hedistest";

  MySQLConnection = mysql_init(NULL);

  printf("enter password: "******"%s", password);

  MySQLConRet = mysql_real_connect(MySQLConnection, hostname, user, password, db, 0, NULL, 0);

  if(MySQLConRet == NULL){
    printf("fail\n");

    return 1;
  }

  printf("MySQL Connection Info: %s \n", mysql_get_host_info(MySQLConnection));
  printf("MySQL Client Info: %s \n", mysql_get_client_info());
  printf("MySQL Server Info: %s \n", mysql_get_server_info(MySQLConnection));

  int mysqlStatus = 0;
  MYSQL_RES *mysqlResult = NULL;

  if(mysqlResult){
    mysql_free_result(mysqlResult);
    mysqlResult = NULL;
  }

  MYSQL_ROW mysqlRow;
  MYSQL_FIELD *mysqlFields;
  my_ulonglong numRows;
  unsigned int numFields;

  char *sqlSelStatement = "select * from user";

  mysqlStatus = mysql_query(MySQLConnection, sqlSelStatement);

  if(mysqlStatus){
    printf((char *)mysql_error(MySQLConnection));

    return 1;
  }

  mysqlResult = mysql_store_result(MySQLConnection);

  if(mysqlResult){
    numRows = mysql_num_rows(mysqlResult);

    numFields = mysql_field_count(MySQLConnection);

    numFields = mysql_num_fields(mysqlResult);

    printf("Number of rows=%u  Number of fields=%u \n", numRows, numFields);
  }else{
    printf("Result set is empty\n");
  }

  mysqlFields = mysql_fetch_fields(mysqlResult);

  for(int i = 0; i < numFields; i++){
    printf("%s\t", mysqlFields[i].name);
  }

  printf("\n");

  while(mysqlRow = mysql_fetch_row(mysqlResult)){
    for(int i = 0; i < numFields; i++){
      printf("%s\t", mysqlRow[i] ? mysqlRow[i] : "NULL");
    }

    printf("\n");
  }

  if(mysqlResult){
    mysql_free_result(mysqlResult);

    mysqlResult = NULL;
  }

  mysql_close(MySQLConnection);

  return 0;
}
コード例 #29
0
ファイル: mysql.cpp プロジェクト: Leveltlab/2Pimage
void mexFunction(int nlhs, mxArray *plhs[],
      int nrhs, const mxArray *prhs[])
{
	int cid=-1;  // Handle of the current connection (invalid until we identify)
	int jarg=0;  // Number of first string arg: becomes 1 if id is specified

	/*********************************************************************/
	// Parse the first argument to see if it is a specific database handle
	if ( nrhs>0 && mxIsNumeric(prhs[0]) )
		{ if ( mxGetM(prhs[0])!=1 || mxGetN(prhs[0])!=1 )
			{ showusage();
			  mexPrintf("First argument is array %d x %d, but it should be a scalar\n",
			      mxGetM(prhs[0]),mxGetN(prhs[0]) );
			  mexErrMsgTxt("Invalid connection handle"); }
		  double xid = *mxGetPr(prhs[0]);
		  cid = int(xid);
		  if ( double(cid)!=xid || cid<0 || cid>=MAXCONN )
			{ showusage();
			  mexPrintf("dbHandle = %g -- Must be integer between 0 and %d\n",
			      xid,MAXCONN-1);
			  mexErrMsgTxt("Invalid connection handle"); }
		  jarg = 1;
		  if (debug) mexPrintf("| Explicit  cid = %d\n",cid); }

	/*********************************************************************/
	//  Check that the remaining arguments are all character strings
	{ for ( int j=jarg ; j<nrhs ; j++ )
		{ if (!mxIsChar(prhs[j]))
			{ showusage();
			  mexErrMsgTxt("All args must be strings, except dbHandle"); }}}

	/*********************************************************************/
	//  Identify what action he wants to do

	enum querytype { OPEN, CLOSE, CLOSEALL, USENAMED, USE,
	                     STATUS, STATSALL, QUOTE, CMD } q;
	char *query = NULL;

	if (nrhs<=jarg)   q = STATSALL;
	else
		{ query = mxArrayToString(prhs[jarg]);
		  if (streq(query,"open"))          q = OPEN;
		  else if (streq(query,"close"))    q = CLOSE;
		  else if (streq(query,"closeall")) q = CLOSEALL;
		  else if (streq(query,"use"))      q = USENAMED;
		  else if (streq(query,"use",3))    q = USE;
		  else if (streq(query,"status"))   q = STATUS;
		  else if (streq(query,"quote"))    q = QUOTE;
		  else q = CMD; }

	if (debug)
		{ switch(q)
			{ case OPEN:     mexPrintf("| q = OPEN\n");     break;
			  case CLOSE:    mexPrintf("| q = CLOSE\n");    break;
			  case CLOSEALL: mexPrintf("| q = CLOSEALL\n"); break;
			  case USENAMED: mexPrintf("| q = USENAMED\n"); break;
			  case USE:      mexPrintf("| q = USE\n");      break;
			  case STATUS:   mexPrintf("| q = STATUS\n");   break;
			  case STATSALL: mexPrintf("| q = STATSALL\n"); break;
			  case QUOTE:    mexPrintf("| q = QUOTE\n");    break;
			  case CMD:      mexPrintf("| q = CMD\n");      break;
			                 mexPrintf("| q = ??\n");              }}

	/*********************************************************************/
	//  If he did not specify the handle, choose the appropriate one
	//  If there are no previous connections, then we will still have
	//     cid=-1, and this will be handled in the appropriate place.
	if (jarg==0)
		{
		if (q==OPEN)
			{ for ( cid=0 ; cid<MAXCONN & c[cid].isopen ; cid++ );
			  if (cid>=MAXCONN) mexErrMsgTxt("Can\'t find free handle"); }
		else if (ncid>0)
			cid=prevcid[ncid-1];
		}

	if (debug) mexPrintf("| cid = %d\n",cid);

	//  Shorthand notation so we don't need to write c[cid]...
	//  These values must not be used if  cid<0
	mp dummyconn;     mp &conn = (cid>=0) ? c[cid].conn : dummyconn;
	bool dummyisopen; bool &isopen = (cid>=0) ? c[cid].isopen : dummyisopen;

	if (q==OPEN)
		{
		if (cid<0)
			{ mexPrintf("cid = %d !\n",cid);
			  mexErrMsgTxt("Internal code error\n"); }
		//  Close connection if it is open
		if (isopen)
			{ mexWarnMsgIdAndTxt("mysql:ConnectionAlreadyOpen",
			    "Connection %d has been closed and overwritten",cid);
			  mysql_close(conn);
			  conn=NULL;  isopen=false;  stackdelete(cid); }

		//  Extract information from input arguments
		char *host=NULL;   if (nrhs>=jarg+2)  host = mxArrayToString(prhs[jarg+1]);
		char *user=NULL;   if (nrhs>=jarg+3)  user = mxArrayToString(prhs[jarg+2]);
		char *pass=NULL;   if (nrhs>=jarg+4)  pass = mxArrayToString(prhs[jarg+3]);
		int port = hostport(host);  // returns zero if there is no port

		if (nlhs<1)
			{ mexPrintf("Connecting to  host=%s", (host) ? host : "localhost" );
			  if (port) mexPrintf("  port=%d",port);
			  if (user) mexPrintf("  user=%s",user);
			  if (pass) mexPrintf("  password=%s",pass);
			  mexPrintf("\n"); }

		//  Establish and test the connection
		//  If this fails, then conn is still set, but isopen stays false
		if (!(conn=mysql_init(conn)))
			mexErrMsgTxt("Couldn\'t initialize MySQL connection object");
		if (!mysql_real_connect( conn, host, user, pass, NULL,port,NULL,0 ))
			mexErrMsgTxt(mysql_error(conn));
		const char *c=mysql_stat(conn);
		if (c)  { if (nlhs<1) mexPrintf("%s\n",c); }
		else    mexErrMsgTxt(mysql_error(conn));

		isopen=true;
		ncid++;
		if (ncid>MAXCONN)
			{ mexPrintf("ncid = %d ?\n",ncid);
			  mexErrMsgTxt("Internal logic error\n"); }
		prevcid[ncid-1] = cid;

		if (debug) stackprint();

		//  Now we are OK -- return the connection handle opened.
		setScalarReturn(nlhs,plhs,cid);
		}

	else if (q==CLOSE)
		{
		if ( cid>=0 && isopen )
			{ if (debug) mexPrintf("| Closing %d\n",cid);
			  mysql_close(conn);
			  conn = NULL; isopen=false;  stackdelete(cid); }
		if (debug) stackprint();
		}

	else if (q==CLOSEALL)
		{ while (ncid>0)
			{ if (debug) stackprint();
			  cid = prevcid[ncid-1];
			  if (debug) mexPrintf("| Closing %d\n",cid);
			  if (!(c[cid].isopen))
				{ mexPrintf("Connection %d is not marked open!\n",cid);
				  mexErrMsgTxt("Internal logic error"); }
			  mysql_close(c[cid].conn);
			  c[cid].conn=NULL;  c[cid].isopen=false;  ncid--; }}

	else if ( q==USE || q==USENAMED )
		{
		if ( cid<0 || !isopen ) mexErrMsgTxt("Not connected");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexPrintf(mysql_error(conn));
			  mexPrintf("\nClosing connection %d\n",cid);
			  mexErrMsgTxt("Use command failed"); }
		char *db=NULL;
		if (q==USENAMED)
			{ if (nrhs>=2) db=mxArrayToString(prhs[jarg+1]);
			  else         mexErrMsgTxt("Must specify a database to use"); }
		else
			{ db = query + 3;
			  while ( *db==' ' || *db=='\t' ) db++; }
		if (mysql_select_db(conn,db))  mexErrMsgTxt(mysql_error(conn));
		if (nlhs<1) mexPrintf("Current database is \"%s\"\n",db); 
		else        setScalarReturn(nlhs,plhs,1.);
		}

	else if (q==STATUS)
		{
		if (nlhs<1)  //  He wants a report
			{ // print connection handle only if multiple connections
			  char idstr[10];  idstr[0]=0;
			  if ( cid>=0 && ncid>1 )  sprintf(idstr,"(%d) ",cid);
			  if ( cid<0 || !isopen )
			   { mexPrintf("%sNot connected\n",idstr,cid);  return; }
			  if (mysql_ping(conn))
				{ mexErrMsgTxt(mysql_error(conn)); }
			  mexPrintf("%s%-30s   Server version %s\n",
			    idstr, mysql_get_host_info(conn), mysql_get_server_info(conn) ); }
		else         //  He wants a return value for this connection
			{ double *pr=setScalarReturn(nlhs,plhs,0.);
			  if ( cid<0 || !isopen ) { *pr=1.; return; }
			  if (mysql_ping(conn))   { *pr=2.; return; }}
		}

	else if (q==STATSALL)
		{
		if (debug) stackprint();
		if (ncid==0)      mexPrintf("No connections open\n");
		else if (ncid==1) mexPrintf("1 connection open\n");
		else              mexPrintf("%d connections open\n",ncid);
		for ( int j=0 ; j<ncid ; j++ )
			{ cid = prevcid[j];
			  if (mysql_ping(c[cid].conn))
				  mexPrintf("%2d:  %s\n",cid,mysql_error(conn));
			  else
				  mexPrintf("%2d:  %-30s   Server version %s\n",
				        cid, mysql_get_host_info(c[cid].conn),
				        mysql_get_server_info(c[cid].conn) ); }
		}

	// Quote the second string argument and return it (Chris Rodgers)
	else if (q==QUOTE)
		{
		if ((nrhs-jarg)!=2)
			mexErrMsgTxt("mysql('quote','string_to_quote') takes two string arguments!");

		//  Check that we have a valid connection
		if ( cid<0 || !isopen ) mexErrMsgTxt("No connection open");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexErrMsgTxt(mysql_error(conn)); }

		const mxArray *a = prhs[jarg+1];
		int llen = mxGetM(a)*mxGetN(a)*sizeof(mxChar);
		char *from = (char *) mxCalloc(llen+1,sizeof(char));
		if (mxGetString(a,from,llen)) mexErrMsgTxt("Can\'t copy string");
		int l = strlen(from);

		/* Allocate memory for input and output strings. */
		char *to = (char*) mxCalloc( llen*2+3, sizeof(char));

		/* Call the C subroutine. */
		to[0] = '\'';
		int n = mysql_real_escape_string( conn, to+1, from, l );
		to[n+1] = '\'';

		/* Set C-style string output_buf to MATLAB mexFunction output*/
		plhs[0] = mxCreateString(to);

		mxFree(from);  mxFree(to);  // just in case Matlab forgets
		}

	else if (q==CMD)
		{
		//  Check that we have a valid connection
		if ( cid<0 || !isopen ) mexErrMsgTxt("No connection open");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexPrintf(mysql_error(conn));
			  mexPrintf("Closing connection %d\n",cid);
			  mexErrMsgTxt("Query failed"); }

		//  Execute the query (data stays on server)
		if (mysql_query(conn,query))  mexErrMsgTxt(mysql_error(conn));

		//  Download the data from server into our memory
		//     We need to be careful to deallocate res before returning.
		//  Matlab's allocation routines return instantly if there is not
		//  enough free space, without giving us time to dealloc res.
		//  This is a potential memory leak but I don't see how to fix it.
		MYSQL_RES *res = mysql_store_result(conn);

		//  As recommended in Paul DuBois' MySQL book (New Riders, 1999):
		//  A NULL result set after the query can indicate either
		//    (1) the query was an INSERT, DELETE, REPLACE, or UPDATE, that
		//        affect rows in the table but do not return a result set; or
		//    (2) an error, if the query was a SELECT, SHOW, or EXPLAIN
		//        that should return a result set but didn't.
		//  Distinguish between the two by checking mysql_field_count()
		//  We return in either case, either correctly or with an error
		if (!res)
			{
			if (!mysql_field_count(conn))
				{ unsigned long nrows=mysql_affected_rows(conn);
				  if (nlhs<1)
					{ mexPrintf("%u rows affected\n",nrows);
					  return; }
				  else
					{ setScalarReturn(nlhs,plhs,nrows);
					  return; }}
			else
				  mexErrMsgTxt(mysql_error(conn));
			}

		unsigned long nrow=mysql_num_rows(res), nfield=mysql_num_fields(res);

		//  If he didn't ask for any output (nlhs=0),
		//       then display the output and return
		if ( nlhs<1 )
			{ fancyprint(res);
			  mysql_free_result(res);
			  return; }

		//  If we are here, he wants output
		//  He must give exactly the right number of output arguments
// 		if ( nlhs != nfield )
// 			{ mysql_free_result(res);
// 			  mexPrintf("You specified %d output arguments, "
// 			         "and got %d columns of data\n",nlhs,nfield);
// 			  mexErrMsgTxt("Must give one output argument for each column"); }
        
        if(nlhs > 1) mexErrMsgIdAndTxt( "MYSQL query: ",
                        "Too many output arguments.");

		//  Fix the column types to fix MySQL C API sloppiness
		MYSQL_FIELD *f = mysql_fetch_fields(res);
		fix_types( f, res );

		//  Create the Matlab arrays for output
// 		double **pr = (double **) mxMalloc( nfield * sizeof(double *) );
// 		{ for ( int j=0 ; j<nfield ; j++ )
// 			{ if ( can_convert(f[j].type) )
// 				{ if (!( plhs[j] = mxCreateDoubleMatrix( nrow, 1, mxREAL ) ))
// 					{ mysql_free_result(res);
// 					  mexErrMsgTxt("Unable to create numeric matrix for output"); }
// 				  pr[j] = mxGetPr(plhs[j]); }
// 			  else
// 				{ if (!( plhs[j] = mxCreateCellMatrix( nrow, 1 ) ))
// 					{ mysql_free_result(res);
// 					  mexErrMsgTxt("Unable to create cell matrix for output"); }
// 				  pr[j] = NULL; }}}
        
         if (!( plhs[0] = mxCreateCellMatrix( nrow, nfield ) )){
					 mysql_free_result(res);
                     mexErrMsgTxt("Unable to create cell matrix for output");                 
         }

		//  Load the data into the cells
		mysql_data_seek(res,0);
		for ( int i=0 ; i<nrow ; i++ ){ 
			  MYSQL_ROW row = mysql_fetch_row(res);
			  if (!row) { 
				mexPrintf("Scanning row %d for data extraction\n",i+1);
				  mexErrMsgTxt("Internal error:  Failed to get a row"); }
// 			  for ( int j=0 ; j<nfield ; j++ ){ 
//                   if (can_convert(f[j].type)) { 
// 					pr[j][i] = field2num(row[j],f[j].type); 
//                   }
// 				  else {
// 					 mxArray *c = mxCreateString(row[j]);
// 					  mxSetCell(plhs[j],i,c); 
//                   }
//               }
             for ( int j=0 ; j <nfield ; j++ ){
                 mxArray *c = mxCreateString(row[j]);
 					  mxSetCell(plhs[0],j*nrow + i,c); 
             }
        }
		mysql_free_result(res);
		}
	else
		{ mexPrintf("Unknown query type q = %d\n",q);
		  mexErrMsgTxt("Internal code error"); }
}
コード例 #30
0
string CDatabase_Connection::get_host_info()
{
	return mysql_get_host_info(&my);
}