Lab 6-1: MySQL Server 1. Objective The participants of the course will be able to: Install and configure a MySQL server. Define a c-program, which enables to access (write and read) to the database of the MySQL server. Define a java-program, which enables to access the database of the MySQL server through the Internet. 2. Install and configure the MySQL server Ref.: http://zetcode.com/db/mysqlvb 2.1 Installation of the MySQL server If you don't already have MySQL installed, we must install it. $ sudo apt-get install mysql-server This command installs the MySQL server and various other packages. While installing the package, we are prompted to enter a password for the MySQL root account. 2.2 Installation of the MySQL C-API The MySQL C-API is a C-based API that client applications written in C can use to communicate with MySQL Server. The MySQL C-API can be installed as follow: $ sudo apt-get install libmysql++-dev 2.3 Creating a new MySQL database Now we are going to create a new database with the command shell. $ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 30 Server version: 5.5.52-0+deb8u1 (Raspbian) Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> SHOW DATABASES; Ver. 1.0 TI Biel, 01/11/2016 Page 1/7
+--------------------+ Database +--------------------+ information_schema mysql +--------------------+ 2 rows in set (0.00 sec) We use the mysql monitor client application to connect to the server. We connect to the database using the root account. We show all available databases with the SHOW DATABASES statement. mysql> CREATE DATABASE testdb; Query OK, 1 row affected (0.02 sec) We create a new testdb database. We will use this database throughout the tutorial. We must grant all the privileges to root, also when he tries to access to the databases from an external computer. Attention: in this example you must type your own mysql root password as ˈroot_passwordˈ. mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root_password' with grant option; Query OK, 0 rows affected (0.00 sec) To quit MySQL, use this command: mysql> quit; Bye 2.4 Configuration of the MySQL server The MySQL server listens on a single network socket for TCP/IP connections. This socket is bound to a single address, but it is possible for an address to map onto multiple network interfaces. The default address is 127.0.0.1. To specify an address explicitly, use the bindaddress=addr option at server startup, where addr is an IPv4 address or a host name. Configuration of the bind-address option If the bind-address must be set to 0.0.0.0, so that the server accepts TCP/IP connections on all server host IPv4 interfaces. This can be realized by setting the value of the bind-address in the configuration file /etc/mysql/my.cnf: bind-address = 0.0.0.0 Make also sure you comment out the following line: # skip-external-locking Ver. 1.0 TI Biel, 01/11/2016 Page 2/7
3. Access to the MySQL database with a C-Program Ref.: http://zetcode.com/db/mysqlc 3.1 Create and fill a MySQL table The next code example will create a table and insert some data into it. #include <my_global.h> #include <mysql.h> /* in order to avoid unnecessary repetition, we create a custom finish with error function */ void finish_with_error(mysql *con) { fprintf(stderr, "%s\n", mysql_error(con)); int main(int argc, char *argv[]) { /* allocates a MYSQL object suitable for the function mysql_real_connect() */ MYSQL *con = mysql_init(null); if (con == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); /* connect to the testdb database: user name is ˈrootˈ, password ˈrootˈ and database ˈtestdbˈ */ if (mysql_real_connect(con, "localhost", "root", "root", "testdb", 0, NULL, 0) == NULL) { if (mysql_query(con, "DROP TABLE IF EXISTS Cars")) { /* create a table named Cars, which has three columns */ if (mysql_query(con, "CREATE TABLE Cars(Id INT, Name TEXT, Price INT)")) { /* insert the first row into the Cars table */ if (mysql_query(con, "INSERT INTO Cars VALUES(1,'Audi',52642)")) { /* insert the second row into the Cars table */ if (mysql_query(con, "INSERT INTO Cars VALUES(2,'Mercedes',57127)")) { Ver. 1.0 TI Biel, 01/11/2016 Page 3/7
/* insert the third row into the Cars table */ if (mysql_query(con, "INSERT INTO Cars VALUES(3,'Skoda',9000)")) { exit(0); We can compile this c-programm as follow: gcc createdb.c -o createdb -std=c99 `mysql_config --cflags --libs` When you have executed this programm, you can test its contributions to the database testdb with the mysql monitor client application: $ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 30 Server version: 5.5.52-0+deb8u1 (Raspbian) Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> USE testdb; mysql> SHOW TABLES; +------------------+ Tables_in_testdb +------------------+ Cars +------------------+ 1 row in set (0.00 sec) mysql> SELECT * FROM Cars; +------+------------+--------+ Id Name Price +------+------------+--------+ 1 Audi 52642 2 Mercedes 57127 3 Skoda 9000 +------+------------+--------+ 3 rows in set (0.00 sec) mysql> quit; Bye 3.2 Read from a MySQL table In the next example, we will retrieve data from a table with a C-Program. We need to do the following steps: Ver. 1.0 TI Biel, 01/11/2016 Page 4/7
Create a connection Execute query Get the result set Fetch all available rows Free the result set #include <my_global.h> #include <mysql.h> void finish_with_error(mysql *con) { fprintf(stderr, "%s\n", mysql_error(con)); int main(int argc, char *argv[]) { MYSQL *con = mysql_init(null); if (con == NULL) { fprintf(stderr, "mysql_init() failed\n"); if (mysql_real_connect(con, "localhost", "root", "root", "testdb", 0, NULL, 0) == NULL) { // prints all columns from the Cars table if (mysql_query(con, "SELECT * FROM Cars")) { // retrieve all data from the Cars table MYSQL_RES *result = mysql_store_result(con); if (result == NULL) { // get the number of fields (columns) in the table int num_fields = mysql_num_fields(result); // fetch the rows and print them to the screen MYSQL_ROW row; while ((row = mysql_fetch_row(result))) { for(int i = 0; i < num_fields; i++) { printf("%s ", row[i]? row[i] : "NULL"); printf("\n"); Ver. 1.0 TI Biel, 01/11/2016 Page 5/7
mysql_free_result(result); exit(0); 4. Access to the MySQL database with a Java-Program In the next example, we will retrieve data from a table with a Java-Program. import java.sql.*; public class ReadDataBase { public static void main(string[] args) { try { // create our mysql database connection String mydriver = "com.mysql.jdbc.driver"; Class.forName(myDriver); // IP address of the server String ipaddress = "192.168.1.42"; String dbname = "testdb"; String dbusername = "root"; String dbpassword = "root"; String connectionstring = "jdbc:mysql://" + ipaddress + "/" + dbname + "?user=" + dbusername + "&password=" + dbpassword + "&useunicode=true&characterencoding=utf-8"; Connection con = null; con = DriverManager.getConnection(connectionString); // our SQL SELECT query String query = "SELECT * FROM Cars"; Statement st = con.createstatement(); ResultSet rs = st.executequery(query); System.out.println("iterate through the java resultset"); while (rs.next()) { int id = rs.getint("id"); String name = rs.getstring("name"); int price = rs.getint("price"); // print the results System.out.format("%d, %s, %d\n", id, name, price); st.close(); Ver. 1.0 TI Biel, 01/11/2016 Page 6/7
catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); Before you compile this Java program, you must download the following jar file into your working directory: mysql-connector-java-5.1.22-bin.jar Then you can compile and start your Java program within a Linux console as follow: javac -classpath mysql-connector-java-5.1.22-bin.jar ReadDataBase.java java -classpath mysql-connector-java-5.1.22-bin.jar:. ReadDataBase Ver. 1.0 TI Biel, 01/11/2016 Page 7/7