Drug preguntas

Mysql Collation Setup

MySql No Comments »

Here are the steps to change MySQL collation from phpMyAdmin in cPanel:

[1] Login to your cPanel and click on “phpMyAdmin” icon.
[2] Click on your database name and the go to “Operations” tab.
[3] At the bottom of the page you will see the collation option. You can now select a collation from the drop down menu and click on the Go button.

Please note that the new collation will be set for new tables only. Old table will use the previous collation under which they were created. If you want to use new collation for already created tables, you will need to change collation for all tables.

Mysql Stored Procedure.

MySql No Comments »

Make sure mysqli is supported.

If you are not able to successfully run stored procedure, please read this.

If you create a stored procedure from remote mysql it opens a record in information_schema database routines table with definer username@ip.You can not access this s.p. with php. if you create a s.p. from php my admin it opens a record in information_schema database routines table with definer username@localhost. If you create a s.p. from php, I mean a file from server it opens a record in information_schema database routines table with definer.a s.p. created from phpmyadmin can only be called from phpmyadmin.but a s.p. created from server (a file in public_html folder) can be called from web site

MySql Tips

MySql No Comments »

1)To check Max Connections
mysql> show variables like ‘%connections’;
+———————-+——-+
| Variable_name | Value |
+———————-+——-+
| max_connections | 100 |
| max_user_connections | 0 |
+———————-+——-+
2 rows in set (0.63 sec)

Also,
mysql> select user, max_connections, max_updates,max_questions from mysql.user;
+—————–+————-+—————+
| max_connections | max_updates | max_questions |
+—————–+————-+—————+
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 |

This may show something useful.

You could also setup an alert for yourself to warn you, and then find out what is really going on. Use the script below.. change the commands as required..

#!/bin/bash

ALERT_DEST=email.addr@email.add
NUM_PROCESSES=`/usr/local/mysql/bin/mysql -e “show processlist;”|wc -l`

MAX_BEFORE_ALERT=25

if [ ${NUM_PROCESSES} -gt ${MAX_BEFORE_ALERT} ]
then
echo |/usr/bin/mail -s “WARNING: MYSQL CONNECTIONS=${NUM_PROCESSES}” ${ALERT_DEST}
fi

Backup mysql db using Cron.

MySql No Comments »
  • Backup mysql db using Cron.
    date=`date -I` ; mysqldump -uusername -pthepass .all-databases | gzip >
    /home/linux/mysql_$date.sql.gz
  • Replace username and thepass with the correct username and the pass.
  • The user need to have access to the database being taken for backup.

How To Create My SQL Database And CREATE And GRANT Privileges

MySql No Comments »

HOW TO CREATE THE MySQL DATABASE

This step is only necessary if you don’t already have a database set-up . In the following examples, ‘username’ is an example MySQL user which has the CREATE and GRANT privileges. Use the appropriate user name for your system.

First, you must create a new database for your site (here, ‘databasename’ is the name of the new database):

  mysqladmin -u username -p create databasename

MySQL will prompt for the ‘username’ database password and then create the initial database files. Next you must login and set the access database rights:

  mysql -u username -p

Again, you will be asked for the ‘username’ database password. At the MySQL prompt, enter following command:

  GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES
  ON databasename.*  TO 'username'@'localhost' IDENTIFIED BY 'password';

  where

 'databasename' is the name of your database
 'username@localhost' is the username of your MySQL account
 'password' is the password required for that username

Note: Unless your database user has all of the privileges listed above, you will not be able to run site on that database.

If successful, MySQL will reply with:

  Query OK, 0 rows affected

To activate the new permissions, enter the following command:

  FLUSH PRIVILEGES;

MySql Access denined error.

MySql No Comments »

Check the URL http://dev.mysql.com/doc/refman/5.0/en/access-denied.html

How to take mysql dump without any data

MySql No Comments »

mysqldump -u root dbname –no-data -p > /tmp/db.sql

This will take the DB dump without any data and will create a db.sql file in /tmp.

Mysql Server Optimization for DBA

MySql No Comments »

MySQL is the most widely used multi-user, multi-threading SQL database management system. To optimize MySQL performance, a DBA should have reasonable knowledge of MySQL system variables. This article covers the basics of MySQL server optimization. We will first discuss MySQL optimization during installation. Then we will discuss the seven most important and common system variables. Plus, a brief note on how to optimize the server using those seven variables.

We will also discuss MySQL status variables. This article would be very useful for a newbie MySQL DBA when setting up a MySQL server.

