Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

MySQL Table Synchronization

MySQL Table Synchronization
=======================

Step: 1 Download the below package and sample script for table sysnchronization.

# cd /opt
# wget  https://static.spiceworks.com/images/how_to_steps/0000/3025/mysql-table-sync-0.9.3.tar.gz
# wget https://static.spiceworks.com/images/how_to_steps/0000/3026/syncTables.sh

Step: 2 Extract above package

# tar xzvf mysql-table-sync-0.9.3.tar.gz
# cd mysql-table-sync-0.9.3

Step: 3 Install perl-mysql modules

# yum install perl-ExtUtils-MakeMaker
# yum install "perl(DBD::mysql)"

Step: 4 Compile and install mysql-table-sync

# perl Makefile.PL
# make install



Step: 4 Then open syncTables.sh read configuration on top of the script. Change the configuration

SQL: Give grants to all tables in a schema

Use this procedure and just execute it as normal SQL query

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='Schema_name 1') LOOP
      EXECUTE IMMEDIATE 'grant select,insert,update,delete on '||R.owner||'.'||R.table_name||' to <>';
   END LOOP;
END;

Schema Name 1 : This is like to which schema you needed grants.
Schema name 2: This like which schema needed those grants.

For example: SchemaA should have access on all tables,view of Schema B, then
Schename Name 1 would be Schema B and Schema Name 2 would be Schema A.

Thanks
Raja

Bash Shell Scripting - Basics

Working with text

1. Read a CSV file line by line and extract specific filed, and store it in a variable.
file_name="data.csv"
while read line
do
field1=$(echo -e $line | gawk -F, '{ print $1}')
field2=$(echo -e $line | gawk -F, '{ print $2}')
done < $file_name

2. Find and repace a string in a file.
sed -i 's/foo/bar/g' file.txt

Arithematic Operations
1. Increment a variable
count=$((count+1))

2. Decrement a variable
count=$((count-1))

Working with date and time
1. Get current date in yy-mm-dd format.
current_date="`date +%y-%m-%d`"
echo $current_date

2. Get backup time stamp in yymmdd-hhmmss format and store it in a variable.
bkptime=("`date +%y%m%d-%H%M%S`")

3. Get yesterday's date in yyyy-mm-dd format.
yesterday_date="`date --date=yesterday +%Y/%m/%d`"
echo $yesterday_date

3. Get 10 days old date in yyyy-mm-dd format.
day=("`date --date=\"10 day ago\" +%Y-%m-%d`")

OR

daysold=10
day=("`date --date=\"$daysold day ago\" +%Y-%m-%d`")

4. Get last day of the month
To get last day of current month:
date -d "-$(date +%d) days 1 month" +%Y-%m-%d

To get last day of last month:
date -d "-$(date +%d) days 0 month" +%Y-%m-%d

To get last day of last before month
date -d "-$(date +%d) days -1 month" +%Y-%m-%d

To get last day of next month
date -d "-$(date +%d) days 2 month" +%Y-%m-%d

To get last day of next to next month
date -d "-$(date +%d) days 3 month" +%Y-%m-%d

If conditions

1. Check a vriable is having some value (it is non-zero)
if [ ! -z "$var" ]; then
     echo "Variable value is $val"
else
     echo "Variable has no value"
fi

2. Check if file exist
if [  -e "$file.csv" ]; then
     echo "File exist"
fi

3. Check if doesn't file exist
if [ !  -e "$file.csv" ]; then
     echo "File exist"
fi

4. Check if previously executed command is successful or not. If not successful exit from loop.
ssconvert "file.xls" "file.csv"
if [ "$?" == "0" ]; then
      echo "File converted successfully.."
else
exit
fi

Working with files

1. Covert EXCEL(.xls) file to CSV file.
ssconvert "file.xls" "file.csv"

2. Compress a directory using 7zip.
/usr/bin/7z a reportdir.7z reportdir > /dev/null

