Install MySQL in Ubuntu and perform simple operations
Installing MySQL on Ubuntu is very simple and requires only a few commands.
1. sudo apt-get install mysql-server
2. apt-get isntall mysql-client
3. sudo apt-get install libmysqlclient-dev
During the installation process, you will be prompted to set the password or something. Do not forget to set the password. After the installation is complete, run the following command to check whether the installation is successful:
Sudo netstat-tap | grep mysql
After the preceding command check, if mysql's socket is in the listen status, the installation is successful.
To log on to the mysql database, run the following command:
Mysql-u root-p
-U indicates the login user name and-p indicates the Login User Password. After the above command is entered, a prompt is displayed for entering the password. Then, you can log on to mysql by entering the password.
Then, you can view the current database through show databases.
Select mysql database to perform the next step. use the use mysql command to display the current database form: show tables.
Write a simple program to access the database and implement the show tables function:
# Include <mysql/mysql. h>
# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
MYSQL * conn;
MYSQL_RES * res;
MYSQL_ROW row;
Char server [] = "localhost ";
Char user [] = "root ";
Char password [] = "mima ";
Char database [] = "mysql ";
Conn = mysql_init (NULL );
If (! Mysql_real_connect (conn, server, user, password, database, 0, NULL, 0 ))
{
Fprintf (stderr, "% s \ n", mysql_error (conn ));
Exit (1 );
}
If (mysql_query (conn, "show tables "))
{
Fprintf (stderr, "% s \ n", mysql_error (conn ));
Exit (1 );
}
Res = mysql_use_result (conn );
Printf ("MySQL Tables in mysql database: \ n ");
While (row = mysql_fetch_row (res ))! = NULL)
{
Printf ("% s \ n", row [0]);
}
Mysql_free_result (res );
Mysql_close (conn );
Printf ("finish! \ N ");
Return 0;
}
To compile the code, you need to link the mysql database. You can compile the Code as follows:
G ++-Wall mysql_test.cpp-o mysql_test-lmsqlclient
Then run the compiled code:
The visible result is the same as the SQL statement show tables.
Make it simple, make it happen