1. How to optimize the MySQL Installation.

Most server owners prefer to have a control panel software (like cPanel, Plesk etc) installed in their server so that they can easily manage their servers. In that case, MySQL installation will be customized according to the control panel software installed.

If you are planning to compile MySQL by your own, following are a few points which you should consider for faster performance.

  1. While compiling MySQL, compile it statically ( -static option). This will require more disk space but runs faster.
  2. Enable debug option if you actually need it. Enabling debug mode installs a safe Memory Allocation (SAFEMALLOC) checker. Running SAFEMALLOC is slow. So if you have enabled debug mode and is having performance problems, you should start mysqld with -skip-safemallaoc option.
  3. Compile without frame pointers (-fomit-frame-pointer). Frame Pointer is a pointer to the current stack frame. Frame pointer is mainly used for debugging purpose. Compiling without frame pointers make mysqld run 1-4% faster.
  4. Standard binary distributions from MySQL are compiled with support for all character sets. When you are compiling by yourself, use the character sets required for your application only. This can be specified by the -with-charset option in the configure option. Or you can use the minimum character set using the -with-extra-charsets=none option.

2. Compilation over.. Now what??

Now according to your requirement, you have compiled your MySQL server and now we can go forward with optimizing it.

Optimizing MySQL is done based on the server specifications and the applications which are running on the server. The MySQL server configuration file should be named my.cnf and is usually placed in DATADIR/my.cnf. You can specify the location to the my.cnf file using the âdefault-file argument during installation. This helps associate configuration files with particular server instances.

Fortunately, MySQL itself is providing some sample my.cnf files which fit to most of the systems. The different config files that MySQL provide are my-huge.cnf, my-large.cnf, my-medium.cnf and my-small.cnf.

Each config file is designed for different systems and it is always recommended to select the sample config according to your system specs.

  • my-huge.cnf : recommended for systems that have at least 1GB memory, and run mainly MySQL
  • my-large.cnf : for systems with slightly less memory (512MB), and also mainly running MySQL.
  • my-medium.cnf : tweaked for a system where MySQL and a Web server are running together with around 128MB, or around 64MB
  • my-small.cnf : for system with less than 64MB

So choose the right config file for your system and your server should work good. But you can get better results if you tweak the variables properly. For this you need to know the different system and status variables and how they are linked together. Remember, changing the system variables improperly may lead to worse situations.There are several MySQL system variables which can be tweaked for improving performance. But here, we will be discussing about 7 variables, tuning which can change the performance drastically.

3. Is the sample config enough for me?

I would say NO. Each database server will be running different applications in it and so you MUST fine tune your server according to the applications and resourse utilization. Now.. how can I identify the variables that need to be tweaked? And how should I go for it?

Below are the 7 most important system variables that need to be tweaked in normal case.

3.1. table_cache

Each time MySQL accesses a table, it places the table in the cache. If your application accesses many tables, it is always good to have them in cache so that data retrieve is faster.

You can check whether your system needs to have the table_cache value increased by checking the open_tables and opened_tables status variables during peak time.

open_tables is the number of tables opened in cache. Whereas opened_tables is the total number of tables open. Since MySQL supports multi-threading, several queries might be executed on the same table at the same time. So each of these queries will open a table.

The default value to table_cache is 64. Lets consider a sample scenario.

table_cache = 64
mysql> SHOW STATUS LIKE "open%tables%";
open_tables = 64
opened_tables = 5426787

Here table_cache has maxed out and opened_tables is fairly high. In this case, if you have enough memory, increase table_cache to reduce the number of opened_tables.

3.2. query_cache_size

Query caching has been introduced from MySQL 4 onwards. If your application executes a particular query again and again, MySQL can cache the result set, thereby avoiding the overhead of running through the data over and over and thereby increase the execution time.

You can enable query caching by setting the server variable query_cache_type=1 and setting the cache size in the variable query_cache_size. If either of the above is set to 0, query caching will not be enabled.

There are three status for query caching;

  1. Disabled - query_cache_type = 0
  2. Enabled - query_cache_type = 1
  3. On Demand - query_cache_type = 2

Some sample scenarios:

If you have enabled query caching and do not want the result of a particular query to be cached, you can mention it in your query by specifying SQL_NO_CACHE.

eg: SELECT SQL_NO_CACHE id, name FROM employee_info WHERE employee_rank < 5;

