Database changed что это

Обновлено: 02.07.2024

Это первая часть. Вторая часть, в которой описаны примеры заполнения таблиц данными находится тут>>>.

Ниже будут приведены наиболее полезные при работе с MySQL команды и примеры их выполнения.

Для примера будет создана таблица, содержащая список контактов.

Для подключения к серверу MySQL используется такая команда:

$ mysql -u username -p
Enter password:
mysql>

Threads: 5 Questions: 8391067 Slow queries: 37 Opens: 17162 Flush tables: 1 Open tables: 64 Queries per second avg: 12.044

mysql> use base1;
Database changed

Просмотреть содержащиеся в ней таблицы можно командой:

В базе base1 имеется только одна таблица tablename .

А просмотреть имеющиеся в базе данных MySQL таблицы из консоли можно так:

Посмотреть содержимое таблицы из консоли можно следующим образом:

$ mysqlshow base1 tablename -u root -p

Выполнять запросы SQL можно как из консоли сервера, так и из консоли клиента mysql . Так же, запросы можно вводить не напрямую, а из файла. К примеру, имеется файл с таким содержимым:

$ cat temp.sql
select now()

$ mysql -u root -p < temp.sql
Enter password:
now()
2013-01-31 17:59:43

При этом, файл должен находится в каталоге, в котором вы находились перед подключением к mysql -клиенту.

При создании таблицы используется такой синтаксис:

имя_столбца ТИП(значение) АТРИБУТ

Атрибуты могут иметь значение либо NULL (может быть пустым), либо NOT NULL — обязательно должен быть заполнен.

В примере будут использоваться такие типы столбцов:

PRIMARY KEY указывает, что указанные столбцы являются индексами, подробнее тут>>>.

mysql> CREATE TABLE main_list (contact_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT NOT NULL, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50), phone VARCHAR(20), city VARCHAR(20), email VARCHAR(50), skype VARCHAR(20), icq INT UNSIGNED, birth_date DATE, facebook_address VARCHAR(50), vk_address VARCHAR(50), real_type ENUM(‘Y’, ‘N’));
Query OK, 0 rows affected (0.26 sec)

Добавим вторую таблицу:

mysql> CREATE TABLE main_socials (entry_id INT UNSIGNED AUTO_INCREMENT NOT NULL, contact_id INT UNSIGNED NOT NULL, vk_id VARCHAR(100), facebook_id VARCHAR(100), PRIMARY KEY (entry_id, contact_id));
Query OK, 0 rows affected (0.01 sec)

ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key

ERROR 1068 (42000): Multiple primary key defined

mysql> drop table tablename;
Query OK, 0 rows affected (0.75 sec)

mysql> ALTER TABLE tablename DROP COLUMN column_name;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0

Это первая часть. Вторая часть, в которой описаны примеры заполнения таблиц данными находится тут>>>.

How can I detect the latest updates made to a database and silently refresh a page when a change occurs?

Let's say the database access looks like:

Any ideas and samples would be appreciated. Thank you.

51.9k 11 11 gold badges 114 114 silver badges 155 155 bronze badges 225 2 2 gold badges 5 5 silver badges 11 11 bronze badges