3. Upload a directory and its content to an FTP location
ftp_server="ftp.mydomain.com"
ftp_bkp_username="myusername"
ftp_bkp_password="mypassword"
FTP Over TLS
lftp -c "open -e \"set ftps:initial-prot \"\"; set ftp:ssl-force true; set ftp:ssl-protect-data true; mirror -R mydir; \" -u \"$ftp_bkp_username\",\"$ftp_bkp_password\" ftp://$ftp_server/mypath/"
FTP (without TLS)
ncftpput –R -u $ftp_bkp_username -p $ftp_bkp_password $ftp_server mypath mydir

4. Upload a file to an FTP location.
ftp_server="ftp.mydomain.com"
ftp_bkp_username="myusername"
ftp_bkp_password="mypassword"
FTP Over TLS
lftp -c "open -e \"set ftps:initial-prot \"\"; set ftp:ssl-force true; set ftp:ssl-protect-data true; put myfile; \" -u \"$ftp_bkp_username\",\"$ftp_bkp_password\" ftp://$ftp_server/mypath/"
FTP (without TLS)
ncftpput -u $ftp_bkp_username -p $ftp_bkp_password $ftp_server mypath myfile

5. Create an empty directory in an FTP location over TLS.
ftp_server="ftp.mydomain.com"
ftp_bkp_username="myusername"
ftp_bkp_password="mypassword"
lftp -c "open -e \"set ftps:initial-prot \"\"; set ftp:ssl-force true; set ftp:ssl-protect-data true; put myemptydir; \" -u \"$ftp_bkp_username\",\"$ftp_bkp_password\" ftp://$ftp_server/mypath/"


Working with user input
1. Read input from user.
echo -n "Enter date for processing data (yyyy/mm/dd) : "
read given_date
echo "You have entered $given_date"

Working with MySQL statements
1. Change a MySQL environment variable.
 db.cnf
[client]
user = root
password = mypassword
host = localhost

mysql --defaults-extra-file=db.cnf  -e "set global general_log='ON';"

2. Get the pids of sleeping MySQL connections and kill them whose sleep time is more than 100 sec.
sleeptime=100
/usr/bin/mysql -N -h $host -p$password -u $username -e "select id from information_schema.processlist where command='Sleep' and time > $sleeptime;" > kill_ids
while read id
do
/usr/bin/mysqladmin -h $host -p$password -u $username kill $id
done < kill_ids
rm -f kill_ids

3. Various options used while taking MySQL DB backup
/usr/bin/mysqldump -h $host --no-data  --routines -p$password -u $username $database > $database-Schema_only.sql
/usr/bin/mysqldump -h $host -p$password -u $username $database  --no-create-db --no-create-info --ignore-table=$database.cdrdetails --ignore-table=$database.clientsummary > $database-without_CDR_Data_tables.sql
--no-data Ã  Do not write any table row information i.e structure only
--routines Ã  Dump stored routines (procedures and functions)
--no-create-db Ã  Do not write CREATE DATABASE statements
--ignore-table=db_name.tbl_name Ã  Do not dump given table
--skip-add-drop-table Ã  Do not add a DROP TABLE statement before each CREATE TABLE statement

Sending Mail
1. Send mail with body text stored in a file.
message.txt
Hi
  Some text here
Thanks & Regards
xxxxxxxxxxxxx

mail -s "Log Rotation Failed" abc@xyz.com < message.txt

2. Send mail with attachment.
mail -a Report.txt -s "Log Rotation Failed" abc@xyz.com < message.txt

3. Send a mail with Cc
mail -a Report.txt -s "Log Rotation Failed" -c id@domain.com abc@xyz.com < message.txt

Working across multiple scripts
  1. There will be situations, where multiple scripts dependent on same data. Such data can be stored in one script, and can be exported to multiple scripts. This will help us in managing the data centrally that changes time to time.