In the above case, the result of the query will not be cached. Similarly, you can enable query caching in ON DEMAND query caching by specifying SQL_CACHE in your query.

eg: SELECT SQL_CACHE id, name FROM employee_info WHERE employee_rank < 5;

After executing the query the result will be added to the cache memory and will used if the query is executed again.

How to check the query cache status variables

mysql> SHOW STATUS LIKE "%qcache%";
+-------------+-----+
| Variable_name | Value |
+-------------+-----+
| Qcache_free_blocks | 2253 |
| Qcache_free_memory | 9184200 |
| Qcache_hits | 247217 |
| Qcache_inserts | 50012 |
| Qcache_lowmem_prunes | 15666 |
| Qcache_not_cached | 13269 |
| Qcache_queries_in_cache | 5215 |
| Qcache_total_blocks | 13117 |
+-------------+-----+

8 rows in set (0.00 sec)

This is a result from a server with query_cache_type set to 1 ( Enabled). Now lets see what all these status variables stand for.

  • Qcache_free_blocks: The number of free memory blocks in the cache memory.
  • Qcache_free_memory: The amount of free memory for the query cache.
  • Qcache_hits : The number of query cache hits.
  • Qcache_inserts : The number of queries added to the query cache.
  • Qcache_lowmem_prunes : The number of queries that were deleted from the query cache because of low memory.
  • Qcache_not_cached : The number of non-cached queries (not cache-able, or not cached due to the query_cache_type setting).
  • Qcache_queries_in_cache : The number of queries registered in the query cache. Qcache_total_blocks: The total number of blocks in the query cache.

Qcache_free_blocks is an indication of fragmentation and if this is high in relation to the Qcache_total_blocks, it means that the cache space is wasted. The default block size for query cache is 4KB. If your query result is small and you see fragmentation, you should decrease the block size. You can use the system variable query_cache_min_res_unit to redefine the block size. And if the query result is large, you should increase the block size.
To defragment the query cache, you can use the command

mysql> FLUSH QUERY CACHE;
Query OK, 0 rows affected (0.07 sec)
mysql> show status like "%qcache%";
+-------------+-----+
| Variable_name | Value |
+-------------+-----+
| Qcache_free_blocks | 1 |
| Qcache_free_memory | 9090576 |
| Qcache_hits | 248169 |
| Qcache_inserts | 50147 |
| Qcache_lowmem_prunes | 15666 |
| Qcache_not_cached | 13316 |
| Qcache_queries_in_cache | 5273 |
| Qcache_total_blocks | 10979 |
+-------------+-----+
8 rows in set (0.00 sec)

Now the cache memory has been defragmented and you can see that the Qcache_free_blocks has reduced.There are situations when a query is not cached, such as returning current time, random number etc. Any queries making use of the following commands / types / functions will not be cached:

User-Defined Functions
BENCHMARK CONNECTION_ID CURDATE CURRENT_DATE  CURRENT_TIME CURRENT_TIMESTAMP CURTIME DATABASE
ENCRYPT (with one parameter) FOUND_ROWS GET_LOCK LAST_INSERT_ID LOAD_FILE MASTER_POS_WAIT NOW RAND
RELEASE_LOCK SYSDATE UNIX_TIMESTAMP (without parameters) USER 

query contains user variables
query references the mysql system database
Queries like these
    SELECT ... IN SHARE MODE
    SELECT ... INTO OUTFILE ...
    SELECT ... INTO DUMPFILE ...
    SELECT * FROM AUTOINCREMENT_FIELD IS NULL
queries inside transactions (in MySQL 4.0.x)

Some interesting facts about Query Caching:

Query caching is case sensitive:

Eg: mysql> show status like "%qcache%";
+-------------+-----+ |
Variable_name | Value |
+-------------+-----+
| Qcache_free_blocks | 1|
| Qcache_free_memory | 12574168 |
| Qcache_hits | 0 |
|Qcache_inserts | 0 |
| Qcache_lowmem_prunes | 0 |
| Qcache_not_cached |0 |
| Qcache_queries_in_cache | 0 |
| Qcache_total_blocks | 1 |
+-------------+-----+
8 rows in set (0.00 sec)
mysql>
select * from wp_post2cat where category_id=14;
+----+----+---+
+-----+-------+
15 rows in set (0.03 sec)
mysql>
select * from wp_post2cat where category_id=14;

+----+-----+-------+
+----+-----+-------+