The best way to manage database changes [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 7 years ago .

What is the best way to manage database changes? I need to have a solutions regardless the database client's language. Also I'd like to be able to use specific database features in those changes such as stored procedures, triggers and so on.

23.4k 16 16 gold badges 71 71 silver badges 76 76 bronze badges

6 Answers 6

First of all, make sure you have your entire Database Build scripted so you can rebuild the database if needed.

Each change should then be written as an Update script. That way you can run each change individually against the your databases.

Once the change has been commited to the codebase, merge the change script with the build process so it happens automatically. and then archive the change script in case any questions arise.

232k 36 36 gold badges 397 397 silver badges 525 525 bronze badges

First and foremost, put all database changes in scripts and put them into the source control system.

Next remove any permissions to production that developers have. Exactly two people should have rights on production in a small to medium shop, the designated dba and his or her designated alternate. Once devs can't make changes to prod, you will find it easier to get them to actually write and use scripts.

Never run a script on prod that wasn't first loaded to QA or staging. If there are issues with the script, it should be found at this point.

MySQL/MariaDB: наиболее используемые команды, примеры

Ниже предоставлен список наиболее полезных и часто используемых команд MySQL с примерами.

Это перевод статьи отсюда>>>, с некоторыми незначительными изменениями и дополнениями.

mysql> в начале строки означает, что команда выполняется из MySQL-клиента.

Общие команды

Что бы проверить статус сервера MYSQL выполните:

Что бы подключиться к серверу MySQL из консоли, если сервер MySQL находится на том же хосте:

Работа с базами и таблицами

Работа с базами

Создать базу данных на MySQL сервере:

Показать список всех баз данных на сервере MySQL:

Переключиться для работы с определенной базой данных:

Работа с таблицами

Отобразить все таблицы в базе данных:

Просмотреть формат таблицы в базе:

Показать все содержимое таблицы:

Отобразить количество строк в таблице:

Подсчитать количество колонок в таблице:

Удаление строки в таблице:

mysql> DELETE from [table name] where [field name] = 'whatever';

Удаление столбца из таблицы:

mysql> alter table [table name] DROP INDEX [column name];

Удалить таблицу из базы:

Работа с колонками

Добавить колонку в таблицу:

mysql> ALTER TABLE [table name] ADD COLUMN [new column name] varchar (20);

Изменение имени колонки:

mysql> ALTER TABLE [table name] CHANGE [old column name] [new column name] varchar (50);

Создать колонку с уникальным именем, что бы избежать дубликатов в названиях:

mysql> ALTER TABLE [table name] ADD UNIQUE ([column name]);

Изменение размера колонки:

mysql> ALTER TABLE [table name] MODIFY [column name] VARCHAR(3);
Выборка данных

Показать все содержимое таблицы:

Отобразить колонки и их содержимое в выбранной таблице:

mysql> SELECT * FROM [table name] WHERE [field name] = "whatever"; mysql> SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444'; mysql> SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444' order by phone_number; mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444'; mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444' limit 1,5;

Показать все уникальные записи:

Отобразить выбранные записи, отсортированные по возрастанию ( asc ) или убыванию ( desc ):

mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;
Регулярные выражения
Импорт и экспорт данных в/из файла

Загрузка файла CSV в таблицу:

mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY 'n' (field1,field2,field3);

Пользователи, пароли сервера MySQL:добавление, изменение пользователей и паролей

mysql> INSERT INTO user (Host,User,Password) VALUES('%','username', PASSWORD('password')); mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');

Восстановление/изменение пароля root сервера MySQL — остановка MySQL, запуск без таблиц привилегий, подключение под root , установка нового пароля, выход и перезапуск MySQL.

Подробнее о восстановлении пароля root для MySQL написано тут>>>.

6 Answers 6

This is how I recently implemented a solution using jQuery.

PHP increments a field in the database every time a significant update occurs.

When the page is initially loaded, populate a JavaScript variable with a number from the database:


2,202 2 2 gold badges 23 23 silver badges 24 24 bronze badges @OfirAttia: Yeah, the echoing was done by the PHP script that generated the JavaScript. I should have made that clear. Ok, for you aknowloedge i took you code and did some changes because i faced with this problem and didnt success to refresh the page with what you gave.. maybe i missed something. but you can see below my post.

Here is what I did and used the answer you marked but I think there is a few things to change there. In the main page ( that you want to refresh if something changed in the database). I created a table in my database called setting, in this table i created a row that called rowCounter. the rowCounter is being updated when the numbers of rows in the table you check has been changed. so my code split in two blocks. one that giving me the number from the setting > rowCounter and the second is the script that give me the current number in the table. if they are not equal then I refresh the page.

so this is the first file you need
script_to_return_latest_pageGenID.php


In the main page you will write the two blocks of code I provided and you should put it before the script.

After this code you put the script that will query every few seconds the php script, check if the numbers are not equal it will refresh the page.


1,117 4 4 gold badges 19 19 silver badges 38 38 bronze badges What about if you change a record? The num of rows will be not changed. @macmuri actually this is an old post, I would suggest to use WebSockets for notifying your website to fetch your API again upon changes in db. if you still want to use this approach, I would suggest here to add another flag for it ( 0 or 1 ) when its 1 you will refresh the page and change it back to 0 and every change on the db will update this flag to 1.

I believe you'd have to poll the database when you use PHP, PHP doesn't exist in a long running process as in the case of a Java container where the Java web application could create a persistent connection (in theory) you'll likely need to employ some sort of polling mechanism by which I mean setup a timer in Javascript or whatever your client code is to periodically make the request, in terms of increasing efficiency for this if need be you could create a flag on the users table and set the flag to indicate that the database has been invalidated since the user last polled, then your first check would be if invalidation has happened since that user last updated rather than sending everything to everyone all the time. Alternatively I think you'd need to abandon PHP for this task.

19.5k 4 4 gold badges 35 35 silver badges 49 49 bronze badges

When you render a page with php , you can pass a js variable witch has keeps a "current database revision" ( a number ) . On the page you make an ajax call once every 30 seconds a witch recives a new current database revision so to speak . You test for those 2 and if the one you got from the ajax call is higher then it means you need to reload the page .

On the server side you need a table to store the current revision , everytime you make a query from php you set the current revision +1 ( in the revision database table ) . When you receive an ajax call from a client you read that number from the database and you pass it on to the cilent . You can setup a cronjob that will reset the counter every day .

9,173 2 2 gold badges 36 36 silver badges 41 41 bronze badges

Strictly speaking, this is not possible. MySQL does not fire triggers back to PHP if something is changed. It's just not possible. Also, MySQL operates using sessions, so even if it could report a change in the database, you'd have to use a persistent connection in order for you to be able to access that sort of trigger.

Now, if you want to execute select statements to detect a change in the database, that's different. Depending on how "new" you want your code to be (depending on how compatible you'd like it to be) you can use any one of the following to "poll" a PHP page to check for changes: Comet, AJAX, a forever frame, or HTML5's new WebSocket class.

While other say use the client to detect a change through variables like a database version stored in javascript, I'd advise that you leave that server sided simply because people who know how to inject javascript will be able to change that value, which may produce undesired or even malicious results (even, depending on how that value is used, MySQL injections).

Читайте также: