MariaDB


MariaDB is an extended version of MySQL.

Installation

Install MariaDB on Ubuntu 18.04


sudo apt update
sudo apt install mysql-server # ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)
sudo apt install mariadb-server
sudo systemctl status mariadb
mysql -V
    

Securing MariaDB


sudo mysql_secure_installation
# answer Y to all questions 
mysql -u root -p [optional] # always start with this
# then input password set up in mysql secure installation
\h # help
\q # quit
    

Install MariaDB in Python


sudo apt install libmariadb3 libmariadb-dev # to avoid 'Please make sure, that MariaDB Connector/C is installed on your system.' warning
pip install mariadb
    

Terminal Commands


show databases; # list out databases
use mysql; # switch database ## MariaDB [(none)] becomes [database_name]
show tables; # 
SELECT User,Password FROM user;
create database demo; # one database can have multiple tables
use demo;

######### Normal SQL
CREATE TABLE Book(  
id INT NOT NULL AUTO_INCREMENT,  
name VARCHAR(100) NOT NULL,  
PRIMARY KEY (id)); 
## Show info of table
DESC Book;

## Insert
INSERT INTO Book
(id, name)  
VALUES  
(2,'MariaDB Book2'),  
(3,'MariaDB Book3'),  
(4,'MariaDB Book4'),  
(5,'MariaDB Book5');

## Select
SELECT * FROM Book;
    

Python Syntax


#### Setup
import mariadb
import sys
try:
    conn = mariadb.connect(
        user="root",
        password="pwd",
        host="localhost",
        port=3306,
        database="demo"
    )
except mariadb.Error as e:
    print(f"Error connecting to MariaDB Platform: {e}")
    sys.exit(1)
cur = conn.cursor()

#### SELECT
cur.execute(
    "SELECT * FROM Book")
for item in cur:
    print(item)

#### Show databases
cur.execute("SHOW DATABASES")
#print all databases
for db in cur:
    print(db)

#### Create table
cur.execute("CREATE TABLE student (id INT, name VARCHAR(255))")

#### Insert
sql = "INSERT INTO student(id,name) VALUES(01, 'John')"
cur.execute(sql)
conn.commit()
print(cur.rowcount, "Record Inserted")

#### Close connection
conn.close()
    

References


  1. How to Install MariaDB on Ubuntu 18.04
  2. MariaDB Connector/C
  3. MariaDB Connector/Python
  4. Github -- datacharmer / test_db
  5. Connect to MariaDB
  6. How to connect Python programs to MariaDB
  7. MariaDB Tutorial for Beginners: Learn with EXAMPLES
  8. Python with MySQL: Connect, Create Database, Table, Insert [Examples]
  9. Expose MySQL and MariaDB Database Server to the Internet