15 rows in set (0.00 sec)
mysql> show status like "%qcache%";
+-------------+-----+
| Variable_name | Value |
+-------------+-----+
| Qcache_free_blocks | 1 |
| Qcache_free_memory | 12571408 |
| Qcache_hits | 1 |
| Qcache_inserts | 1 |
| Qcache_lowmem_prunes | 0 |
| Qcache_not_cached | 0 |
| Qcache_queries_in_cache | 1 |
| Qcache_total_blocks | 4 |
+-------------+-----+
8 rows in set (0.00 sec)

If you check the status variables,Before executing the query, the Qcache_inserts and Qcache_hits was 0. And the query took 0.03secs to execute for the first time.

When the query was executed for the second time, the Qcache_inserts and Qcache_hits was increased by 1 and took less time to execute.

Now I am executing the same query with a small difference:

mysql> SELECT * FROM wp_post2cat where category_id=14;
+----+-----+-------+
+----+-----+-------+
15 rows in set (0.02 sec)

mysql> show status like "%qcache%";
+-------------+-----+
| Variable_name | Value |
+-------------+-----+
| Qcache_free_blocks | 1 |
| Qcache_free_memory | 12569160 |
| Qcache_hits | 1 |
| Qcache_inserts | 2 |
| Qcache_lowmem_prunes | 0 |
| Qcache_not_cached | 0 |
| Qcache_queries_in_cache | 2 |
| Qcache_total_blocks | 6 |
+-------------+-----+
8 rows in set (0.00 sec)

Now you can see that the Qcache_inserts has increased and the query took 0.02 secs to execute. MySQL has inserted another query in the cache since it is considering this as a separate query. So if you are a programmer, make sure that you write all the query in a standard format so that your program utilizes query caching properly.

Query cache Clearing:

MySQL is clever enough to clear the query results whenever a change is made to the table. Any of INSERT, UPDATE, DELETE, TRUNCATE, ALTER, DROP TABLE or DROP DATABASE will remove queries from the cache. You can manually clear the query cache with RESET QUERY CACHE.

3.3. key_buffer_size:

key_buffer_size is the size of buffer used by all the indexes. Ideally, it should be large enough to contain all the indexes ie., total size of all the .MYI files in the server. A rule of thumb is to set to to at least a quarter of the memory available, half the memory to the maximum but not more than that.

When to increase your key_buffer_size:

The status variables you should be checking to find this are Key_read_requests, Key_reads, Key_write_requests and Key_writes.

Key_read_requests : The number of requests to read a key block from the cache.

Key_reads : The number of physical reads of a key block from disk.

Key_write_requests : The number of requests to write a key block to the cache.

Key_writes : The number of physical writes of a key block to disk.

The optimum solution is to keep the ratio Key_reads : Key_read_requests should be 1:100 and Key_writes / Key_write_requests should always be less than 1.

If the Key_reads value is high compared to Key_read_requests, it is high time you increase your key_buffer_size.

3.4. sort_buffer_size:

Improves large and complex sorts. Each thread that needs to do a sort allocates a buffer of this size. Increase this value for faster ORDER BY or GROUP BY operations. The default value for sort_buffer_size is 2MB. Please note this buffer is at a per client level.

When to increase sort_buffer_size:

Queries that sort rows, either by GROUP BY or ORDER BY undergo three processes.

1.Find the rows

2.sort the rows

3.read the sorted rows

MySQL first tries to sort the rows to the memory, the size of which is controlled by sort_buffer_size system variable. If the memory is not sufficient, it creates a temporary file to create the sorted rows, however the temporary file need to be sorted too after all the rows have been found from step 1. The re-sorting of the temporary file counts to the status variable Sort_merge_passes. MySQL actually creates a second temporary file into which it puts the sorted contents of the first file. Therefore, its common to see almost exactly twice as many created temporary files as Sort_merge_passes.

Sort_merge_passes can be reduced by increasing sort_buffer_size.

3.5. read_rnd_buffer_size:

read_rnd_buffer_size is used after a sort for reading the rows in the sorted order. If your application has a lot of queries with ORDER BY, increasing this can improve the performance. This is buffer is also at a per client basis. The default value for read_rnd_buffer_size is 128K. A general rule of thumb is to allocate 1MB for every 1GB memory.

3.6. tmp_table_size:

Sometimes for executing a statement, a temporary table needs to be created. This variable determines the maximum size for a temporary table in memory.

Always try to avoid temporary table creation by optimizing your query. But if it is unavoidable, make sure that the table is created in the memory. If the memory is not sufficient, a MyISAM table will be created in the disk.