00_CONFIG.sh
#!/bin/bash
host="192.168.10.23"
export host

database=mydbname
export database

port=3306
export port

serverids="1 2 3 4 5 6 7 8 9 10"
export serverids

recenthours="3 2 1"
export recenthours

mysql_username="myuserid"
export mysql_username

mysql_password="mypassword"
export mysql_password

01_DAILY DATA_VERIFY.sh
#!/bin/bash
source 00_CONFIG.sh

for id in `echo $serverids`
do
..................
..................
done

02_DAILY DATA_BACKUP.sh
#!/bin/bash
source 00_CONFIG.sh

for id in `echo $serverids`
do
..................
..................
done

03_DAILY DATA_DELETE.sh
#!/bin/bash
source 00_CONFIG.sh

for id in `echo $serverids`
do
..................
..................
done

Important Note: The above example will work when you run scripts manually in shell. In case if you want to schedule the jobs using crontab, you need to declare those variables (CONFIG.sh) in cron environment. In this case it looks like this.
# crontab -e 
host="192.168.10.23"
database=mydbname
port=3306
serverids="1 2 3 4 5 6 7 8 9 10"
recenthours="3 2 1"
mysql_username="myuserid"
mysql_password="mypassword"
30    5     *    *     *    /mypath_to_scripts/01_DAILY DATA_VERIFY.sh
59    23     *    *     *    /mypath_to_scripts/01_DAILY DATA_BACKUP.sh

Rename Database in MySQL

Today I am writing about how to rename MySQL Database.

So If you want to rename a database in MySQL dont forget taking backup of your Views,Procedures and Functions of current database. Because while you renaming changes wont apply for Views,Procedures and functions.

After you have taken the backup , We can go for renaming with the command below.

RENAME TABLE old_db.table TO new_db.table;
Here old_db is your old database name and new_db is your new database name. You have to execute this command for each table. And this is the way.

But what if we have a big database with 1000 tables ? executing the same above command for 1000 times is a stupid idea.

If you are using Linux you can use following BASH script to do that for you

for table in $(mysql -p -s -N -e "show tables from db1"); do mysql -s -N -e "rename table db1.$table to db2.$table"; done;

db1 is your old database name and db2 is your new database name and remaining everything will tool care by script only except giving password.:P

After executing the command successfully without any errors , you must have to restore that backup of Views,Proc's and Functions.

Errors: I have got one error with triggering. Generally some tables have triggers. So you copy the code of triggers and then delete those triggers. Then try to rename the table again.

After it got successful , just recreate the triggers for the same tables in new database.

I have done this trigger creation in MYSQL Workbench.

If you want to backup only Functions and not data of database then you can use this command
mysqldump --routines --no-create-info --no-data --no-create-db --skip-opt  <database> > outputfile.sql
Here : 

--routines                 =       for including routines ( views,functions,procedures)
--no-create-info       =       Do not write CREATE TABLE statements that re-create each dumped
                              table.
--no-data                  =        Do not write any row information for the table. This is very useful
                        if you want to get a dump of only the structure for a table.
 --no-create-db         =        This option suppresses the CREATE DATABASE /*!32312 IF NOT EXISTS*/
                        db_name statements that are otherwise included in the output if the
--databases or --all-databases option is given.
--skip-out        = --opt
                    This option is shorthand; it is the same as specifying
--add-drop-table --add-locks --create-options --disable-keys
--extended-insert --lock-tables --quick --set-charset. It should
give you a fast dump operation and produce a dump file that can be
reloaded into a MySQL server quickly. As of MySQL 4.1, --opt is on
by default, but can be disabled with --skip-opt. To disable only
certain of the options enabled by --opt, use their --skip forms; for
example, --skip-add-drop-table or --skip-quick.




Basic MySQL Administration

1. How to create a user and along with his privileges automatically ?

