====Creating and managing databases in MySQL====
First install the MySQL server.\\
$ sudo apt-get install mysql-server
Automatically it will request a root password. Now we can login mysqlserver, write in console:
$ mysql -uroot -p
And write your password. Now you can create and user, commands ends with semicolon:
> CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
This new user does not have any privileges, but we haven't create a database to give him privileges so lets create a database:
> CREATE DATABASE [database_name];
We can see which databases are available:
> SHOW DATABASES;
Now select the database, and give the 'user' privileges:
> USE [database_name];
> GRANT ALL PRIVILEGES ON 'database' TO 'user'@'localhost' WITH GRANT OPTION ;
Creating a basic table:
> CREATE TABLE [table_name]
> ( column_name_1 type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY] [COMMENT 'string'] [reference_definition] ,
> column_name_2 type [NOT NULL | NULL] ... ,
...
> column_name_n type [NOT NULL | NULL] ... ) ;
The types are describe [[http://dev.mysql.com/doc/refman/5.0/en/data-types.html|here]]. And you can describe a table with:
> DESCRIBE [table_name] ;
MySql has a function called ALTER TABLE, it changes the structure of a table. For example, you can add or delete columns, create or destroy indexes, change the type of existing columns, or rename columns or the table itself. How to use it [[http://dev.mysql.com/doc/refman/5.1/en/alter-table.html|here]]
Also you can use an existing table, save the table in .txt or .cvs format, and write:
> LOAD DATA INFILE [file_path] INTO TABLE [table_name];
Showing the table content:
> SELECT * FROM [table_name] ;
Delete a database:\\
> DROP DATABASE [database_name] ;
Delete any table:\\
> DROP TABLE [table_name] ;
Delete the records in a table:\\
>TRUNCATE TABLE [table_name] ;
Save a database in a file for this, in a console, in the directory you want to save the database:
$ mysqldump -u[user] -p [database_name] > [file_name].sql
Read a database from a file
> SOURCE [file_path]/[file_name].sql