Ubuntu and Database
Ubuntu and Database
Ubuntu Server 12.04 comes with MySQL, Apache, and PHP through the application LAMP (Linux Apache MySQL PHP). It
is during the installation of Ubuntu when you will also be asked to install LAMP. It is also then when you will have to set
up the username and password for MySQL. The username for the administrator is usually root, the password of course
depends on what you assigned.
1. Access MySQL by simply typing: mysql u root p <your password>
2. Upon entering, create a database. Assign it with a user and password. See example below for your guide:
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
mysql> GRANT ALL ON *.* TO jim@localhost IDENTIFIED BY secretpass;
Query OK, 0 rows affected (0.01 sec)
mysql> \q
Bye
$ mysql -u jim -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
mysql> CREATE DATABASE sample;
Query OK, 1 row affected (0.01 sec)
mysql> \q
3. You have now created your new database. Rather than type a lot of table creation and population
commands directly into the mysql command line, which is somewhat prone to error and not very
productive if you ever need to type it again, you will create a file with the commands you need in it.
This file is create_children.sql:
4. Now sign back in to mysql so we can execute the file that we created.
$ mysql -u rick --password=secret foo
Welcome to the MySQL monitor. Commands end with ; or \g.
mysql> \. create_children.sql
Query OK, 0 rows affected (0.01 sec)
5. Exit mysql and create C program with the filename Connect1.c. The following should be the content of your
code:
#include <stdlib.h>
#include <stdio.h>
#include mysql.h
int main(int argc, char *argv[]) {
MYSQL *conn_ptr;
conn_ptr = mysql_init(NULL);
if (!conn_ptr) {
fprintf(stderr, mysql_init failed\n);
return EXIT_FAILURE;
}
conn_ptr = mysql_real_connect(conn_ptr, localhost, username, password, databasename, 0,
NULL, 0);
if (conn_ptr) {
printf(Connection success\n);
} else {
printf(Connection failed\n);
}
mysql_close(conn_ptr);
return EXIT_SUCCESS;
}
6. Compile your program with the following line:
$ gcc -I/usr/include/mysql connect1.c -L/usr/lib/mysql -lmysqlclient -o connect1
7. Run your program and it should be able to connect with the database successfully.
8. Now create another program insert1.c
#include <stdlib.h>
#include <stdio.h>
#include mysql.h
int main(int argc, char *argv[]) {
MYSQL my_connection;
int res;
mysql_init(&my_connection);