When to increase tmp_table_size:

Check the processlist and see if any query is using temporary tables and is taking too long to resolve. In this case, you should increase the tmp_table_size.

You can also check the status variables Created_tmp_disk_tables and Created_tmp_tables.

Created_tmp_disk_tables : Number of temporary tables created on disk while executing a statement Created_tmp_tables : Number of in-memory tables created.

If a large number of tables are created in the disk, its high time you increase your tmp_table_size. Please note memory is allocated in per client basis (per thread basis).

3.7. thread_cache:

If your server is busy is making a lot of new connections ie., if you high max_connections, then the server will create a lot of new threads at a very high rate. This may eat up a lot of CPU time.

So the solution is to increase the thread_cache. When a client disconnects, the client’s threads are put in the cache if there aren’t more than thread_cache from before. All new threads are first taken from the cache, and only when the cache is empty is a new thread created. This variable can be increased to improve performance if you have a lot of new connections. (Normally this doesn’t give a notable performance improvement if you have a good thread implementation.) By examining the difference between the status variables Connections and Threads_created you can see how efficient the current thread cache is for you.â

If Threads_created is big, you may want to increase the thread_cache_size variable. The cache hit rate can be calculated with Threads_created/Connections.

4. Can I keep on increasing the size….?

The answer is NO!!. You should be aware of the resources available while tweaking the system variables. Here are some points you should take care of while optimizing your server.

4.1. DO NOT allocate too much memory.

Using less memory than available can reduce the performance, but using more memory than available can lead to worse performance or even crashes. A general resource allocation formula is

memory=key_buffer+(sort_buffer_size+read_buffer_size)*max_connections

4.2. Never let your box use the swap space actively.

Using swap space will affect the server performance badly.

4.3. Do not just scale the sample config file blindly.

If the my-huge.cnf (for 1GB memory) has some variable=1MB. And suppose you are having 16GB so you should set it to 16MB.. NO!! Set the variables wisely.

4.4. Consider per session variable.

Suppose you have set the sort_buffer_size for your server as 1MB and you have one query which requires more sort_buffer_size (say 16MB). Do NOT set sort_buffer_size=16M globally.

Use SET command to increase the sort_buffer_size

execute the command and

change it to 1MB using SET command.

5. All set….??.. NO!!

Mentioned above are only 7 of the 100+ system variables. There are several other variables which can be tweaked.

Tuning server parameters can increase the performance. But this doesn’t mean that MySQL optimization is only Server parameters’ optimization. No.. The database design and the SQL queries used also plays an equally important role. In fact, I would say Schema and Queries hold an upper hand. If the database is properly designed and the queries are properly created, tuning server parameters will make your server / site lightning speed..

Enjoy using MySQL….

Running Multiple MySQL versions

MySql No Comments »

Sometimes we may require to run multiple versions of MySQL on the same Server. This can happen if you either need to test a new MySQL release or you need a new MySQL version and you don’t want to make any changes to the existing system.

The whole idea behind this is to compile the new MySQL server with different TCP/IP ports and Unix socket files so that each one is listening on different network interfaces. Compiling in different base directories for each installation also results in separate compiled-in data directory, log file, and PID file location for each server.

First download the source the tar file from mysql.com.

$> tar xfz mysql.tar.gz
$> cd mysql.XX

* Important **
“/etc/my.cnf ” is the default file that is used by a mysql server. When the new version is tested it will load the default configuration’s in /etc/my.cnf.

To resolve this I replaced every instance of ” cnf ” inside the source folder to ” conf ” by using this following command.

find ./ -type f | xargs perl -pi -w -e 's/cnf/conf/g;'

1) The default user generally is “mysql”. Add another user and group for example mysqlt for the new version of MySQL.

2) A typical ./configure command…

./configure --prefix=/usr/local/mysql --enable-local-infile
--with-tcp-port=4444 --with-mysqld-user=mysqlt
--with-base_dir=/usr/local/mysql --with-log=/usr/local/mysql/mysqld.log
--with-pid_file=/usr/local/mysql/mysqld.pid
-with-unix-socket-path=/tmp/mysqlt.sock --localstatedir=/var/lib/mysqlt

The new values you will use for your new MySQL server are:

Port number : 4444

mysql user : mysqlt

base_dir :  /usr/local/mysql

data directory : /var/lib/mysqlt

log file : /usr/local/mysql/mysqld.log

3) Compile and Install

make && make install