GRANT ALL PRIVILEGES ON database.* To 'username'@'hosr or IP ' IDENTIFIED BY 'password';
flush privileges;

2. How to give only specific privileges to users ?

GRANT select,lock tables ON *.* To 'user'@'host or IP ' IDENTIFIED BY 'password';
flush privileges;

3. How to see permissions of a user ?

show grants for 'username'@'hostanme';

4. How to revoke all given privileges ?

revoke all privileges on *.* from 'user'@'host';

5. How to take backup of database ?

mysqldump --user <username> --password=<password> databasename > databasebackup.sql

6. How to take backup of two databases ?

mysqldump --user <username> --password=<password> databasename1 databasename2 > databasebackup.sql

7. How to take backup of all databases in MySQL ?

mysqldump --user <username> --password=<password> -all-databases > alldbbackup.sql

8. How to take backup of table in database ?

mysqldump --user <username> --password=<password> database_name database_table \  >  databasebackup.sql 

9. How to restore one database ?

mysql --user <username> --password=<password> databasename < databasebackup.sql
mysql_upgrade -p -u root --force

PHPMyAdmin in your CentOS 6.X


Open your terminal and EPEL Repo

 wget http://epel.mirror.net.in/epel/6/i386/epel-release-6-8.noarch.rpm 
rpm -Uvh epel-release-6-8.noarch.rpm

Then Add Remi


rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm

Now open /etc/httpd/conf.d/phpMyAdmin.conf file and enter the address field with address from where you want access PhPMyAdmin remotely cause it is accessed by default from localhost only.


vim /etc/httpd/conf.d/phpMyAdmin.conf

Next restart your httpd with


service httpd restart
Open your browser and type there as localhost/phpmyadmin and login with your mysql username and password. If you want browse remotely then your IP must allowed( added ) from above mentioned configuration file. Note: This information has taken from several sources.

Running Multiple Instances of MySQL in CentOS/Fedora/RedHat Linux



              Running Multiple Instances of MySQL in CentOS/Fedora/RedHat Linux


                       1. Make sure that you have installed mysql-server in your Linux , If not install it with

yum install –y mysql-server

              2.  After installing MySQL-Server , Open your terminal and paste as 
  
                        mkdir /var/lib/mysql2
chown -R mysql.mysql /var/lib/mysql2
mkdir /var/log/mysql2         
chown -R mysql.mysql /var/log/mysql2

Above code stands for creating two directories for MySQL 2nd instance , There /var/lib/mysql2  for data directory and /var/log/mysql2 is for log directory. After that changing the owner as mysql for both.

              3. Make a dump of mycnf configuration file with 
 
 cp -R /etc/my.cnf /etc/my2.cnf

                    Then Open it with
nano /etc/my2.cnf  (or ) vim /etc/my2.cnf

                     Make the changes as mentioned in the below file.

                                     # change/add the following options
                                    port = 3307     #different port
                                    datadir = /var/lib/mysql2       #diff data dir
                                    socket =  /var/lib/mysql2/mysql2.sock           # diff socket path
                                    # add [mysql_safe]
                                    log-error = /var/log/mysql2/mysql.log # diff log
                                    pid-file = /var/lib/mysql2/mysql2.pid            #diff PI


 Then save & close it.

                            4.  Now in the terminal paste these lines after one , with success of each command

mysql_install_db --user=mysql --datadir=/var/lib/mysql2/
mysqld_safe --defaults-file=/etc/my2.cnf &
mysqladmin -S  /var/lib/mysql2/mysql2.sock -u root password 'newpass'
mysql -S  /var/lib/mysql2/mysql2.sock -u root -p

5                 5. That will start your MySQL 2ndinstance and you can check it with 

netstat -nptelu | grep my
netstat -l | grep my

6                6. If you want to shutdown that instance then you can do it with

mysqladmin -S  /var/lib/mysql2/mysql2.sock -u root -p shutdown