/* test should run with valgrind */
static int test_conc118(MYSQL *mysql)
{
  int rc;

  mysql->reconnect= 1;
  mysql->options.unused_1= 1;

  rc= mysql_kill(mysql, mysql_thread_id(mysql));
  sleep(2);

  rc= mysql_query(mysql, "SET @a:=1");
  check_mysql_rc(rc, mysql);

  FAIL_IF(mysql->options.unused_1 != 1, "options got lost");

  rc= mysql_kill(mysql, mysql_thread_id(mysql));
  sleep(2);

  mysql->host= "foo";

  rc= mysql_query(mysql, "SET @a:=1");
  FAIL_IF(!rc, "error expected");

  mysql->host= hostname;
  rc= mysql_query(mysql, "SET @a:=1");
  check_mysql_rc(rc, mysql);

  return OK;
}
/* test should run with valgrind */
static int test_conc118(MYSQL *mysql)
{
  int rc;
  my_bool reconnect= 1;

  mysql_options(mysql, MYSQL_OPT_RECONNECT, &reconnect);

  mysql->options.unused_1= 1;

  rc= mysql_kill(mysql, mysql_thread_id(mysql));
  sleep(2);

  mysql_ping(mysql);

  rc= mysql_query(mysql, "SET @a:=1");
  check_mysql_rc(rc, mysql);

  FAIL_IF(mysql->options.unused_1 != 1, "options got lost");

  rc= mysql_kill(mysql, mysql_thread_id(mysql));
  sleep(2);

  mysql_ping(mysql);
  rc= mysql_query(mysql, "SET @a:=1");
  check_mysql_rc(rc, mysql);

  return OK;
}
bool MySQLConnection::_HandleMySQLErrno(uint32 errNo)
{
    switch (errNo)
    {
        case CR_SERVER_GONE_ERROR:
        case CR_SERVER_LOST:
        case CR_INVALID_CONN_HANDLE:
        case CR_SERVER_LOST_EXTENDED:
        {
            m_reconnecting = true;
            uint64 oldThreadId = mysql_thread_id(GetHandle());
            mysql_close(GetHandle());
            if (this->Open())                           // Don't remove 'this' pointer unless you want to skip loading all prepared statements....
            {
                sLog->outInfo(LOG_FILTER_SQL, "Connection to the MySQL server is active.");
                if (oldThreadId != mysql_thread_id(GetHandle()))
                    sLog->outInfo(LOG_FILTER_SQL, "Successfully reconnected to %s @%s:%s (%s).",
                        m_connectionInfo.database.c_str(), m_connectionInfo.host.c_str(), m_connectionInfo.port_or_socket.c_str(),
                            (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous");

                m_reconnecting = false;
                return true;
            }

            uint32 lErrno = mysql_errno(GetHandle());   // It's possible this attempted reconnect throws 2006 at us. To prevent crazy recursive calls, sleep here.
            ACE_OS::sleep(3);                           // Sleep 3 seconds
            return _HandleMySQLErrno(lErrno);           // Call self (recursive)
        }

        case ER_LOCK_DEADLOCK:
            return false;    // Implemented in TransactionTask::Execute and DatabaseWorkerPool<T>::DirectCommitTransaction
        // Query related errors - skip query
        case ER_WRONG_VALUE_COUNT:
        case ER_DUP_ENTRY:
            return false;

        // Outdated table or database structure - terminate core
        case ER_BAD_FIELD_ERROR:
        case ER_NO_SUCH_TABLE:
            sLog->outError(LOG_FILTER_SQL, "Your database structure is not up to date. Please make sure you've executed all queries in the sql/updates folders.");
            ACE_OS::sleep(10);
            std::abort();
            return false;
        case ER_PARSE_ERROR:
            sLog->outError(LOG_FILTER_SQL, "Error while parsing SQL. Core fix required.");
            ACE_OS::sleep(10);
            std::abort();
            return false;
        default:
            sLog->outError(LOG_FILTER_SQL, "Unhandled MySQL errno %u. Unexpected behaviour possible.", errNo);
            return false;
    }
}
Beispiel #4
0
bool MySQLConnection::HandleMySQLError(uint32 errNo)
{
    switch (errNo)
    {
        case CR_SERVER_GONE_ERROR:
        case CR_SERVER_LOST:
        case CR_INVALID_CONN_HANDLE:
        case CR_SERVER_LOST_EXTENDED:
        {
            uint64 oldThreadId = mysql_thread_id(mMysql);
            mysql_close(mMysql);

            if (OpenConnection(true))
            {
                FreePreparedStatements(); // We need to prepare everything again!
                sLog.outString("Reconnection attempt to database %s (on %s)", m_database.c_str(), m_host.c_str());
                if (oldThreadId != mysql_thread_id(mMysql))
                    sLog.outString("Successfully reconnected to %s @%s:%u.",
                        m_database.c_str(), m_host.c_str(), m_port);

                return true;
            }

            return false; // Failed to reconnect
        }

        case ER_LOCK_DEADLOCK:
            return false;
        // Query related errors - skip query
        case ER_WRONG_VALUE_COUNT:
        case ER_DUP_ENTRY:
            return false;

        // Outdated table or database structure - terminate core
        case ER_BAD_FIELD_ERROR:
        case ER_NO_SUCH_TABLE:
            sLog.outErrorDb("Your database structure is not up to date. Please make sure you have executed all the queries in the sql/updates folders.");
            ASSERT(false);
            return false;
        case ER_PARSE_ERROR:
            sLog.outErrorDb("Error while parsing SQL. Core fix required.");
            ASSERT(false);
            return false;
        default:
            sLog.outErrorDb("Unhandled MySQL errno %u. Unexpected behaviour possible.", errNo);
            return false;
    }
}
Beispiel #5
0
static void mysql_client_thread(void *arg)
{
    unsigned long i, succeeded, failed;
    DBPool *pool = arg;

    succeeded = failed = 0;

    info(0,"Client thread started with %ld queries to perform on pool", queries);

    /* perform random queries on the pool */
    for (i = 1; i <= queries; i++) {
        DBPoolConn *pconn;
        int state;
        MYSQL_RES *result;

        /* provide us with a connection from the pool */
        pconn = dbpool_conn_consume(pool);
        debug("",0,"Query %ld/%ld: mysql thread id %ld obj at %p",
              i, queries, mysql_thread_id(pconn->conn), (void*) pconn->conn);

        state = mysql_query(pconn->conn, octstr_get_cstr(sql));
        if (state != 0) {
            error(0, "MYSQL: %s", mysql_error(pconn->conn));
            failed++;
        } else {
            succeeded++;
        }
        result = mysql_store_result(pconn->conn);
        mysql_free_result(result);

        /* return the connection to the pool */
        dbpool_conn_produce(pconn);
    }
    info(0, "This thread: %ld succeeded, %ld failed.", succeeded, failed);
}
Beispiel #6
0
bool MySQLConnection::_HandleMySQLErrno(uint32 errNo)
{
    switch (errNo)
    {
        case 2006:  // "MySQL server has gone away"
        case 2013:  // "Lost connection to MySQL server during query"
        case 2048:  // "Invalid connection handle"
        case 2055:  // "Lost connection to MySQL server at '%s', system error: %d"
        {
            m_reconnecting = true;
            uint64 oldThreadId = mysql_thread_id(GetHandle());
            mysql_close(GetHandle());
            if (this->Open())                           // Don't remove 'this' pointer unless you want to skip loading all prepared statements....
            {
                sLog->outSQLDriver("Connection to the MySQL server is active.");
                if (oldThreadId != mysql_thread_id(GetHandle()))
                    sLog->outSQLDriver("Successfully reconnected to %s @%s:%s (%s).",
                        m_connectionInfo.database.c_str(), m_connectionInfo.host.c_str(), m_connectionInfo.port_or_socket.c_str(),
                            (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous");

                m_reconnecting = false;
                return true;
            }

            uint32 lErrno = mysql_errno(GetHandle());   // It's possible this attempted reconnect throws 2006 at us. To prevent crazy recursive calls, sleep here.
            ACE_OS::sleep(3);                           // Sleep 3 seconds
            return _HandleMySQLErrno(lErrno);           // Call self (recursive)
        }

        case 1213:      // "Deadlock found when trying to get lock; try restarting transaction"
            return false;    // Implemented in TransactionTask::Execute and DatabaseWorkerPool<T>::DirectCommitTransaction
        // Query related errors - skip query
        case 1058:      // "Column count doesn't match value count"
        case 1062:      // "Duplicate entry '%s' for key '%d'"
            return false;

        // Outdated table or database structure - terminate core
        case 1054:      // "Unknown column '%s' in '%s'"
        case 1146:      // "Table '%s' doesn't exist"
            WPFatal(!errNo, "Your database structure is not up to date. Please make sure you've executed all queries in the sql/updates folders.");
            return false;

        default:
            sLog->outSQLDriver("Unhandled MySQL errno %u. Unexpected behaviour possible.", errNo);
            return false;
    }
}
Beispiel #7
0
static VALUE rb_mysql_client_thread_id(VALUE self) {
  unsigned long retVal;
  GET_CLIENT(self);

  REQUIRE_OPEN_DB(wrapper);
  retVal = mysql_thread_id(wrapper->client);
  return ULL2NUM(retVal);
}
static int test_reconnect(MYSQL *mysql)
{
  my_bool my_true= TRUE;
  MYSQL *mysql1;
  int rc;
  my_bool reconnect;

  mysql1= mysql_init(NULL);
  FAIL_IF(!mysql1, "not enough memory");

  mysql_get_option(mysql1, MYSQL_OPT_RECONNECT, &reconnect);
  FAIL_UNLESS(reconnect == 0, "reconnect != 0");

  rc= mysql_options(mysql1, MYSQL_OPT_RECONNECT, &my_true);
  check_mysql_rc(rc, mysql1);

  mysql_get_option(mysql1, MYSQL_OPT_RECONNECT, &reconnect);
  FAIL_UNLESS(reconnect == 1, "reconnect != 1");

  if (!(mysql_real_connect(mysql1, hostname, username,
                           password, schema, port,
                           socketname, 0)))
  {
    diag("connection failed");
    mysql_close(mysql);
    return FAIL;
  }

  mysql_get_option(mysql1, MYSQL_OPT_RECONNECT, &reconnect);
  FAIL_UNLESS(reconnect == 1, "reconnect != 1");

  diag("Thread_id before kill: %lu", mysql_thread_id(mysql1));
  mysql_kill(mysql, mysql_thread_id(mysql1));
  sleep(4);

  mysql_ping(mysql1);

  rc= mysql_query(mysql1, "SELECT 1 FROM DUAL LIMIT 0");
  check_mysql_rc(rc, mysql1);
  diag("Thread_id after kill: %lu", mysql_thread_id(mysql1));

  mysql_get_option(mysql1, MYSQL_OPT_RECONNECT, &reconnect);
  FAIL_UNLESS(reconnect == 1, "reconnect != 1");
  mysql_close(mysql1);
  return OK;
}
Beispiel #9
0
static PyObject* wsql_connection_get_thread_id(wsql_connection *self, void* closure)
{
    unsigned long pid;
    CHECK_CONNECTION(self, NULL);
    Py_BEGIN_ALLOW_THREADS
    pid = mysql_thread_id(&(self->connection));
    Py_END_ALLOW_THREADS
    return PyLong_FromLong((long)pid);
}
Beispiel #10
0
bool MySQLConnection::_HandleMySQLErrno(uint32 errNo)
{
    switch (errNo)
    {
    case 2006:  // "MySQL server has gone away"
    case 2013:  // "Lost connection to MySQL server during query"
    case 2048:  // "Invalid connection handle"
    case 2055:  // "Lost connection to MySQL server at '%s', system error: %d"
    {
        m_reconnecting = true;
        uint64 oldThreadId = mysql_thread_id(GetHandle());
        mysql_close(GetHandle());
        if (this->Open())                           // Don't remove 'this' pointer unless you want to skip loading all prepared statements....
        {
            sLog->outSQLDriver("Die Verbindung zum MySQL-Server aktiv ist.");
            if (oldThreadId != mysql_thread_id(GetHandle()))
                sLog->outSQLDriver("Online %s @%s:%s (%s).",
                                   m_connectionInfo.database.c_str(), m_connectionInfo.host.c_str(), m_connectionInfo.port_or_socket.c_str(),
                                   (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous");

            m_reconnecting = false;
            return true;
        }

        uint32 lErrno = mysql_errno(GetHandle());   // It's possible this attempted reconnect throws 2006 at us. To prevent crazy recursive calls, sleep here.
        ACE_OS::sleep(3);                           // Sleep 3 seconds
        return _HandleMySQLErrno(lErrno);           // Call self (recursive)
    }

    case 1213:      // "Deadlock found when trying to get lock; try restarting transaction"
        return false;    // Implemented in TransactionTask::Execute and DatabaseWorkerPool<T>::DirectCommitTransaction
    // Query related errors - skip query
    case 1058:      // "Column count doesn't match value count"
    case 1062:      // "Duplicate entry '%s' for key '%d'"
    case 1054:      // "Unknown column '%s' in 'order clause'"
        return false;

    default:
        sLog->outSQLDriver("Unbehandelte MySQL Err %u. Unerwarteter Fehler.", errNo);
        return false;
    }
}
bool MySQLConnection::_HandleMySQLErrno(uint32 errNo)
{
    sLog->outDebug("%s", __FUNCTION__);

    switch (errNo)
    {
        case 2006:  // "MySQL server has gone away"
        case 2013:  // "Lost connection to MySQL server during query"
        case 2048:  // "Invalid connection handle"
        case 2055:  // "Lost connection to MySQL server at '%s', system error: %d"
        {
            m_reconnecting = true;
            uint64 oldThreadId = mysql_thread_id(GetHandle());
            mysql_close(GetHandle());
            if (this->Open())                           // Don't remove 'this' pointer unless you want to skip loading all prepared statements....
            {
                sLog->outSQLDriver("Connection to the MySQL server is active.");
                if (oldThreadId != mysql_thread_id(GetHandle()))
                    sLog->outSQLDriver("Succesfuly reconnected to %s @%s:%s (%s).", 
                        m_connectionInfo.database.c_str(), m_connectionInfo.host.c_str(), m_connectionInfo.port_or_socket.c_str(),
                            (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous");

                m_reconnecting = false;
                return true;
            }

            uint32 lErrno = mysql_errno(GetHandle());   // It's possible this attempted reconnect throws 2006 at us. To prevent crazy recursive calls, sleep here.
            ACE_OS::sleep(3);                           // Sleep 3 seconds
            return _HandleMySQLErrno(lErrno);           // Call self (recursive)
        }

        // Query related errors - skip query
        case 1058:      // "Column count doesn't match value count"
        case 1062:      // "Duplicate entry '%s' for key '%d'"
        case 1054:      // "Unknown column '%s' in 'order clause'"
            return false;

        default:
            sLog->outSQLDriver("Unhandled MySQL errno %u. Unexpected behaviour possible.", errNo);
            return false;
    }
}
Beispiel #12
0
Datei: mysql.c Projekt: FileGo/wx
int restoreDbConn(void) {
	mysql_thread_id(dbh);
	
	if(mysql_ping(dbh) != 0) {
		return 0;
	}
	
	// int ret2 = mysql_thread_id(dbh);
	
	return 1;
	
}
Beispiel #13
0
static int test_conc75(MYSQL *my)
{
  int rc;
  MYSQL *mysql;
  int i;
  my_bool reconnect= 1;

  mysql= mysql_init(NULL);

  mysql_options(mysql, MYSQL_OPT_RECONNECT, &reconnect);
  mysql_real_connect(mysql, hostname, username, password, schema, port, socketname, 0| CLIENT_MULTI_RESULTS | CLIENT_REMEMBER_OPTIONS);

  rc= mysql_query(mysql, "DROP TABLE IF EXISTS a");
  check_mysql_rc(rc, mysql);

  rc= mysql_query(mysql, "CREATE TABLE a (a varchar(200))");
  check_mysql_rc(rc, mysql);

  rc= mysql_set_character_set(mysql, "utf8");
  check_mysql_rc(rc, mysql);

  for (i=0; i < 10; i++)
  {
    ulong thread_id= mysql_thread_id(mysql);
    /* force reconnect */
    mysql_options(mysql, MYSQL_OPT_RECONNECT, &reconnect);
    diag("killing connection");
    mysql_kill(my, thread_id);
    sleep(2);
    mysql_ping(mysql);
    rc= mysql_query(mysql, "load data local infile './nonexistingfile.csv' into table a (`a`)");
    FAIL_IF(!test(mysql->options.client_flag | CLIENT_LOCAL_FILES), "client_flags not correct");
    diag("thread1: %d %d", thread_id, mysql_thread_id(mysql));
    FAIL_IF(thread_id == mysql_thread_id(mysql), "new thread id expected");
    //diag("cs: %s", mysql->charset->csname);
    //FAIL_IF(strcmp(mysql->charset->csname, "utf8"), "wrong character set");
  }
  mysql_close(mysql);
  return OK;
}
Beispiel #14
0
void CDataBaseThread::__run()
{
	while ( true )
	{
		if ( ProcessRequest() )
			break ;
		if ( !m_bRunning )
		{
			ProcessRequest(); 
			break;
		}

		Sleep(1);

		if ( time(NULL) >= m_tNextMysqlPingTime )
		{
			unsigned long id = mysql_thread_id(m_pMySql);
			mysql_ping(m_pMySql);
			if ( id != mysql_thread_id(m_pMySql) )
			{
				// reconnected ;
				if (!mysql_set_character_set(m_pMySql, "utf8"))
				{
					printf("Reconnect !!! New client character set: %s\n",
						mysql_character_set_name(m_pMySql));
				}
			}
			m_tNextMysqlPingTime = time(NULL) + MYSQL_PING_TIME;
		}
	}

	if ( m_pMySql )
	{
		mysql_close(m_pMySql) ;
	}
}
nsresult
mozSqlConnectionMysql::CancelExec()
{
  unsigned long id = mysql_thread_id(mConnection);
  mysql_kill(mConnection, id);

  if (mysql_errno(mConnection)) {
    mErrorMessage.Assign(NS_ConvertUTF8toUTF16(mysql_error(mConnection)));
    return NS_ERROR_FAILURE;
  }

  mysql_ping(mConnection);

  return NS_OK;
}
Beispiel #16
0
MySQL::MySQL(const std::string &host, const std::string &user, const std::string &pass, const std::string &db, short p = 0) :
	user(user), pass(pass), host(host), db(db), port(p)
{
	printf("MySQL client version: %s\n", mysql_get_client_info());

	// Create the MySQL object
	this->con = mysql_init(NULL);

	if (!con)
		throw MySQLException("Failed to create a mysql object!");

	// Authenticate to the MySQL database
	if (!this->DoConnection())
		throw MySQLException(tfm::format("%s (%d)", mysql_error(this->con), mysql_errno(this->con)));

	printf("Connected to %s: %lu\n", host.c_str(), mysql_thread_id(this->con));
}
long int Database::getID() {
	return mysql_thread_id(&conn);
}
Beispiel #18
0
unsigned long CDatabase_Connection::thread_id()
{
	return mysql_thread_id(&my);
}
Beispiel #19
0
/*	thread_id()	*/
static VALUE thread_id(VALUE obj)
{
    return INT2NUM(mysql_thread_id(GetHandler(obj)));
}
Beispiel #20
0
BOOL ProList(const char * strParas , char * szReturn , int &nSize)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	bool bRet = false;
	CString strHost = _T("");
	CString strUserName = _T("");
	CString strPWD = _T("");
	int nPort = 3306;	//MySQL的默认端口号是3306

	MYSQL_RES * res;	//MYSQL数据库的记录集指针
	MYSQL_ROW row;		
	MYSQL	*mysql;	//接收MySQL数据的对象
	CStringList paramList;
	MakeStringListByChar(paramList, strParas);
	POSITION pos = paramList.GetHeadPosition();
	while(pos)
	{
		CString strTemp = paramList.GetNext(pos);
		if(strTemp.Find(__MACHINENAME__, 0)==0)
		{
			strHost = strTemp.Right(strTemp.GetLength() - (int)strlen(__MACHINENAME__));
		}
		else if(strTemp.Find(__PORT__, 0)==0)
		{
			nPort = atoi(strTemp.Right(strTemp.GetLength() - (int)strlen(__PORT__)));
		}
		else if(strTemp.Find(__USERACCOUNT__ , 0)==0)
		{
			strUserName = strTemp.Right(strTemp.GetLength() - (int)strlen(__USERACCOUNT__));
		}
		else if(strTemp.Find(__PASSWORD__ , 0)==0)
		{
			strPWD = strTemp.Right(strTemp.GetLength() - (int)strlen(__PASSWORD__));
		}
	}

	if(strHost.IsEmpty())
	{
		sprintf(szReturn,"error = %s",FuncGetStringFromIDS("SV_MYSQL","MYSQL_SERVER_HOST_IS_NULL"));
		return false;
	}
	if(nPort<=0)
	{
		sprintf(szReturn,"error = %s",FuncGetStringFromIDS("SV_MYSQL","MYSQL_SERVER_PORT_IS_BAD"));
		return false;
	}
	unsigned int i=0;
	CString strTMP = _T("");
	//////////////////////////////////////////////////

	int nID =0;							//MYSQL线程标识,你要kill一个语句的时候很有用
	unsigned long nCurrentID = 0;

	//////////////////////////////////////////////////



	if((mysql = mysql_init((MYSQL   *)NULL)) && mysql_real_connect(mysql,strHost, strUserName, strPWD, NULL, nPort,  NULL, 0))
	{
		res = mysql_list_processes(mysql);
		nCurrentID = mysql_thread_id(mysql);    //获取当前线程ID号。
		while(row = mysql_fetch_row(res))
		{
			
			nID = atoi(row[0]);
			if(nID==nCurrentID)
			{
				break;
			}

			sprintf(szReturn,"%d=%d$",nID,nID);
			strTMP+=szReturn;
			
		}
		sprintf(szReturn,"%s$",strTMP.GetBuffer(1));
		CString strInput ;
		strInput =szReturn;
		MakeCharByString(szReturn,nSize,strInput);

		mysql_free_result(res);		//关闭查询的结果集
		mysql_close(mysql);

		bRet = TRUE;
	}
	else
	{
		sprintf(szReturn, "error=%s(%s:%d)$", FuncGetStringFromIDS("SV_MYSQL",
            "MYSQL_CONNECT_DATABASE_FAILED"), strHost, nPort);
		fprintf(stderr, "Failed to connect to database: Error: %s\n",
          mysql_error(mysql));

        mysql_close( mysql ) ;
        return FALSE;
	}
/*
	const char * strEnd = szReturn;
	while(*strEnd)
	{
		PrintLog(strEnd);
		strEnd+=strlen(strEnd)+1;
	}
*/
	return TRUE;	
}
Beispiel #21
0
Variant f_mysql_thread_id(CVarRef link_identifier /* = uninit_null() */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (!conn) return false;
  return (int64_t)mysql_thread_id(conn);
}
Beispiel #22
0
ulong MYSQLC::GetThreadID(void)
  {
  return (m_DB) ? mysql_thread_id(m_DB) : 0;
  } // end of GetThreadID
Beispiel #23
0
Variant HHVM_FUNCTION(mysql_thread_id,
                      const Variant& link_identifier /* = uninit_null() */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (!conn) return false;
  return (int64_t)mysql_thread_id(conn);
}
Beispiel #24
0
unsigned long vt_thread_id(VT_CONN *conn) {
  mysql_thread_init();
  return mysql_thread_id(conn->mysql);
}
Beispiel #25
0
BOOL ProInfo(const char * strParas , char * szReturn , int &nSize)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());


	bool bRet = false;
	CString strHost = _T("");
	CString strUserName = _T("");
	CString strPWD = _T("");
	int nProID=0;		//保存传进来的进程ID号
	int nPort = 3306;	//MySQL的默认端口号是3306

	MYSQL_RES * res;	//MYSQL数据库的记录集指针
	MYSQL_ROW row;		
	MYSQL	*mysql;	//接收MySQL数据的对象
	CStringList paramList;
	MakeStringListByChar(paramList, strParas);
	POSITION pos = paramList.GetHeadPosition();
	while(pos)
	{
		CString strTemp = paramList.GetNext(pos);
		if(strTemp.Find(__MACHINENAME__, 0)==0)
		{
			strHost = strTemp.Right(strTemp.GetLength() - (int)strlen(__MACHINENAME__));
		}
		else if(strTemp.Find(__PORT__, 0)==0)
		{
			nPort = atoi(strTemp.Right(strTemp.GetLength() - (int)strlen(__PORT__)));
		}
		else if(strTemp.Find(__USERACCOUNT__ , 0)==0)
		{
			strUserName = strTemp.Right(strTemp.GetLength() - (int)strlen(__USERACCOUNT__));
		}
		else if(strTemp.Find(__PASSWORD__ , 0)==0)
		{
			strPWD = strTemp.Right(strTemp.GetLength() - (int)strlen(__PASSWORD__));
		}
		else if(strTemp.Find(__PROID__, 0)==0)
		{
			nProID = atoi(strTemp.Right(strTemp.GetLength() - (int)strlen(__PROID__)));
		}
	}

	if(strHost.IsEmpty())
	{
		sprintf(szReturn,"error = %s",FuncGetStringFromIDS("SV_MYSQL","MYSQL_SERVER_HOST_IS_NULL"));
		return false;
	}
	if(nPort<=0)
	{
		sprintf(szReturn,"error = %s",FuncGetStringFromIDS("SV_MYSQL","MYSQL_SERVER_PORT_IS_BAD"));
		return false;
	}
	unsigned int i=0;
	CString strTMP = _T("");
	//////////////////////////////////////////////////

	int nID = 0;						//MYSQL线程标识,你要kill一个语句的时候很有用
	CString strDBUser = _T("");			//user列,显示当前用户,如果不是root,这个命令就只显示你权限范围内的sql语句
	CString strDBHost = _T("");			//host列,显示这个语句是从哪个ip的哪个端口上发出的
	CString strDatabase = _T("");		//db列,显示这个进程目前连接的是哪个数据库
	CString strCommand = _T("");		//command列,显示当前连接的执行的命令,一般就是休眠(sleep),查询(query),连接(connect)。
	int nTime = 0;						//time列,此这个状态持续的时间,单位是秒
	CString strState = _T("");			//state列,显示使用当前连接的sql语句的状态
	CString strInfo = _T("");			//info列,显示这个sql语句,因为长度有限,所以长的sql语句就显示不全
	unsigned long nCurrentID = 0;		//当前线程ID

	int nTotalConn=0;					//连接总数
	map<CString,int> hostMap;
	map<CString,int>::const_iterator ptrHost;
	typedef pair <CString,int> hostPair;

	//////////////////////////////////////////////////

	if((mysql = mysql_init((MYSQL   *)NULL)) && mysql_real_connect(mysql,strHost, strUserName, strPWD, NULL, nPort,  NULL, 0))
	{
//		res = mysql_list_processes(mysql);
		CString strCommand=_T("");
		mysql_query(mysql,"show processlist");
		res = mysql_store_result(mysql);
		nCurrentID = mysql_thread_id(mysql);	//获取当前线程ID
		strCommand.Format("kill %d",nCurrentID);
		while(row = mysql_fetch_row(res))
		{	
			nID = atoi(row[0]);
			strDBUser = row[1];
			strDBHost = row[2];
			strDatabase = row[3];
			strCommand = row[4];
			nTime = atoi(row[5]);
			strState = row[6];
			strInfo = row[7];
			strDBHost=strDBHost.Left(strDBHost.Find(':'));		//擦掉获得的主机端口号
			ptrHost = hostMap.find(strDBHost.GetBuffer(strDBHost.GetLength()));

			if(nID!=nCurrentID)
			{
				if(ptrHost==hostMap.end())
				{
					hostMap.insert(hostPair(strDBHost.GetBuffer(strDBHost.GetLength()),1));
				}																						//用MAP保存主机名,并且将主机出现次数统计在键值中
				else
				{
					hostMap[strDBHost.GetBuffer(strDBHost.GetLength())]++;
				}
			}
/*
			else
			{
				PrintLog(row[0]);
				PrintLog(row[2]);
			}
*/			
			nTotalConn++;
		}

		nTotalConn=nTotalConn-1;		//减去自身的连接
		for(ptrHost=hostMap.begin();ptrHost!=hostMap.end();ptrHost++)
		{
			strTMP.Format("%s%s的连接数是%d,",strTMP.GetBuffer(strTMP.GetLength()),ptrHost->first,ptrHost->second);
		}
		strTMP.Delete(strTMP.GetLength()-1,1);			//去除返回值后多余的一个“,”
		sprintf(szReturn,"nTotalConn=%d$result=%s",nTotalConn,strTMP.GetBuffer(strTMP.GetLength()));

		CString strInput ;
		strInput =szReturn;
		MakeCharByString(szReturn,nSize,strInput);
		mysql_free_result(res);				//释放结果集使用的内存。
		mysql_close(mysql);					// 关闭服务器连接。
		bRet = TRUE;

	}
	else
	{
		sprintf(szReturn, "error=%s(%s:%d)$", FuncGetStringFromIDS("SV_MYSQL",
            "MYSQL_CONNECT_DATABASE_FAILED"), strHost, nPort);
		fprintf(stderr, "Failed to connect to database: Error: %s\n",
          mysql_error(mysql));

        mysql_close( mysql ) ;
        return FALSE;
	}

/*
	const char * strEnd=szReturn;
	while(*strEnd)
	{
		PrintLog(strEnd);
		strEnd+=strlen(strEnd)+1;
	}
*/
	return bRet;	
}
Beispiel #26
0
unsigned long SQLCONN::thread_id()
{
	return(mysql_thread_id(&(this->mysql_connx)));
}