4)Create your new MySQL config file.

cp support-files/my-medium.conf /etc/my.conf
cd /usr/local/mysql
bin/mysql_install_db --user=mysqlt
( this will install all the needed databases )
bin/mysqld_safe --user=mysqlt &

TO SET A PASSWORD FOR THE MySQL root USER

/usr/local/mysql/bin/mysqladmin -u root -h hostname password 'new-password'

/usr/local/mysql/bin/mysqladmin -u root password 'new-password'

5) To start the service

cd /usr/local/mysql

./share/mysql/mysql.server start

6) To test

#telnet localhost 4444

and you should see this
Trying 127.0.0.1...

Connected to localhost.

Escape character is '^]'.

+ 4.0.26-logIE^*THL

And you are done. You can copy mysql.server >> rc.d to start it when the server is rebooted.

With these steps, you can download and configure different mysql versions to use different values for port, datadirectory, mysql user, configuration file etc….

Warning: You should never have two servers that update data in the same databases.

How to set up Database replication in MySQL

MySql No Comments »

This article describes how to set up database replication in MySQL. MySQL replication allows you to have an exact copy of a database from a master server on another server (say we can call it as slave), and all updates to the database on the master server are immediately replicated to the database on the slave server so that both databases are in sync.

This is not a backup method or policy because an accidentally issued DELETE or ALTER command will also be carried out on the slave; but replication can help protect against hardware failures though.

2. Configure The Master:

We can configure the master server for replication using the mysql configuration file /etc/my.cnf. We have to enable networking for MySQL, and MySQL should listen on all IP addresses, therefore we will comment these lines (if already existing in my.cnf)

 #skip-networking
 #bind-address            = 127.0.0.1

Now we have to configure the MySQL server for which database it should write logs (these logs are used by the slave to see what has changed on the master) and we have to specify that this MySQL server is the master. We want to replicate the database db_test, so we put the following lines into /etc/my.cnf

log-bin
binlog-do-db=db_test
server-id=1

Then restart MySQL:

 # /etc/rc.d/init.d/mysql restart

Then we need to log into the MySQL database as root and create a user with replication privileges:

mysql> GRANT REPLICATION SLAVE ON *.* TO 'u1@%' IDENTIFIED BY 'p1';
mysql> FLUSH PRIVILEGES;

Next (still on the MySQL shell) do this:

mysql> USE db_test;
mysql> FLUSH TABLES WITH READ LOCK;
mysql> SHOW MASTER STATUS;

The sample master status will be as follows:

mysql> show master status;
+----------------+----------+--------------+------------------+
| File           | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+----------------+----------+--------------+------------------+
| rs2-bin.000063 |       79 | db_test      |                  |
+----------------+----------+--------------+------------------+
1 row in set (0.00 sec)

We need this information later on for the slave configuration Then leave the MySQL shell:

mysql> quit;

3.Configure The Slave:

We can configure the slave server for replication using the file /etc/my.cnf. We have to tell MySQL on the slave that it is the slave, that the master is H1, and that the master database to watch is db_test. Therefore we add the following lines to /etc/my.cnf

server-id=2
master-host=H1
master-user=u1
master-password=p1
master-connect-retry=100
replicate-do-db=db_test

The master-user and master-password are those to which we set when we granted REPLICATION SLAVE permission on the master. The server-id must be a unique number, different to the master or any other slaves in the system. The master-connect-retry is time in seconds for the slave to attempt to reconnect if the master goes down. 60 seconds is default.

Then restart MySQL:

# /etc/rc.d/init.d/mysql restart

4.Data Transfer:

There are two possibilities to get the existing tables and data from db_test from the master to the slave. The first one is to make a database dump, the second one is to use the LOAD DATA FROM MASTER; command on the slave.

(a)For Mysqldump method:

On master server, please take the dump of the database using

# mysqldump  db_test>db_test.sql
Then scp the file db_test.sql to slave server.
# Scp db_test.sql root@slave_serverip:/root
root@slaveip's password:

Restore the db_test.sql file at slave server

# mysqldump db_test < db_test.sql

(b)To LOAD DATA FROM MASTER:

Please perform the following at Master end:

# mysql -u root -p
Enter password:
mysql> UNLOCK TABLES;
mysql> quit;

Please perform the following at Slave end:

# mysql -u root -p
Enter password:
mysql> LOAD DATA FROM MASTER;
mysql> quit;

5. Replication in action:

Once the mysql master and slave configuration completed, we can check the replication action using the command ‘SHOW SLAVE STATUS’.

