Monday, September 8, 2014

MYSQL BASICS

MYSQL BASICS


About MySQL

MySQL is an open source database management software that helps users store, organize, and retrieve data. It is a very powerful  program with a lot of flexibility—this tutorial will provide the simplest introduction to MySQL

How to Install MySQL on Ubuntu and CentOS

If you don't have MySQL installed on your droplet, you can quickly download it.

Ubuntu:

sudo apt-get install mysql-server

Centos:

sudo yum install mysql-server
/etc/init.d/mysqld start

How to Access the MySQL shell

Once you have MySQL installed on your droplet, you can access the MySQL shell by typing the following command into terminal:

mysql -u root -p

After entering the root MySQL password into the prompt (not to be confused with the root droplet password), you will be able to start building your MySQL database.

Two points to keep in mind:

All MySQL commands end with a semicolon; if the phrase does not end with a semicolon, the command will not execute.Also, although it is not required, MySQL commands are usually written in uppercase and databases, tables, usernames, or text are in lowercase to make them easier to distinguish. However, the MySQL command line is not case sensitive.

How to Create and Delete a MySQL Database

MySQL organizes its information into databases; each one can hold tables with specific data.

You can quickly check what databases are available by typing:

SHOW DATABASES;

Your screen should look something like this:

 mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.01 sec)

Creating a database is very easy:


 CREATE DATABASE database name;
In this case, for example, we will call our database "events."

 mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| events             |
| mysql              |
| performance_schema |
| test               |
+--------------------+
5 rows in set (0.00 sec)
In MySQL, the phrase most often used to delete objects is Drop. You would delete a MySQL database with this command:

 DROP DATABASE database name;

How to Access a MySQL Database

Once we have a new database, we can begin to fill it with information.

The first step is to create a new table within the larger database.

Let’s open up the database we want to use:

 USE events;

In the same way that you could check the available databases, you can also see an overview of the tables that the database contains.

 SHOW tables;

Since this is a new database, MySQL has nothing to show, and you will get a message that says, “Empty set”

How to Create a MySQL Table

Let’s imagine that we are planning a get together of friends. We can use MySQL to track the details of the event.

Let’s create a new MySQL table:


CREATE TABLE potluck (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20),food VARCHAR(30),confirmed CHAR(1),signup_date DATE);

This command accomplishes a number of things:


It has created a table called potluck within the directory, events.
We have set up 5 columns in the table—id, name, food, confirmed, and signup date.
The “id” column has a command (INT NOT NULL PRIMARY KEY AUTO_INCREMENT) that automatically numbers each row.
The “name” column has been limited by the VARCHAR command to be under 20 characters long.
The “food” column designates the food each person will bring. The VARCHAR limits text to be under 30 characters.
The “confirmed” column records whether the person has RSVP’d with one letter, Y or N.
The “date” column will show when they signed up for the event. MySQL requires that dates be written as yyyy-mm-dd

Let’s take a look at how the table appears within the database using the "SHOW TABLES;" command:


 mysql> SHOW TABLES;
+------------------+
| Tables_in_events |
+------------------+
| potluck          |
+------------------+
1 row in set (0.01 sec)

We can remind ourselves about the table’s organization with this command:

 DESCRIBE potluck;

Keep in mind throughout that, although the MySQL command line does not pay attention to cases, the table and database names are case sensitive: potluck is not the same as POTLUCK or Potluck.

 mysql>DESCRIBE potluck;
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| id          | int(11)     | NO   | PRI | NULL    | auto_increment |
| name        | varchar(20) | YES  |     | NULL    |                |
| food        | varchar(30) | YES  |     | NULL    |                |
| confirmed   | char(1)     | YES  |     | NULL    |                |
| signup_date | date        | YES  |     | NULL    |                |
+-------------+-------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)

How to Add Information to a MySQL Table

We have a working table for our party. Now it’s time to start filling in the details.

Use this format to insert information into each row:


INSERT INTO `potluck` (`id`,`name`,`food`,`confirmed`,`signup_date`) VALUES (NULL, "John", "Casserole","Y", '2012-04-11');

Once you input that in, you will see the words:

 Query OK, 1 row affected (0.00 sec)

Let’s add a couple more people to our group:

INSERT INTO `potluck` (`id`,`name`,`food`,`confirmed`,`signup_date`) VALUES (NULL, "Sandy", "Key Lime Tarts","N", '2012-04-14');
INSERT INTO `potluck` (`id`,`name`,`food`,`confirmed`,`signup_date`) VALUES (NULL, "Tom", "BBQ","Y", '2012-04-18');
INSERT INTO `potluck` (`id`,`name`,`food`,`confirmed`,`signup_date`) VALUES (NULL, "Tina", "Salad","Y", '2012-04-10');

We can take a look at our table:

mysql> SELECT * FROM potluck;
+----+-------+----------------+-----------+-------------+
| id | name  | food           | confirmed | signup_date |
+----+-------+----------------+-----------+-------------+
|  1 | John  | Casserole      | Y         | 2012-04-11  |
|  2 | Sandy | Key Lime Tarts | N         | 2012-04-14  |
|  3 | Tom   | BBQ            | Y         | 2012-04-18  |
|  4 | Tina  | Salad          | Y         | 2012-04-10  |
+----+-------+----------------+-----------+-------------+
4 rows in set (0.00 sec)

How to Update Information in the Table

Now that we have started our potluck list, we can address any possible changes. For example: Sandy has confirmed that she is attending, so we are going to update that in the table.

UPDATE `potluck`
SET
`confirmed` = 'Y'
WHERE `potluck`.`name` ='Sandy';
You can also use this command to add information into specific cells, even if they are empty.

How to Add and Delete a Column

We are creating a handy chart, but it is missing some important information: our attendees’ emails.

We can easily add this:

 ALTER TABLE potluck ADD email VARCHAR(40);
This command puts the new column called "email" at the end of the table by default, and the VARCHAR command limits it to 40 characters.

However, if you need to place that column in a specific spot in the table, we can add one more phrase to the command.


 ALTER TABLE potluck ADD email VARCHAR(40) AFTER name;
Now the new “email” column goes after the column “name”.

Just as you can add a column, you can delete one as well:

ALTER TABLE potluck DROP email;
I guess we will never know how to reach the picnickers.

How to Delete a Row

If needed, you can also delete rows from the table with the following command:

DELETE from [table name] where [column name]=[field text];
For example, if Sandy suddenly realized that she will not be able to participate in the potluck after all, we could quickly eliminate her details.

mysql> DELETE from potluck  where name='Sandy';
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM potluck;
+----+------+-----------+-----------+-------------+
| id | name | food      | confirmed | signup_date |
+----+------+-----------+-----------+-------------+
|  1 | John | Casserole | Y         | 2012-04-11  |
|  3 | Tom  | BBQ       | Y         | 2012-04-18  |
|  4 | Tina | Salad     | Y         | 2012-04-10  |
+----+------+-----------+-----------+-------------+
3 rows in set (0.00 sec)
Notice that the id numbers associated with each person remain the same.


How to create a new user and provide the access permissions?

user@server:~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 40
Server version: 5.1.41-3

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create user  'user'@'localhost' identified by 'pass' ;
Query OK, 0 rows affected (0.00 sec)

mysql> grant create on *.* to 'user'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye

user@server:~$ mysql -u user -ppass
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 42
Server version: 5.1.41-3ubuntu12.10 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> DROP USER ‘user’@‘localhost’;

---------------------------------------------------------------------------------------------------------------
---next Method of creating a new user and granting the permissions?

mysql> craete user 'test'@'localhost' identified by 'test'
    -> grant create on *.* to 'test'@'localhost'
    -> flush privileges
    -> quit
    -> ^CCtrl-C -- exit!
Aborted
Query OK, 1 row affected (0.00 sec)

If we want to revoke the permissions we can use the following command:

---------------------------------------------------------------------------------------------------------------
REVOKE [type of permission] ON [database name].[table name] FROM ‘[username]’@‘localhost’;
----------------------------------------------------------------------------------------------------------------

How to Import and Export Databases

Export

To Export a database, open up terminal, making sure that you are not logged into MySQL and type,

mysqldump -u [username] -p [database name] > [database name].sql
The database that you selected in the command will now be exported to your droplet.

Import

To import a database, first create a new blank database in the MySQL shell to serve as a destination for your data.

CREATE DATABASE newdatabase;
Then log out of the MySQL shell and type the following on the command line:

mysql -u [username] -p newdatabase < [database name].sql
With that, your chosen database has been imported into your destination database in MySQL.

How to Reset a Root Password

When you first install MySQL, you have to set up your root password. However, should you forget it at any point, you can still recover it.

1. Shut Down MySQL

In terminal, stop the MySQL process

/etc/init.d/mysql stop

2. Access MySQL Safe Mode

In safe mode, you will be able to make changes within the MySQL system with a root password alone, without the need for MySQL root password.

sudo mysqld_safe --skip-grant-tables &

Once safe mode has started up, log into MySQL and when prompted, use your standard root password.

mysql -u root mysql

3. Set Up a New Password

Finally, set up the new MySQL root password by typing the command below. Replace "newpassword" with the password of your choice.

update user set password=PASSWORD("newpassword") where User='root';
Be sure to reload everything:

 FLUSH PRIVILEGES;

and you now have a new root password.

mysql> quit
Bye


----------------------------------------------------------------------------------------------------------------

About MySQL replication

MySQL replication is a process that allows you to easily maintain multiple copies of a MySQL data by having them copied automatically from a master to a slave database.This can helpful for many reasons including facilating a backup for the data,a way to analyze it without using the main database, or simply as a means to scale out.

