Mysql закрыть все подключения

mysql_close

mysql_close — Закрывает соединение с сервером MySQL

Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:

  • mysqli_close()
  • PDO: Присвоить значение null объекту PDO

Описание

mysql_close() закрывает непостоянное соединение с базой данных MySQL, на которое указывает переданный дескриптор. Если параметр link_identifier не указан, закрывается последнее открытое (текущее) соединение.

Открытые непостоянные соединения MySQL и результирующие наборы автоматически удаляются сразу по окончании работы PHP-скрипта. Следовательно, закрывать соединения и очищать результирующие наборы не обязательно, но рекомендуется, так как это сразу же освободит ресурсы базы данных и память, занимаемую результатами выборки, что может положительно сказаться на производительности. Больше информации можно почерпнуть в разделе Освобождение ресурсов

Список параметров

Соединение MySQL. Если не указано, то используется последнее соединение, открытое mysql_connect() . Если соединение не найдено или не установлено, то будет сгенерирована ошибка уровня E_WARNING .

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования mysql_close()

Результат выполнения данного примера:

Примечания

mysql_close() не закрывает постоянные соединения, созданные функцией mysql_pconnect() . Для дополнительной информации смотрите руководство по постоянным соединениям.

Смотрите также

  • mysql_connect() — Открывает соединение с сервером MySQL
  • mysql_free_result() — Освобождает память от результата запроса

User Contributed Notes 6 notes

A little note about multiple simultaneous connections to different hosts.

I work on a site that pulls content primarily from one db but uses a db on a foreign server to verify licensing. One might expect the following to work:

// Open the connection to the primary db
$res1 = mysql_connect ( $host1 , $user1 , $pass1 );
mysql_select_db ( $db1 );

// Open connection to the license server
$res2 = mysql_connect ( $host2 , $user2 , $pass2 );
mysql_select_db ( $db2 , $res2 );

// Pull license data and close when done
mysql_query ( $check_sql , $res2 );
// .
mysql_close ( $res2 );

// Now pull content from the primary db
// Not specifying the resource should default to the last open db
mysql_query ( $query );
// .
?>

Turns out this last query, since it cant find an active connection, will try to connect with mysql_connect() with no paramaters. But if instead you do it as mysql_query($query, $res1), or alternatively, run the mysql_connect for this host again then it works fine. Thus, it doesnt seem to be possible to have code with an overarching «global» db connection interspersed with temporary connections to another host/db.

i just came over a problem that i had with apache.

It crashs and said :

«Parent: child process exited with status 3221225477 — Restarting.»

the error came from the extesion php_mysql.dll

i didn’t understand what was the reason of that crash..

Then, i debug the script that i had downloaded and i noticed that that was the function mysql_close() which caused the problem.

The solution is, to send to it the link identifier which is optionnal in the description but cause a crash with no commentary.

Thanks to agneady.

The variable is definitely not optional in 5.3. Caused me a bit of a headache when I was debugging until I realized it was the close function that was causing a hang. So if using just:

Рекомендуем:  Как продиагностировать блок питания телевизора

mysql_close ( $connection );
?>

(where $connection is any variable of your choice)

As at 5.0.x and 4.3.x: This function should never be used with shared links; instead you should set your link variables to null.
(This explains red’s and beer’s () problems in previous comments)

Here is how shared links work:
— Each link is a resource. mysql_connect() by default looks for a resource with the same paramaters. If one exists, it will return the existing resource.
— Every assignment of that resource to a variable increases the resource’s reference count.
— When the reference is decremented to zero, the underlying TCP/socket connection is closed.
— Every assignment of a variable away from that resource decrements the reference count. (This includes a function level variable going out of scope)
— mysql_close() also decrements the reference count.

Note the last two points: mysql_close() _and_ reassignment of a variable decrement the link’s reference count.

A common mistake is a function like:

function dothings () <
$link = mysql_open (. );
// .. do some queries ..
mysql_close ( $link )
$link = null ;
>
?>

this will decrement the counter twice, possibly closing the underlying connection and causing errors in other parts of the program.

Источник

Mysql закрыть все подключения