We can check if the slave is running correctly by looking at the Slave_IO_Running and Slave_SQL_Running. The most important field is the Last_Error field.

Mysql> SHOW SLAVE STATUSG

This will give the result as follows:
mysql> SHOW SLAVE STATUSG
*************************** 1. row ***************************
             Slave_IO_State: Waiting for master to send event
                Master_Host: H1
                Master_User: u1
                Master_Port: 3306
              Connect_Retry: 60
            Master_Log_File: rs2-bin.000063
        Read_Master_Log_Pos: 346
             Relay_Log_File: vrh-relay-bin.000001
              Relay_Log_Pos: 312
      Relay_Master_Log_File: rs2-bin.000063
           Slave_IO_Running: Yes
          Slave_SQL_Running: Yes
            Replicate_Do_DB: db_test
        Replicate_Ignore_DB:
         Replicate_Do_Table:
     Replicate_Ignore_Table:
    Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
                 Last_Errno: 0
                 Last_Error:
               Skip_Counter: 0
        Exec_Master_Log_Pos: 346
            Relay_Log_Space: 312
            Until_Condition: None
             Until_Log_File:
              Until_Log_Pos: 0
         Master_SSL_Allowed: No
         Master_SSL_CA_File:
         Master_SSL_CA_Path:
            Master_SSL_Cert:
          Master_SSL_Cipher:
             Master_SSL_Key:
      Seconds_Behind_Master: 0
1 row in set (0.00 sec)

If you need to force the slave to begin at a certain point, usually when the master has been running with an active binary log, you can do so as follows ( refer the master status value). The following starts with the 63rd binary log, as position 79.

mysql> CHANGE MASTER TO MASTER_HOST='H1',
MASTER_USER='u1',MASTER_PASSWORD='p1', MASTER_LOG_FILE='rs2-bin.000063', MASTER_LOG_POS=79;
MASTER_HOST is the IP address or hostname of the master (in this example it is H1).
MASTER_USER is the user we granted replication privileges on the master.
MASTER_PASSWORD is the password of MASTER_USER on the master.
MASTER_LOG_FILE is the file MySQL gave back when you ran SHOW MASTER STATUS; on the master.
MASTER_LOG_POS is the position MySQL gave back when you ran SHOW MASTER STATUS; on the master.

The SLAVE START and SLAVE STOP commands are used to manually stop and start the slave. The slave will also always stop if it comes across an error while replicating.

mysql> SLAVE STOP;
mysql> SLAVE START;

On active databases, the binary logs tend to grow quite quickly. We can use RESET MASTER to clear them. The RESET MASTER command tells the master to flush all its binary logs and start fresh. But while replication in action, we will have to execute the following.

mysql> PURGE MASTER LOGS TO 'rs2-bin.000063';

6. Options:

By default, the slave will replicate everything, but you can change this behavior with the following options in the slave configuration file (my.cnf).