This tutorial will use the following IP addresses:

12.34.56.789- Master Database

12.23.34.456- Slave Database

Setup

This article assumes that you have user with sudo privileges and have MySQL installed.
If you do not have mysql, you can install it with this command:

sudo apt-get install mysql-server mysql-client

1. Configure the Master Database

Open up the mysql configuration file on the master server.

sudo nano /etc/mysql/my.cnf

Once inside that file, we need to make a few changes.

The first step is to find the section that looks like this, binding the server to the local host:

bind-address            = 127.0.0.1
Replace the standard IP address with the IP address of server.

bind-address            = 12.34.56.789
The next configuration change refers to the server-id, located in the [mysqld] section. You can choose any number for this spot (it may just be easier to start with 1), but the number must be unique and cannot match any other server-id in your replication group. I’m going to go ahead and call this one 1.

Make sure this line is uncommented.

server-id               = 1

Move on to the log_bin line. This is where the real details of the replication are kept. The slave is going to copy all of the changes that are registered in the log. For this step we simply need to uncomment the line that refers to log_bin:

log_bin                 = /var/log/mysql/mysql-bin.log

Finally, we need to designate the database that will be replicated on the slave server. You can include more than one database by repeating this line for all of the databases you will need.

binlog_do_db            = newdatabase

After you make all of the changes, go ahead and save and exit out of the configuration file.

Refresh MySQL.

sudo service mysql restart

The next steps will take place in the MySQL shell, itself.Open up the MySQL shell.

mysql -u root -p

We need to grant privileges to the slave. You can use this line to name your slave and set up their password.

The command should be in this format:

GRANT REPLICATION SLAVE ON *.* TO 'slave_user'@'%' IDENTIFIED BY 'password';

Follow up with:

FLUSH PRIVILEGES;

The next part is a bit finicky. To accomplish the task you will need to open a new window or tab in addition to the one that you are already using a few steps down the line.

In your current tab switch to “newdatabase”.

USE newdatabase;

Following that, lock the database to prevent any new changes:

FLUSH TABLES WITH READ LOCK;

Then type in:

SHOW MASTER STATUS;

You will see a table that should look something like this:

mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      107 | newdatabase  |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

This is the position from which the slave database will start replicating. Record these numbers, they will come  in useful later.If you make any new changes in the same window, the database will automatically unlock. For this reason, you should open the new tab or window and continue with the next steps there.Proceeding the with the database still locked, export your database using mysqldump in the new window (make sure you are typing this command in the bash shell, not in MySQL).

mysqldump -u root -p --opt newdatabase > newdatabase.sql

Now, returning to your your original window, unlock the databases (making them writeable again). Finish up by exiting the shell.

UNLOCK TABLES;
QUIT;
Now you are all done with the configuration of the the master database.

2. Configure the Slave Database

Once you have configured the master database. You can put it aside for a while, and we will now begin to configure the slave database.Log into your slave server, open up the MySQL shell and create the new database that you will be replicating from the master (then exit):

CREATE DATABASE newdatabase;
EXIT;

Import the database that you previously exported from the master database.

mysql -u root -p newdatabase < /path/to/newdatabase.sql

Now we need to configure the slave configuration in the same way as we did the master:

sudo nano /etc/mysql/my.cnf

We have to make sure that we have a few things set up in this configuration. The first is the server-id. This number, as mentioned before needs to be unique. Since it is set on the default (still 1), be sure to change it’s something different.

server-id               = 2

Following that, make sure that your have the following three criteria appropriately filled out:

relay-log               = /var/log/mysql/mysql-relay-bin.log
log_bin                 = /var/log/mysql/mysql-bin.log
binlog_do_db            = newdatabase

You will need to add in the relay-log line: it is not there by default. Once you have made all of the necessary changes, save and exit out of the slave configuration file.

Restart MySQL once again:

sudo service mysql restart

The next step is to enable the replication from within the MySQL shell.Open up the the MySQL shell once again and type in the following details, replacing the values to match your information:

CHANGE MASTER TO MASTER_HOST='12.34.56.789',MASTER_USER='slave_user', MASTER_PASSWORD='password',MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=  107;

This command accomplishes several things at the same time:

It designates the current server as the slave of our master server.It provides the server the correct login credentialsLast of all, it lets the slave server know where to start replicating from; the master log file and log position come from the numbers we wrote down previously.With that—you have configured a master and slave server.Activate the slave server:

START SLAVE;

You be able to see the details of the slave replication by typing in this command. The \G rearranges the text to make it more readable.

SHOW SLAVE STATUS\G
If there is an issue in connecting, you can try starting slave with a command to skip over it:

SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1; SLAVE START;
All done.

----------------------------------------------------------------------------------------------------------------

No comments:

Easy Way to Handle Android Notifications

Android Notifications Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persist...