Each connection to mysqld runs in a separate thread. You can kill a thread with the KILL processlist_id statement.

Thread processlist identifiers can be determined from the ID column of the INFORMATION_SCHEMA PROCESSLIST table, the Id column of SHOW PROCESSLIST output, and the PROCESSLIST_ID column of the Performance Schema threads table. The value for the current thread is returned by the CONNECTION_ID() function.

KILL permits an optional CONNECTION or QUERY modifier:

KILL CONNECTION is the same as KILL with no modifier: It terminates the connection associated with the given processlist_id , after terminating any statement the connection is executing.

KILL QUERY terminates the statement the connection is currently executing, but leaves the connection itself intact.

The ability to see which threads are available to be killed depends on the PROCESS privilege:

Without PROCESS , you can see only your own threads.

With PROCESS , you can see all threads.

The ability to kill threads and statements depends on the CONNECTION_ADMIN privilege and the deprecated SUPER privilege:

Without CONNECTION_ADMIN or SUPER , you can kill only your own threads and statements.

With CONNECTION_ADMIN or SUPER , you can kill all threads and statements, except that to affect a thread or statement that is executing with the SYSTEM_USER privilege, your own session must additionally have the SYSTEM_USER privilege.

When you use KILL , a thread-specific kill flag is set for the thread. In most cases, it might take some time for the thread to die because the kill flag is checked only at specific intervals:

During SELECT operations, for ORDER BY and GROUP BY loops, the flag is checked after reading a block of rows. If the kill flag is set, the statement is aborted.

ALTER TABLE operations that make a table copy check the kill flag periodically for each few copied rows read from the original table. If the kill flag was set, the statement is aborted and the temporary table is deleted.

Рекомендуем:  Pioneer deh x8600bt схема подключения

The KILL statement returns without waiting for confirmation, but the kill flag check aborts the operation within a reasonably small amount of time. Aborting the operation to perform any necessary cleanup also takes some time.

During UPDATE or DELETE operations, the kill flag is checked after each block read and after each updated or deleted row. If the kill flag is set, the statement is aborted. If you are not using transactions, the changes are not rolled back.

GET_LOCK() aborts and returns NULL .

If the thread is in the table lock handler (state: Locked ), the table lock is quickly aborted.

If the thread is waiting for free disk space in a write call, the write is aborted with a “ disk full ” error message.

EXPLAIN ANALYZE aborts and prints the first row of output. This works in MySQL 8.0.20 and later.

Killing a REPAIR TABLE or OPTIMIZE TABLE operation on a MyISAM table results in a table that is corrupted and unusable. Any reads or writes to such a table fail until you optimize or repair it again (without interruption).

Источник

Terminate MySQL Connections

Every so often I run into a situation when I need to terminate connections on MySQL server – for example, hundreds of instances of some bad query is running, making the server unusable. Many people have special scripts which can take the user, source host, or query as a parameter and perform the action. There is also a way to do it just using MySQL with a few commands:

In general, this is a very powerful approach which I use in a lot of cases to create a set of SQL statements by SQL query and then execute it.

It would be nice and clean if MySQL would have some way to “eval” – execute the result set of the query as SQL commands. This would avoid the requirement to use temporary file etc.

Author

Peter managed the High Performance Group within MySQL until 2006, when he founded Percona. Peter has a Master’s Degree in Computer Science and is an expert in database kernels, computer hardware, and application scaling.

You are not the only one. I’ve thought that this would be handy several times.

Create a session variable and then make it so that it can be parsed by the parser?

Not terribly hard.

Yes that is one possibility. Though I think it is nicer if result set can be executed line by line – the GROUP_CONCAT trick works but it is typically restricted in size.

Could you please update your post to point out that this feature is 5.1+?

I prefer the following as it will kill them in a multi threaded manner… (sometimes killing a single query can take a while)

for i in $(mysql -uroot -pPASS -e ‘show processlist’ | grep ‘search_term’ | awk ‘’); do
mysql -uroot -pPASS -e “kill $i” &
done

Peter,
Couldn’t you use prepared statements as an eval?

could also be a modifier to the client instead of a special sql construct (much like \G)