replicate-do-db=db_name (replicate this database)
replicate-ignore-db=db_name (don't replicate this database)
replicate-do-table=db_name.table_name (replicate this table)
replicate-ignore-table=db_name.table_name (don't replicate this table)

7. Testing:

At master end if you are modifying the database db_test, it will reflect on slave server in real time using replication.

Example: On master slave if we are inserting the values as follows:-

mysql> use db_test
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-------------------+
| Tables_in_db_test |
+-------------------+
| staffactive       |
+-------------------+
1 row in set (0.00 sec)
mysql> desc staffactive;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(20) |      |     |         |       |
| date     | varchar(20) |      |     |         |       |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> INSERT INTO staffactive (username,date) VALUES ('savi','20070305');
Query OK, 1 row affected (0.02 sec)
mysql> INSERT INTO staffactive (username,date) VALUES ('testuser', 'testdate');
Query OK, 1 row affected (0.00 sec)
mysql> select * from staffactive;
+----------+----------+
| username | date     |
+----------+----------+
| savi     | 20070305 |
| testuser | testdate |
+----------+----------+
2 rows in set (0.00 sec)

mysql> q

Bye

This will reflect on the slave server in real time as follows:-

mysql> use db_test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select * from staffactive;
+----------+----------+
| username | date     |
+----------+----------+
| savi     | 20070305 |
| testuser | testdate |
+----------+----------+
2 rows in set (0.00 sec)

mysql> q

Bye

Increasing mysql packet size in my.cnf

MySql No Comments »

For increasing mysql packet size add the following entry in my.cnf and restart mysql server.

[mysqld]
max_allowed_packet=16M


How to check if innoDb engine enabled in Mysql

MySql No Comments »

Steps: Overview:

1. -Start MySql
(you will need version 3.23.29 or higher)

2. -Run the SQL query

SHOW VARIABLES LIKE ‘have_innodb’;

3. -This should show

+—————+——-+
| Variable_name | Value |
+—————+——-+
| have_innodb | YES |
+—————+——-+

MySQL collation in phpmyadmin

MySql No Comments »

Usually you will be interested in changing your MySQL collation in order to solve problems with foreign character encodings. The most common case is to change your MySQL collation from latin1 to utf8. This can be done by using phpMyAdmin and following the instructions below:

1. Enter your cPanel and click on the phpMyAdmin icon in the Databases box.

2. Select the database you wish to manage from the drop-down menu on the left

3. Click on the Operations tab in the top menu of your phpMyAdmin

4. At the bottom of the page you will see the collation option. You can now select a collation from the drop down menu and click on the Go button.

Please note that after your change the collation of a database only the new tables will be created with the new collation. All other tables remain with the collation, they were initially created.


MySql querry to delete a user

MySql No Comments »

mysql> delete from user where user=’username’;
mysql> FLUSH PRIVILEGES;

File where mysql root password is stored

MySql No Comments »

If you forgot your mysql root password you can get it from
/root/.my.cnf


allow access to a remote database

MySql No Comments »

grant all privileges on *.* to username@<server ip> identified by ’somepassword’;


Reset mysql root password

MySql No Comments »

Stop mysql server

/etc/init.d/mysql.server stop

Start mysql in safe mode

/usr/local/mysql/bin/mysqld_safe –user=root –skip-grant-tables –skip-networking &

NOw the mysql will be running in the background in safe mode. You will be able to klogin as root by just using

mysql -u root

Once you got in you can use the following commands to reset the root password.

UPDATE mysql.user SET Password=PASSWORD(’qwert123′) WHERE User=’root’; //Here password is qwert123

FLUSH PRIVILEGES;

Now just quit from the mysql prompt and try using the new password

mysql -u root -p

When it ask for passwprd, provide the new password. It will work.


Mysql Not Starting

MySql No Comments »

Sometimes such behavior of apache/httpd (taking more and more memory until it dies or crashes the server) can be caused by corrupted MySQL database. Try to do the following:

1) Kill the mysql server
/etc/rc.d/init.d/mysql stop

2) Repair all SQL databases:
myisamchk -r /var/lib/mysql/*/*.MYI

3) Start mysql again:
/etc/rc.d/init.d/mysql start


MySQL connection testing code

MySql No Comments »

Please put the following code in a php file in the server and access it through a browser to view the result.

Change the username of database user from “root” to your “database-user”, followed by the password of the database user from “testuser” to your “database-access-password”.

If the connection was successful the page will display Success. Other wise it will display Could not select DB.

Code:


<?php
$con=mysql_connect(”localhost”,”root”,”testuser”) or die(”Could not connect”);
$db=mysql_select_db(”test”,$con) or die(”Could not select DB”);
echo “Success”;
?>


How to reset mysql root password if lost– last resort

MySql No Comments »

If you have lost your mysql root password and you are unable to login to mysql, then as a last resort you can relogin by performing the following steps.

step1
——

You can stop the MySQL server by sending a normal kill (not kill -9) to the mysqld process, using the pathname of the .pid file in the following command:

Stop mysql service on the server. Do it in this way

shell> kill `cat /mysql-data-directory/host_name.pid` //note that ` is not single quotes it a back tab found in the top row of key
board (number row)

step2
——

Create a text file and place the following command within it on a single line:

SET PASSWORD FOR ‘root’@'localhost’ = PASSWORD(’123456′);

Save the file with any name. For this example the file will be mysql-init.

Step 3
——–

#

Restart the MySQL server with the special –init-file=~/mysql-init option:

shell> mysqld_safe –init-file=~/mysql-init &

The contents of the init-file are executed at server startup, changing the root password. After the server has started successfully you should delete ~/mysql-init.

Step 4
——–

You should be able to connect using the new password.

shell> mysql -u root -p

Then it will ask for password and give the password 123456

Login and reset the mysql password. Dont forget to delete the mysql-init file that we have created before restarting mysql.

Wordpress Themes by Natty WP. Web Hosting
Images by our golf tips desEXign.