PROCESSLIST table exists in MySQL 5.1 as well as Percona patches MySQL 5.0 I actually used later for this test.

With INFORMATION_SCHEMA.PROCESSLIST one can create a stored procedure using server cursor to achieve this. The following procedure accepts a user name and kills all queries for that user.
server cursors are a MySQL solution for ‘eval’.

Рекомендуем:  Как сделать андервольт ноутбука

DROP PROCEDURE IF EXISTS test . kill_user_queries $$
CREATE PROCEDURE test . kill_user_queries (kill_user_name VARCHAR(16) CHARSET utf8)
SQL SECURITY INVOKER
BEGIN
DECLARE query_id INT;
DECLARE iteration_complete INT DEFAULT 0;
DECLARE select_cursor CURSOR FOR SELECT id FROM INFORMATION_SCHEMA.PROCESSLIST WHERE user=kill_user_name;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET iteration_complete=1;

OPEN select_cursor;
cursor_loop: LOOP
FETCH select_cursor INTO query_id;
IF iteration_complete THEN
LEAVE cursor_loop;
END IF;
KILL QUERY query_id;
END LOOP;
CLOSE select_cursor;

Источник

mysql_close — Закрывает соединение с сервером MySQL

mysql_close — Закрывает соединение с сервером MySQL

Данное расширение устарело, начиная с версии PHP 5.5.0, и будет удалено в будущем. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API и соответствующий FAQ для получения более подробной информации. Альтернативы для данной функции:

  • mysqli_close()
  • PDO: Присвоить значение NULL объекту PDO

Описание

mysql_close() закрывает непостоянное соединение с базой данных MySQL, на которое указывает переданный дескриптор. Если параметр link_identifier не указан, закрывается последнее открытое (текущее) соединение.

В использовании mysql_close() обычно нет надобности для непостоянных соединений, т.к. они автоматически закрываются в конце скрипта. См. также высвобождение ресурсов.

Список параметров

Соединение MySQL. Если не указано, то используется последнее соединение, открытое mysql_connect() . Если соединение не найдено или не установлено, то будет сгенерирована ошибка уровня E_WARNING .

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования mysql_close()

Результат выполнения данного примера:

Примечания

mysql_close() не закрывает постоянные соединения, созданные функцией mysql_pconnect() .

Смотрите также

  • mysql_connect() — Открывает соединение с сервером MySQL
  • mysql_free_result() — Освобождает память от результата запроса

Источник

mysqli::close

(PHP 5, PHP 7, PHP 8)

mysqli::close — mysqli_close — Закрывает ранее открытое соединение с базой данных

Описание

Закрывает ранее открытое соединение с базой данных.

Открытые непостоянные соединения MySQL и наборы результатов автоматически закрываются при уничтожении их объектов. Явное закрытие открытых соединений и освобождение наборов результатов не обязательно. Однако рекомендуется закрыть соединение, как только скрипт завершит выполнение всех своих операций с базой данных, если ему ещё предстоит большая обработка после получения результатов.

Список параметров

Только для процедурного стиля: объект mysqli , полученный с помощью mysqli_connect() или mysqli_init() .

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования mysqli::close()

( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );

$result = $mysqli -> query ( «SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3» );

/* Закройте соединение, как только оно становится ненужным */
$mysqli -> close ();

foreach ( $result as $row ) <
/* Обработка данных, полученных из базы данных */
>

( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );

$result = mysqli_query ( $mysqli , «SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3» );

/* Закройте соединение, как только оно становится ненужным */
mysqli_close ( $mysqli );

foreach ( $result as $row ) <
/* Обработка данных, полученных из базы данных */
>

Примечания

mysqli_close() не закрывает постоянные соединения. Для получения подробностей смотрите руководство по persistent connections.

Смотрите также

  • mysqli::__construct() — Устанавливает новое соединение с сервером MySQL
  • mysqli_init() — Инициализирует MySQLi и возвращает объект для использования в функции mysqli_real_connect()
  • mysqli_real_connect() — Устанавливает соединение с сервером mysql
  • mysqli_free_result() — Освобождает память, занятую результатами запроса

Источник

Adblock
detector