Category: mysql

  • Khóa học miễn phí MySQL – Table Locking nhận dự án làm có lương

    MySQL – Table Locking

    Table of content


    MySQL database provides a multi-user environment, that allows multiple clients to access the database at the same time. To run this environment smoothly, MySQL introduced the concept of locks.

    A client in a session can lock a certain table they are working on, in order to prevent other clients from using the same table. This process will avoid any data losses that might occur when multiple users work on the same table simultaneously.

    A client can lock a table and unlock it whenever needed. However, if a table is already locked by a client session, it cannot be accessed by other client sessions until it is released.

    Locking Tables in MySQL

    You can restrict the access to records of the tables in MYSQL by locking them. These locks are used to keep other sessions away from modifying the tables in the current session.

    MySQL sessions can acquire or release locks on the table only for itself. To lock a table using the MySQL LOCK TABLES Statement you need have the TABLE LOCK and SELECT privileges.

    These locks are used to solve the concurrency problems. There are two kinds of MYSQL table locks −

    • READ LOCK − If you apply this lock on a table the write operations on it are restricted. i.e., only the sessions that holds the lock can write into this table.

    • WRITE LOCK − This lock allows restricts the sessions (that does not possess the lock) from performing the read and write operations on a table.

    Syntax

    Following is the syntax of the MySQL LOCK TABLES Statement −

    LOCK TABLES table_name [READ | WRITE];
    

    Unlocking Tables in MySQL

    Once the client session is done using/accessing a MySQL table, they must unlock the table for other client sessions to use it. To do so, you can use the MySQL UNLOCK TABLE statement. This will release the table until other sessions lock it again.

    Syntax

    Following is the syntax of the MySQL UNLOCK TABLES Statement −

    UNLOCK TABLES;
    

    Example

    Let us start with creating a table named CUSTOMERS that contains the details as shown below −

    CREATE TABLE CUSTOMERS (
       ID INT AUTO_INCREMENT,
       NAME VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Now, let”s insert 2 records into the above created table using the INSERT statement as −

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES
      (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
      (2, ''Khilan'', 25, ''Delhi'', 1500.00 );
    

    Create another table named BUYERS using the following query −

    CREATE TABLE BUYERS (
       B_ID INT AUTO_INCREMENT,
       B_NAME VARCHAR(20) NOT NULL,
       B_AGE INT NOT NULL,
       B_ADDRESS CHAR (25),
       B_SALARY DECIMAL (18, 2),
       PRIMARY KEY (B_ID)
    );
    

    Following queries inserts records into the BUYERS table using the INSERT INTO SELECT statement. Here, we are trying to insert records from the CUSTOMERS table to BUYERS table.

    Locking and Unlocking:

    Here before the transfer, we are acquiring the write lock on the BUYERS table to which we are inserting records and acquiring read lock on the CUSTOMERS table from which we are inserting records. Finally, after the transfer we are releasing the records.

    LOCK TABLES CUSTOMERS READ, BUYERS WRITE;
    
    INSERT INTO BUYERS (B_ID, B_NAME, B_AGE, B_ADDRESS, B_SALARY)
       SELECT
          ID, NAME, AGE, ADDRESS, SALARY
       FROM
          CUSTOMERS
       WHERE
          ID = 1 AND NAME = ''Ramesh
    INSERT INTO BUYERS (B_ID, B_NAME, B_AGE, B_ADDRESS, B_SALARY)
       SELECT
          ID, NAME, AGE, ADDRESS, SALARY
       FROM
          CUSTOMERS
       WHERE
          ID = 2 AND NAME = ''Khilan
    
    UNLOCK TABLES;
    

    Verification

    We can verify the contents of the BUYERS table using the below query −

    SELECT * FROM BUYERS;
    

    As we can see in the BUYERS table, the records has been transferred.

    B_ID B_NAME B_AGE B_ADDRESS B_SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00

    Table Locking Using a Client Program

    Besides locking a table in a MySQL database with a MySQL query, we can also use a client program to perform the LOCK TABLES operation.

    Syntax

    Following are the syntaxes to Lock a table in MySQL in various programming languages −

    To lock the table in MySQL database through a PHP program, we need to execute the Lock Tables statement using the mysqli function query() as −

    $sql="LOCK TABLES table_name [READ | WRITE]";
    $mysqli->query($sql);
    

    To lock the table in MySQL database through a Node.js program, we need to execute the Lock statement using the query() function of the mysql2 library as −

    sql = "LOCK TABLES table_name [READ | WRITE]";
    con.query(sql);
    

    To lock the table in MySQL database through a Java program, we need to execute the Lock statement using the JDBC function executeUpdate() as −

    String sql="LOCK TABLES table_name [READ | WRITE]";
    statement.executeUpdate(sql);
    

    To lock the table in MySQL database through a Python program, we need to execute the Lock statement using the execute() function of the MySQL Connector/Python as −

    sql="LOCK TABLES table_name [READ | WRITE]";
    cursorObj.execute(sql);
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $dbname = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } // printf(''Connected successfully.
    ''); // Here we are locking two table; $sql = "LOCK TABLES tut_tbl READ, clone_table WRITE"; if ($mysqli->query($sql)) { printf("Table locked successfully!.
    "); } if ($mysqli->errno) { printf("Table could not be locked!.
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table locked successfully!.
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "Nr5a0204@123"
    });
    
      //Connecting to MySQL
      con.connect(function (err) {
      if (err) throw err;
      console.log("Connected!");
      console.log("--------------------------");
    
      sql = "USE TUTORIALS"
      con.query(sql);
    
      sql = "CREATE TABLE SalesDetails (ID INT, ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255), CustomerAge INT, CustomrtPhone BIGINT, DispatchAddress VARCHAR(255), Email VARCHAR(50));"
      con.query(sql);
    
      sql = "insert into SalesDetails values(1, ''Key-Board'', ''Raja'', DATE(''2019-09-01''), TIME(''11:00:00''), 7000, ''Hyderabad'', 25, ''9000012345'', ''Hyderabad - Madhapur'', ''pujasharma@gmail.com'');"
      con.query(sql);
      sql = "insert into SalesDetails values(2, ''Mobile'', ''Vanaja'', DATE(''2019-03-01''), TIME(''10:10:52''), 9000, ''Chennai'', 30, ''90000123654'', ''Chennai- TNagar'', ''vanajarani@gmail.com'');"
      con.query(sql);
    
      sql = "CREATE TABLE CustContactDetails (ID INT,Name VARCHAR(255), Age INT,Phone BIGINT, Address VARCHAR(255), Email VARCHAR(50));"
      con.query(sql);
    
      sql = "LOCK TABLES SalesDetails READ, CustContactDetails WRITE;"
      con.query(sql);
    
      sql = "INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email) SELECT ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email FROM SalesDetails  WHERE  ID = 1 AND CustomerName = ''Raja"
      con.query(sql);
    
      sql = "INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email) SELECT ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email FROM  SalesDetails WHERE ID = 2 AND CustomerName = ''Vanaja"
      con.query(sql);
    
      sql = "UNLOCK TABLES;"
      con.query(sql);
    
      sql = "SELECT * FROM CustContactDetails;"
      con.query(sql, function(err, result){
        if (err) throw err
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    [
      {
        ID: 1,
        Name: ''Raja'',
        Age: 25,
        Phone: 9000012345,
        Address: ''Hyderabad - Madhapur'',
        Email: ''pujasharma@gmail.com''
      },
      {
        ID: 2,
        Name: ''Vanaja'',
        Age: 30,
        Phone: 90000123654,
        Address: ''Chennai- TNagar'',
        Email: ''vanajarani@gmail.com''
      }
    ]
    
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class TableLock {
        public static void main(String[] args) {
            String url = "jdbc:mysql://localhost:3306/TUTORIALS";
            String username = "root";
            String password = "password";
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                Connection connection = DriverManager.getConnection(url, username, password);
                Statement statement = connection.createStatement();
                System.out.println("Connected successfully...!");
    
                //Lock table....
                String sql = "LOCK TABLES tutorials_tbl READ, clone_tbl WRITE";
                statement.executeUpdate(sql);
                System.out.println("Table Locked successfully...!");
    
                connection.close();
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    Table Locked successfully...!
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    table_name = ''tutorials_tbl''
    #Creating a cursor object
    cursorObj = connection.cursor()
    lock_table_query = f"LOCK TABLES {table_name} WRITE"
    cursorObj.execute(lock_table_query)
    print(f"Table ''{table_name}'' is locked successfully.")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Table ''tutorials_tbl'' is locked successfully.
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Create Database nhận dự án làm có lương

    MySQL – Create Database

    Table of content


    After establishing connection with MySQL, to manipulate data in it you need to connect to a database. You can connect to an existing database or, create your own.

    You would need special privileges to create or to delete a MySQL database. So, if you have access to the root user, you can create any database using the MySQL CREATE DATABASE statement.

    MySQL CREATE Database Statement

    The CREATE DATABASE statement is a DDL (Data Definition Language) statement used to create a new database in MySQL RDBMS.

    If you are creating your database on Linux or Unix, then database names are case-sensitive, even though keywords SQL are case-insensitive. If you are working on Windows then this restriction does not apply.

    Syntax

    Following is the syntax to create a database in MySQL

    CREATE DATABASE DatabaseName;
    

    Where, the “DatabaseName” is just a placeholder representing the name of the database that we want to create.

    Example

    Let us create a database TUTORIALS in MySQl using the CREATE DATABASE statement as follows −

    CREATE DATABASE TUTORIALS;
    

    Make sure you have the necessary privilege before creating any database.

    Verification

    Once the database TUTORIALS is created, we can check it in the list of databases using the SHOW statement as shown below −

    SHOW DATABASES;
    

    Following are the list of databases present in the server −

    Database
    information_schema
    mysql
    performance_schema
    tutorials

    CREATE Database with IF NOT EXISTS clause

    If you try to create a database with an existing name an error will be generated. Suppose there is an existing database in MySQL with the name mydb and if we try to create another database with the same name as −

    CREATE DATABASE myDatabase
    

    An error will be generated as shown below −

    ERROR 1007 (HY000): Can''t create database ''mydb database exists
    

    If you use the IF NOT EXISTS clause along with the CREATE statement as shown below a new database will be created and if a database with the given name, already exists the query will be ignored.

    CREATE DATABASE IF NOT EXISTS myDatabase
    

    Create Database Using mysqladmin

    You would need special privileges to create or to delete a MySQL database. So assuming you have access to the root user, you can create any database using the mysql mysqladmin binary.

    Example

    Here is a simple example to create a database named TUTORIALS using mysqladmin −

    [root@host]# mysqladmin -u root -p create TUTORIALS
    Enter password:******
    

    This will create a MySQL database called TUTORIALS.

    Creating Database Using a Client Program

    Besides creating a database in MySQL RDBMS with a MySQL query, you can also use a client program in programming languages such as Node.js, PHP, Java, and Python to achieve the same result.

    Syntax

    Following are the syntaxes of this operation in various programming languages −

    To create a database in MySQL RDBMS through a PHP program, we need to execute the ”CREATE DATABASE” statement using the mysqli function named query() as shown below −

    $sql = "CREATE DATABASE DatabaseName";
    $mysqli->query($sql);
    

    To create a database in MySQL RDBMS through a Node.js program, we need to execute the ”CREATE DATABASE” statement using the query() function of the mysql2 library as follows −

    sql = "CREATE DATABASE DatabaseName";
    con.query(sql, function (err, result) {
       if (err) throw err;
          console.log(result);
    });
    

    To create a database in MySQL RDBMS through a Java program, we need to execute the ”CREATE DATABASE” statement using the JDBC function executeUpdate() as follows −

    String sql = "CREATE DATABASE DatabaseName";
    st.executeUpdate(sql);
    

    To create a database in MySQL RDBMS through a Python program, we need to execute the ”CREATE DATABASE” statement using the execute() function of the MySQL Connector/Python as follows −

    sql = "CREATE DATABASE DatabaseName"
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''root@123
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass);
    
    if($mysqli->connect_errno ) {
       printf("Connect failed: %s<br />", $mysqli->connect_error);
       exit();
    }
    printf(''Connected successfully.<br />'');
    
    if ($mysqli->query("CREATE DATABASE TUTORIALS")) {
       printf("Database created successfully.<br />");
    }
    if ($mysqli->errno) {
       printf("Could not create database: %s<br />", $mysqli->error);
    }
    $mysqli->close();
    

    Output

    The output obtained is as follows −

    Connected successfully.
    Database created successfully.
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
       host: "localhost",
       user: "root",
       password: "Nr5a0204@123"
    });
      //Connecting to MySQL
      con.connect(function (err){
      if (err) throw err;
      console.log("Connected!");
      console.log("--------------------------");
      //Creating a Database
      sql = "create database TUTORIALS"
      con.query(sql, function(err){
       if (err) throw err
         console.log("Database created successfully...")
       });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    Database created successfully...
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class createDatabase {
        public static void main(String[] args) {
    		String url = "jdbc:mysql://localhost:3306/";
            String user = "root";
            String password = "password";
            ResultSet rs;
            try {
            	Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st = con.createStatement();
                //System.out.println("Connected successfully...!");
                String sql = "CREATE DATABASE TUTORIALS";
                st.execute(sql);
                System.out.println("Database created successfully...!");
            }catch(Exception e) {
            	e.printStackTrace();
            }
    	}
    }
    

    Output

    The output obtained is as shown below −

    Database created successfully...!
    
    import mysql.connector
    # creating the connection object
    connection = mysql.connector.connect(
    host ="localhost",
    user ="root",
    password ="password"
    )
    # creating cursor object
    cursorObj = connection.cursor()
    # creating the database
    cursorObj.execute("CREATE DATABASE MySqlPythonDB")
    print("Database Created Successfully")
    # disconnecting from server
    connection.close()
    

    Output

    Following is the output of the above code −

    Database Created Successfully
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Select Database nhận dự án làm có lương

    MySQL – Select Database (USE Statement)

    Table of content


    Once you get connected with the MySQL server, it is required to select a database to work with. This is because there might be more than one database available with the MySQL Server.

    MySQL USE Statement

    To select a database in MySQL, we use the SQL USE statement. Once a specific database is selected, we can perform different operations such as creating tables, adding data, updating, and deleting information. Every operation we perform after selecting a database will be stored in that particular database.

    Syntax

    Following is the syntax of the USE statement in SQL −

    USE DatabaseName;
    

    Here, the “DatabaseName” is a placeholder representing the name of the database that we want to use.

    The database name must always be unique within the MySQL or any other RDBMS.

    Example

    Let us start by creating a database named TUTORIALS using the following CREATE query −

    create database TUTORIALS;
    

    Now, we will fetch all the databases present in MySQL server using the below query −

    Show databases;
    

    Following are the list of databases −

    Field
    information_schema
    mysql
    performance_schema
    tutorials

    The following will select/switch the current database to TUTORIALS

    USE TUTORIALS;
    

    Output

    The database has been selected/switched successfully without any error.

    Database changed
    

    Once we finish switching to the database TUTORIALS, we can perform operations such as creating a table, and inserting data in that table as shown below −

    CREATE TABLE CUSTOMERS (
       ID INT AUTO_INCREMENT,
       NAME VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Once the table is created, execute the following query to retrieve the data present in the current database (TUTORIALS) −

    SHOW TABLES;
    

    As we can see in the output below, the CUSTOMERS table we have created after selecting the TUTORIALS database is stored in it.

    Tables_in_tutorials
    customers

    Selecting a Non Existing MySQL Database

    If we try to select/switch a non-existent database in a MySQL server, it will result in an error stating that “Unkwown Database”.

    Example

    Here, we are trying to select/swith to the database which doesn”t exist −

    USE NonExistingDatabase;
    

    The output for the above query is produced as given below −

    ERROR 1049 (42000): Unknown database ''nonexistingdatabase''
    

    Selecting Database Using a Client Program

    Besides selecting/switching a database in a MySQL server using a MySQL query, we can also use a client program to perform the USE operation.

    Syntax

    Following are the syntaxes of this operation in various programming languages −

    To select/switch a database in a MySQL server through PHP program, we need to execute the USE statement using the mysqli function query() as follows −

    $sql = "USE Database_name";
    $mysqli->query($sql);
    

    To select/switch a database in a MySQL server through Node.js program, we need to execute the USE statement using the query() function of the mysql2 library as follows −

    sql = "USE Database_name";
    con.query(sql);
    

    To select/switch a database in a MySQL server through Java program, we need to execute the USE statement using the JDBC function executeUpdate() as follows −

    String sql = "USE Database_name";
    st.execute(sql);
    

    To select/switch a database in a MySQL server through Python program, we need to execute the USE statement using the execute() function of the MySQL Connector/Python as follows −

    sql = "USE Database_name";
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''root@123
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass);
    
    if($mysqli->connect_errno ) {
       printf("Connect failed: %s<br />", $mysqli->connect_error);
       exit();
    }
    printf(''Connected successfully.<br />'');
    
    if ($mysqli->query("USE TUTORIALS")) {
       printf("Database selected successfully...!<br />");
    }
    if ($mysqli->errno) {
       printf("Database could not connect: %s<br />", $mysqli->error);
    }
    $mysqli->close();
    

    Output

    The output obtained is as follows −

    Connected successfully.
    Database selected successfully...!
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "Nr5a0204@123"
    });
    
      //Connecting to MySQL
      con.connect(function (err) {
      if (err) throw err;
      console.log("Connected!");
      console.log("--------------------------");
    
      //Selecting a Database
      sql = "Use TUTORIALS;"
      con.query(sql, function(err, result){
        if (err) throw err
        console.log("Database selected successfully...")
      });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    Database selected successfully...!
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class SelectDatabase {
    	public static void main(String[] args) {
    		String url = "jdbc:mysql://localhost:3306/";
    		String user = "root";
    		String password = "password";
    		System.out.println("Connecting to select database.....!");
    		try {
    			Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st1 = con.createStatement();
                String sql = "USE TUTORIALS";
                st1.execute(sql);
                System.out.println("Database selected successfully...!");
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Output

    The output obtained is as shown below −

    Connecting to select database.....!
    Database selected successfully...!
    
    import mysql.connector
    # creating the connection object
    connection = mysql.connector.connect(
    host ="localhost",
    user ="root",
    password ="password")
    # creating cursor object
    cursorObj = connection.cursor()
    # selecting the database
    cursorObj.execute("USE TUTORIALS")
    # Fetching a single row
    print("Database selected Successfully...!")
    # disconnecting from server
    connection.close()
    

    Output

    Following is the output of the above code −

    Database selected Successfully...!
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Workbench nhận dự án làm có lương

    MySQL – Workbench

    Table of content


    The MySQL workbench is a graphical tool for working with MySQL servers and databases. It is developed and maintained by Oracle. This application includes various features such as data modelling, data migration, SQL development, server administration, database backup, database recovery and many more. MySQL Workbench supports the MySQL versions 5.7 and above.

    The versions of MySQL prior to version 5.7 are deprecated and they are incompatible with MySQL workbench. Therefore, we need to ensure that they should be upgraded before we make a connection.

    MySQL Workbench is a recommended application for database developers and administrators. We can download this application on Windows, macOS, and Linux operating systems.

    Functionalities of MySQL Workbench

    Following are the five main functionalities of MySQL workbench −

    • SQL Development − This functionality allows to create and manage connections to database servers. SQL queries can be executed on the database connections using the built-in SQL editor in MySQL workbench.

    • Data Modelling (Design) − This functionality allows to create models of our database schema graphically, reverse and forward engineer between a schema and a live database, and edits all aspects of the database using the comprehensive table. The table editor provides facilities to edit Tables, Columns, Indexes, Triggers, Partitioning, Options, Inserts, Privileges, Routines and Views.

    • Server Administration − It allows us to administer the MySQL sever instances by administering users, viewing database health, performing backup and recovery, inspecting audit data, and monitoring the MySQL server performance.

    • Data Migration − It allows us to migrate from the Microsoft SQL server, Microsoft Access, Sybase ASE, SQLite, SQL Anywhere PostreSQL, and other RDBMS tables, objects and data to MySQL. Migration also allows us to migrate from prior versions of MySQL to the latest releases.

    • MySQL Enterprise support − This functionality provides the support for Enterprise products such as MySQL Enterprise backup, MySQL Firewall and MySQL Audit.

    MySQL Workbench Editions

    The MySQL Workbench is offered in three editions. The same is described below −

    • MySQL Workbench Community Edition – Open Source (GPL License)

    • MySQL Workbench Standard Edition – Commercial

    • MySQL Workbench Enterprise Edition – Commercial

    Community Edition

    This is an open-source and freely downloadable version of the database system. It comes under the GPL (General public license) and it is supported by a large community of developers.

    Standard Edition

    This is the commercial edition that gives the capability to deliver high-performance and scalable OLT (online transaction processing) applications.

    Enterprise Edition

    The Enterprise edition includes a set of advanced features, management tools, and technical support to achieve the highest scalability, security, uptime and reliability. This edition will reduce the risk, cost, complexity in the development, deployment, and managing MySQL applications.

    Comparison Chart

    The following is the comparison chart of the above discussed functionalities −

    Functionality Community Edition Standard Edition Enterprise Edition
    Visual SQL Development Yes Yes Yes
    Visual Database Administration Yes Yes Yes
    Performance Tuning Yes Yes Yes
    User and Session Management Yes Yes Yes
    Connection Management Yes Yes Yes
    Object Management Yes Yes Yes
    Data Management Yes Yes Yes
    Visual Data Modelling Yes Yes Yes
    Reverse Engineering Yes Yes Yes
    Forward Engineering Yes Yes Yes
    Schema Synchronization Yes Yes Yes
    Schema & Model Validation No Yes Yes
    DBDoc No Yes Yes
    GUI for MySQL Enterprise Backup No Yes Yes
    GUI for MySQL Enterprise Audit No Yes Yes
    GUI for MySQL Enterprise Firewall No Yes Yes
    Scripting & Plugins No Yes Yes
    Database Migration No Yes Yes

    MySQL Workbench Administration Tool

    The administration tool in MySQL workbench plays a vital role in securing the data. Following are some administration tools provided by MySQL workbench −

    User Administration

    This tool allows to create, modify and delete the user related accounts. Using this we can manage the user”s privileges and permissions.

    Server Configuration

    It allows us to configure the server paramerters. It shows various details about the sever and status variable, number of threads, buffer allocation size, fine-tuning for optimal performance, etc.

    Database Backup and Restorations

    This tools is used for importing and exporting the MySQL dump files. These dump files contains the SQL script for table creation, view creation, stored procedure creation etc.

    Server Logs

    This tool shows log information for the MySQL server by each connection tab. For every tab connection, it includes an additional tab for the general error logs.

    Performance Dashboard

    This tab provides real-time statistical view and analysis of server performance such as CPU usage, memory usage, query execution time, etc.

    Create Database in MySQL Workbench

    We can create a database in MySQL Workbench, without explicitly using SQL statements. Following steps show how to create a database in MySQl Workbench −

    Step 1 − Open the MySQL workbench application and log in using the username and password.

    Step 2 − Now, to create a database, right click on schemas menu and select the create schema option. Another way to create a schema is by clicking on the schema button which is highlighted with a red outline in the following picture.

    mysql

    Step 3 − After selecting the create schema option, a new schema window will be opened as shown in the following figure. We can now enter the database name (say testdb) and use the default collation. Then click on the apply button.

    mysql

    Step 4 − A new window will be opened after clicking the apply button. Now click on the Apply button and then click on Finish button.

    Step 5 − Now, we can see the above-created testdb database in the schema menu. If it is not visible, click on the refresh button on top-right corner in schemas menu.

    mysql

    Note − If we want to see more information about the testdb database, click on the testdb database and then click on the i icon. The information window displays various options such as Table, Column, Indexes, Triggers and many more.

    Drop Database in MySQL Workbench

    Similarly, we can also drop a database using workbench. Following are the steps to drop a database using MySQL workbench −

    Step 1 − To drop a database in MySQL workbench, right click on the particular database that we want to delete and click on drop schema option as shown in the following figure.

    Here, we are trying to delete the previously created database, testdb.

    mysql

    Step 2 − Now, a new window will be opened and click on the drop now option as shown in the below picture.

    mysql

    MySQL Workbench Create, Alter, and Drop Table

    We can create, alter, and drop a table using the MySQL workbench application. Let us look into them in a step by step process.

    Create Table

    Following are the steps to create a table using MySQL workbench −

    Step 1 − Open MySQL workbench, login with the username and password. Then, click on the schemas menu on left-corner of the window. Here, we can find all the databases which exist in the MySQL server.

    Step 2 − Now, double click on the previously created testdb database, and we can see sub-menu under the database such as Tables, Views, Functions and Stored procedures as shown in the picture below.

    mysql

    Step 3 − Now, right click on the Tables and click on create table option. Else, we can create a table by clicking the table button which is highlighted with a red outline in the above picture.

    Step 4 − After clicking the create table option, the following will be displayed. Then we need to enter the name of the table (say employees) and use the default collation and engine.

    mysql

    Step 5 − Now, click on the table fields and enter the column names. We can also select attributes to the columns such as Primary Key (PK), Not Null (NN), Unique Key (UQ) and so on. After providing all the details click on the apply button.

    Step 6 − After we click the apply button, an SQL statement window will be opened and then we need to click on apply button and finish button to save the changes.

    Step 7 − Now, go back to the schema menu and select the database that contains the newly created employees table. There we can find all the data that we provided to the table.

    mysql

    Alter Table

    Following are the steps to alter a table using MySQL workbench −

    Step 1 − Select the table which we want to modify and click on the i icon. Here, we are modifying the previously created employees table.

    mysql

    Step 2 − After clicking on the i icon, the following will be displayed where we can find the options to modify the table”s columns, indexes and other datatypes etc. After modifying, click on the analyze table button to save the changes.

    mysql

    Drop Table

    Following are the steps to drop a table using MySQL workbench −

    Step 1 − To drop a table, we need to select the particular table which we want to delete. Then, right click on it and select the drop table option. Here, we are deleting the employees table.

    mysql

    Step 2 − A new window will be opened and click on drop now option to remove the table from the database.

    mysql

    MySQL Workbench Insert and Delete Table Rows

    Let”s have a look on how to inset and delete table rows using the MySQL Workbench application.

    Insert Rows

    Following are the steps to insert rows into a table using MySQL workbench −

    Step 1 − Open MySQL workbench. Then click on schemas menu on left corner of the window. Here, we can see that our previously created database (testdb) and table (employees).

    Step 2 − First double click on testdb database, then double click on tables. Now, if we hover the mouse on the employees table, a table icon will appear. Click on that table icon.

    mysql

    Step 3 − Now, click on the respected column or row to insert the values.

    mysql

    Step 4 − After inserting the values, click on the apply button. Then a new SQL statement window will be opened, click on apply and finish buttons to save the records. If we want to modify the records, we can follow the same procedure as discussed.

    Delete Rows

    Following are the steps to delete rows into a table using MySQL workbench −

    Step 1 − To delete an individual row from the table, we can simply right click on that particular row and click on the Delete row(s) option as shown below. Here, we have deleted the first row (i.e ID = 1).

    mysql

    Step 2 − After selecting the delete row(s) option a new window will be opened. Then, click on apply and finish buttons to save the changes. In the following picture, we can see that the row1 (i.e. ID =1) got deleted.

    mysql

    MySQL Workbench Export and Import Database

    Let”s have a look on how to export and import database using the MySQL Workbench application.

    Export Database

    Following are the steps to export a database using MySQL workbench −

    Step 1 − To export a database, go to menu bar at the top of the window and click on the Server option. After clicking that, select the data export option.

    mysql

    Step 2 − A new data export window will be opened. Now, select the database (testdb), it will display all the corresponding tables exist in that.

    mysql

    Step 3 − Now, click on the drop-down setting, there we will be having three options such as Dump Structure and Data, Dump Data Only, and Dump Structure Only.

    • Dump Structure and Data − This option will export both the table structure and data records.

    • Dump Data Only − This will export only the records in the table.

    • Dump Structure Only − This will export only the table structure, which are columns and datatypes defined by us.

    Step 4 − Select the Dump Structure and Data option. Then in the Export options, we can see two options to select the export path as follows −

    • Export to Dump Project Folder − This option will export all the tables as separate SQL files under one folder. It is recommended when we import the exported file one by one.

    • Export to Self-Contained File − This options will export all the databases and tables in a single SQL file. It is recommended when we import all the databases, tables, and data rows using a single SQL file.

    Step 5 − Select the “Export to Dump Project Folder” option and click on the start export button. Then it displays a process bar as shown in the figure below.

    mysql

    Step 6 − Now, we can find the exported file in the provided path while exporting.

    Import Database

    Following are the steps to import a database using MySQL workbench −

    Step 1 − To export a database, go to menu bar at the top of the window and click on the Server option. After clicking that, select the data import option.

    mysql

    Step 2 − A new data import window will be opened. Here, we can find two options such as “Import from Dump Project Folder” and “Import from Self-Contained File”.

    Step 3 − Now, we are going to select the “Import from Dump Project Folder” option and click on the “Load Folder Contents” to show all the available databases in the project folder.

    Step 4 − Now, select the testdb database from the Data import option and select the respective employees table.

    mysql

    Step 5 − Select the “Dump Structure and Data” option and click on the “start import” button to import the database from the exported file.

    mysql

    Step 6 − Now, go the schema menu and click on the employees and again click on the table to see the imported table.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Drop Database nhận dự án làm có lương

    MySQL – Drop Database

    Table of content


    MySQL DROP Database Statement

    The DROP DATABASE statement in MySQL is used to delete a database along with all the data such as tables, views, indexes, stored procedures, and constraints.

    While deleting an existing database −

    • It is important to make sure that we have to perform the backup of the database that we are going to delete because once the “DROP DATABASE” statement is executed, all the data and database objects in the database will be permanently deleted and cannot be recovered.
    • It is also important to ensure that no other user or application is currently connected to the database that we want to delete. If we try to delete the database while others users are connected to it, then it can cause data corruption or other issues.

    In addition to these we need to make sure we have the necessary privileges before deleting any database using the DROP DATABASE statement.

    Syntax

    Following is the syntax to delete a database in MySQL −

    DROP DATABASE DatabaseName;
    

    Here, the “DatabaseName” is the name of the database that we want to delete.

    Example

    First of all, let us create a database named TUTORIALS into database system using the following query −

    CREATE DATABASE TUTORIALS;
    

    Once the database is created, execute the following query to verify whether it is created or not −

    SHOW DATABASES;
    

    As we can see the list of databases below, the TUTORIALS database has been created successfully −

    Database
    information_schema
    mysql
    performance_schema
    tutorials

    Now, let us delete the existing database <TUTORIALS> using the following DROP DATABASE statement −

    DROP DATABASE TUTORIALS;
    

    Output

    On executing the given query, the output is displayed as follows −

    Query OK, 0 rows affected (0.01 sec)
    

    Verification

    Once we have deleted the TUTORIALS database, we can verify whether it is deleted or not using the following query −

    SHOW DATABASES;
    

    As we can in the output, the database has been deleted successfully.

    Database
    information_schema
    mysql
    performance_schema

    Dropping a Database using mysqladmin

    You would need special privileges to create or to delete a MySQL database. So, assuming you have access to the root user, you can create any database using the mysql mysqladmin binary.

    Note: Be careful while deleting any database because you will lose your all the data available in your database.

    Example

    Here is an example to delete a database(TUTORIALS) created in the previous chapter −

    [root@host]# mysqladmin -u root -p drop TUTORIALS
    Enter password:******
    

    This will give you a warning and it will ask you to confirm (Y/N) that you really want to delete this database or not. If you enter ”y”, the database will be deleted, else no −

    Dropping the database is potentially a very bad thing to do.
    Any data stored in the database will be destroyed.
    
    Do you really want to drop the ''TUTORIALS'' database [y/N] y
    

    Output

    The TUTORIALS database has been deleted successfully.

    Database "TUTORIALS" dropped
    

    Dropping Database Using a Client Program

    Besides using MySQL queries to perform the DROP DATABASE operation, we can also use client programs like Node.js, PHP, Java, and Python to achieve the same result.

    Syntax

    Following are the syntaxes of this operation in various programming languages −

    To drop a database through a PHP program, we need to execute the ”DROP DATABASE” statement using the mysqli function query() as follows −

    $sql = "DROP DATABASE DatabaseName;";
    $mysqli->query($sql);
    

    To drop a database through a Node.js program, we need to execute the ”DROP DATABASE” statement using the query() function of the mysql2 library as follows −

    sql = "DROP DATABASE DatabaseName;";
    con.query(sql, function (err, result) {
       if (err) throw err;
          console.log(result);
    });
    

    To drop a database through a Java program, we need to execute the ”DROP DATABASE” statement using the JDBC function executeUpdate() as follows −

    String sql = "DROP DATABASE DatabaseName;";
    st.execute(sql);
    

    To drop a database through a Python program, we need to execute the ”DROP DATABASE” statement using the execute() function of the MySQL Connector/Python as follows −

    sql = "DROP DATABASE DatabaseName;"
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''root@123
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass);
    
    if($mysqli->connect_errno ) {
       printf("Connect failed: %s<br />", $mysqli->connect_error);
       exit();
    }
    printf(''Connected successfully.<br />'');
    
    if ($mysqli->query("Drop DATABASE TUTORIALS")) {
       printf("Database dropped successfully.<br />");
    }
    if ($mysqli->errno) {
       printf("Could not drop database: %s<br />", $mysqli->error);
    }
    $mysqli->close();
    

    Output

    The output obtained is as follows −

    Connected successfully.
    Database dropped successfully.
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
       host: "localhost",
       user: "root",
       password: "Nr5a0204@123"
    });
       //Connecting to MySQL
       con.connect(function (err){
        if (err) throw err;
        console.log("Connected!");
        console.log("--------------------------");
        //Creating a Database
        sql = "DROP DATABASE TUTORIALS"
        con.query(sql, function(err){
          if (err) throw err
          console.log("Database Dropped successfully...!")
        });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    Database Dropped successfully...!
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class DropDatabase {
    	public static void main(String[] args) {
    		String url = "jdbc:mysql://localhost:3306/tutorials";
    		String user = "root";
    		String password = "password";
    		ResultSet st;
    		try {
    			Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st1 = con.createStatement();
                //System.out.println("Connected successfully...!");
                String sql = "DROP DATABASE TUTORIALS";
                st1.execute(sql);
                System.out.println("Database dropped successfully...!");
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Output

    The output obtained is as shown below −

    Database dropped successfully...!
    
    import mysql.connector
    # creating the connection object
    connection = mysql.connector.connect(
    host ="localhost",
    user ="root",
    password ="password"
    )
    # creating cursor object
    cursorObj = connection.cursor()
    # dropping the database
    cursorObj.execute("DROP DATABASE MySqlPython")
    print("Database dropped Successfully")
    # disconnecting from server
    connection.close()
    

    Output

    Following is the output of the above code −

    Database dropped Successfully
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Database Import nhận dự án làm có lương

    MySQL – Database Import

    Table of content


    As we learned in the previous tutorial about ”Database Export”, now we”ll learn how to import the exported data, or backup, into an existing MySQL database. This process is known as database import.

    In MySQL, to import an existing dump or backup file into a database, we use the mysql command-line tool.

    Importing Backup Data

    We can import the backup data into an MySQL database using the mysql command-line tool. It takes the username, database name, and the backup file with the data.

    Syntax

    Following is the syntax of mysql command-line tool −

    $ mysql -u username -p new_database_name < dumpfile_path
    

    Where,

    • username: This is the MySQL username to use when connecting to the MySQL server.

    • new_database_name: The name of the database where you want to import the data.

    • dumpfile_path: It is the path of the backup file. The data will be imported from this file.

    • <: This symbol imports the data from the file named output_file_path.

    Example

    In this example, we will import the file named “data-dump.sql” that was generated in the previous tutorial (Database Export). The file contains a table named ”CUSTOMERS”.

    Before doing that, let us login to MySQL server as a user to create a new databases −

    $ mysql -u root -p
    

    After logging in, it will bring you into MySQL command-line. Now, create a new database named testdb using the below query −

    CREATE DATABASE testdb;
    

    When we execute the above query, the output is obtained as follows −

    Query OK, 1 row affected (0.01 sec)
    

    To exit from the MySQL command-line, execute q. Now, from the normal command line, we can import the dump file ”data-dump.sql” using the following query.

    Once we execute the below statement, we need to enter our MySQL server password.

    $ mysql -u root -p testdb < data-dump.sql
    

    If the above command is runs successfully, it won”t show any visible output. Instead, it imports the data. If any error occur during the execution, MySQL will display them to the terminal.

    Verification

    To verify whether the import was successful, execute the following query to login into MySQL command-line −

    $ mysql -u root -p
    

    Now, select the current database to ”testdb” using the following MySQL ”Use” query −

    Use testdb;
    

    Execute the following query to check whether the table named CUSTOMERS in “data-dump.sql” file has been imported or not −

    Show Tables;
    

    As we can see the output below, the CUSTOMERS table has been succesfully imported into the new database ”testdb”.

    Tables_in_testdb
    customers

    Let us also verify whether the records has been imported or not by executing the below query −

    select * from customers;
    

    The records are also successfully imported.

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Show Database nhận dự án làm có lương

    MySQL – SHOW Databases

    Table of content


    MySQL SHOW Databases Statement

    To display the list of all databases present in a MySQL server, we need to use the SHOW DATABASES statement. It returns the result in a tabular form with one column. The databases in the result set will be sorted in alphabetical order.

    Syntax

    Following is the syntax to list all databases in MySQL sever −

    SHOW DATABASES [LIKE ''pattern'' | WHERE expr]
    

    Example

    First of all, let us create a database with a name TUTORIALS using the following query −

    CREATE DATABASE TUTORIALS;
    

    Make sure you have the admin privilege before creating any database. Once a database is created, you can check it in the list of databases by using the following query −

    SHOW DATABASES;
    

    Output

    The above query displayed all the databases present in the current MySQL server.

    Database
    information_schema
    mysql
    performance_schema
    tutorials

    MySQL SHOW SCHEMAS Statement

    We can also use the SHOW SCHEMAS statement to list out the databases in MySQL.

    Syntax

    Following is the syntax of the MySQL SHOW SCHEMAS statement −

    SHOW SCHEMAS [LIKE ''pattern'' | WHERE expr]
    

    Example

    Lets try to verify the list of databases once again you can using the following query −

    SHOW SCHEMAS;
    

    Output

    The output of the above query will be as shown below −

    Database
    information_schema
    mysql
    performance_schema
    tutorials

    Showing Databases Using a Client Program

    Besides fetching the list of all databases in current MySQL server with a MySQL query, we can also use a client program to perform the SHOW DATABASES operation.

    Syntax

    Following are the syntaxes of this operation in various programming languages −

    To show the list of all databases present in current MySQL through PHP program, we need to execute the SHOW DATABASES statement using the mysqli function query() as follows −

    $sql = "SHOW Database_name";
    $mysqli->query($sql);
    

    To show the list of all databases present in current MySQL through Node.js program, we need to execute the SHOW DATABASES statement using the query() function of the mysql2 library as follows −

    sql= "SHOW {DATABASES | SCHEMAS} LIKE ''pattern'' | WHERE expr]";
    con.query(sql);
    

    To show the list of all databases present in current MySQL through Java program, we need to execute the SHOW DATABASES statement using the JDBC function executeUpdate() as follows −

    String sql = "SHOW Database_name";
    st.executeQuery(sql);
    

    To show the list of all databases present in current MySQL through Python program, we need to execute the SHOW DATABASES statement using the execute() function of the MySQL Connector/Python as follows −

    sql = "SHOW Database_name";
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass);
    
    if($mysqli->connect_errno ) {
       printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); if ($result = $mysqli->query("SHOW DATABASES")) { printf("Show Database executed successfully..!"); echo "Database list are: "; while($row = mysqli_fetch_array($result)){ print_r($row); } } if ($mysqli->errno) { printf("Could not find database: %s
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Show Database executed successfully..!Database list are:
    Array
    (
        [0] => bank
        [Database] => bank
    )
    Array
    (
        [0] => company
        [Database] => company
    )
    Array
    (
        [0] => information_schema
        [Database] => information_schema
    )
    Array
    (
        [0] => mydb
        [Database] => mydb
    )
    Array
    (
        [0] => mysql
        [Database] => mysql
    )
    Array
    (
        [0] => performance_schema
        [Database] => performance_schema
    )
    Array
    (
        [0] => sys
        [Database] => sys
    )
    Array
    (
        [0] => testdb
        [Database] => testdb
    )
    Array
    (
        [0] => tutorials
        [Database] => tutorials
    )
    Array
    (
        [0] => usersdb
        [Database] => usersdb
    )
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
       host: "localhost",
       user: "root",
       password: "Nr5a0204@123"
    });
    
    //Connecting to MySQL
    con.connect(function (err) {
    if (err) throw err;
    console.log("Connected!");
    console.log("--------------------------");
    
    //Creating a Database
    sql = "create database testDB1"
    con.query(sql);
    sql = "create database testDB2"
    con.query(sql);
    sql = "create database testDB3"
    con.query(sql);
    sql = "create database testDB4"
    con.query(sql);
    
    //Displaying Databases
    sql = "show databases;"
    con.query(sql, function(err, result){
      if (err) throw err
      console.log(result)
    });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    [
      { Database: ''customers'' },
      { Database: ''information_schema'' },
      { Database: ''mysql'' },
      { Database: ''performance_schema'' },
      { Database: ''testdb1'' },
      { Database: ''testdb2'' },
      { Database: ''testdb3'' },
      { Database: ''testdb4'' }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class ShowDatabase {
    	public static void main(String[] args) {
    		String url = "jdbc:mysql://localhost:3306/TUTORIALS";
    		String user = "root";
    		String password = "password";
    		ResultSet rs;
    		try {
    			Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st1 = con.createStatement();
                //System.out.println("Database connected successfully...!");
                String sql = "SHOW DATABASES";
                rs = st1.executeQuery(sql);
                System.out.println("Show query executed successfully...!");
                System.out.println("Databases are: ");
                while(rs.next()) {
                	String db = rs.getNString(1);
                	System.out.println(db);
                }
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Output

    The output obtained is as shown below −

    Show query executed successfully...!
    Databases are:
    bank
    company
    information_schema
    mydb
    mysql
    performance_schema
    sys
    testdb
    tutorials
    usersdb
    
    import mysql.connector
    # Creating the connection object
    connection = mysql.connector.connect(
    host ="localhost",
    user ="root",
    password ="password"
    )
    # Creating cursor object
    cursorObj = connection.cursor()
    # Show databases
    cursorObj.execute("SHOW DATABASES")
    # Fetch all the databases
    databases = cursorObj.fetchall()
    # Printing the list of databases
    print("The list of databases are: ")
    for database in databases:
        print(database[0])
    # Disconnecting from server
    connection.close()
    

    Output

    Following is the output of the above code −

    The list of databases are:
    information_schema
    mysql
    mysqlpythondb
    performance_schema
    sqlserver
    stdi
    sys
    textx
    tut
    tutorials
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Database Export nhận dự án làm có lương

    MySQL – Database Export

    Table of content


    MySQL is one of the most popular relational database systems used to store and manage data. It structures data in the form of tables and views so that data handling becomes easier making organizations prefer using MySQL to manage their company”s confidential data. Since their data is highly confidential, it becomes necessary to back up the database and restore it whenever necessary. Hence we perform database export.

    Exporting a database in MySQL is commonly used for backup purposes or transferring data between servers. You can export entire database or just a portion of it. The simplest way of exporting a database is by using the mysqldump command-line tool.

    Exporting Database using mysqldump

    The mysqldump command-line tool is used in MySQL to create backups of databases. It can be used to back up an entire database, specific tables, or even specific rows based of a table.

    Following is the syntax of mysqldump command to export a database −

    $ mysqldump -u username -p database_name > output_file_path
    

    Where,

    • username: It is the MySQL username to use when connecting to the database.

    • database_name: It is the name of the database to be exported.

    • output_file_path: It is the path of the backup file. This is where the backup data will be stored.

    • >: This symbol exports the output of the mysqldump command into a file named output_file_path.

    Example

    First of all, create a database named TUTORIALS using the following query −

    Create database TUTORIALS;
    

    Execute the below query to select the current database as TUTORIALS −

    USE TUTORIALS;
    

    Let us also create a table named CUSTOMERS in the above-created database −

    CREATE TABLE CUSTOMERS (
       ID INT AUTO_INCREMENT,
       NAME VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    The following query inserts 7 records into the CUSTOMERS table −

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00 ),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00 ),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 ),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00 ),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00 ),
    (7, ''Muffy'', 24, ''Indore'', 10000.00 );
    

    Here, we are using the mysqldump command-line statement to export the TUTORIALS database to the ”datadump.sql” file. Once we execute the below statement, we need to enter our MySQL server password.

    $ mysqldump -u root -p TUTORIALS > data-dump.sql
    

    The above command will not produce any visual output. Instead, the ”data-dump.sql” file will be saved in the current working directory of the command prompt or terminal where you executed the command.

    Exporting only Specific Tables in Database

    We can also export only specific tables in a database using the mysqldump command-line tool. To do so, we use the following syntax −

    mysqldump -u username -p database_name table1 table2 ... > output_file.sql
    

    Example

    Before exporting, let us create two new tables (STUDENTS and EMPLOYEES) in the above-created TUTORIALS database using the following query −

    CREATE TABLE STUDENTS (
       ID INT AUTO_INCREMENT,
       NAME VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       FEES DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Here, we are creating the EMPLOYEES table −

    CREATE TABLE EMPLOYEES (
       ID INT AUTO_INCREMENT,
       NAME VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARIES DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Let us fetch the list of tables in the TUTORIALS database using the below query −

    Show Tables;
    

    As we can in the output below, we have three tables present in TUTORIALS database −

    Tables_in_tutorials
    customers
    employees
    students

    Now, let us export two tables named EMPLOYEES and STUDENTS into the ”datadump2.sql” as follows −

    $ mysqldump -u root -p TUTORIALS employees students > output_file.sql
    

    Once we executed the above query, it wont display any ouptut. Instead, it exports the data of both the tables into the specified file.

    Exporting all Databases in a Host

    For instance, you have multiple databases in your host and you want to export all of them in a single query. In such scenario, we can use the “–all-databases” option of mysqldump command.

    Example

    Following is the query to export all the databases in a host using the –all-databases option −

    $ mysqldump -u root -p --all-databases > database_dump.sql
    

    The above command won”t show any visible output on the screen. Instead, the ”database_dump.sql” file will be saved in the current working directory of the command prompt or terminal where you ran the command.”


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Copy Database nhận dự án làm có lương

    MySQL – Copy Database

    Table of content


    In modern times, companies rely on databases to store crucial information like financial transactions, customer profiles, and employee records. It is very important to maintain regular copies of databases there can always be a chance of data loss from power surges and disk crashes. Therefore, regular backups of databases are crucial for effective data management.

    Copy Database in MySQL

    In MySQL, copying a database involves creating an exact duplicate of an existing database, including its schema and data. This is almost similar to having a backup of a database. It is important to ensure that any changes made to the original database after the copy is made are also reflected in the copied database, if necessary.

    To create a copy of a database SQL Server provides the Copy Database statement. But, this is not available in MySQL. Therefore, to create copy of a database we need to dump the contents of one database to other manually.

    The following are three steps that involve in copying a database −

    • First of all, we need to create a new database.

    • Then, we need to export the original database using mysqldump.

    • Finally, importing the exported data into the new database.

    Example

    First of all, let us create a database in the MySQL server using the following query −

    CREATE DATABASE testdb;
    

    We can verify whether the database testdb is created or not using the SHOW DATABASES statement.

    SHOW DATABASES;
    

    As we can see the output below, the testdb database has been created successfully.

    Database
    information_schema
    mysql
    performance_schema
    testdb

    Once the database is created successfully, we need to change the current database to ”testdb”, using the USE statement so that any operations we perform such as creating a table will be stored in this database.

    USE testdb;
    

    Now, let us create a table named CUSTOMERS using the CREATE query as follows −

    CREATE TABLE CUSTOMERS (
       ID INT AUTO_INCREMENT,
       NAME VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    The following query inserts 7 records into the above-created table −

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00 ),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00 ),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 ),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00 ),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00 ),
    (7, ''Muffy'', 24, ''Indore'', 10000.00 );
    

    Using the following query, we can verify whether the table CUSTOMERS is created in ”testdb” database or not −

    SHOW TABLES;
    

    The table is successfully created in the testdb database.

    Tables_in_testdb
    customers

    Creating Copy database (Manually)

    As discussed earlier in MySQL to create a copy of an existing database we need to create a separate database and dump the contents of it to the newly created database manually.

    Following statement creates a database named testdb_copy (to which we need to copy the contents of the testdb database created above).

    CREATE DATABASE testdb_copy;
    

    Once both our source (testdb) and destination (testdb_copy) databases are ready, we need to follow the steps given below to manually copy the data from one to another.

    Step1 − Open the command prompt, browse through the bin folder of the MySQL server. For instance, we have installed MySQL in the C Program Files directory so, the following command will take us to the bin folder −

    C:> CD C:Program FilesMySQLMySQL Server 8.0bin
    

    Step 2 − Using the mysqldump tool, we can copy the database objects and data into a .sql file. Here, we are exporting the contents of the testdb database to a file named “testdb.sql” located at “D:Database_backup”.

    Note − The (>) operator is used for exporting the database from one location to another.

    mysqldump -u root -p testdb > D:database_backuptestdb.sql
    

    Step 3 − Import the contents of the “testdb.sql” file into the destination database (in our case “testdb_copy”).

    Note − The (<) operator is used for importing the database from one location to another.

    mysql -u root -p testdb_copy
    

    Verification

    To verify whether the data and database object is imported into the testdb_copy database, first, we need to use the current database using the following query in the MySQL Command Line Client

    USE testdb_copy;
    

    If the contents of the testdb are copied in to the testdb_copy successfully, we should be able to find the customers table in the list of tables (which is created earlier).

    Therefore, let us verify whether the data from the "testdb" database have been copied to the "testdb_copy" database or not using the following query −

    SHOW TABLES;
    

    As we can see in the list below, all the database objects and data have been successfully copied.

    Tables_in_testdb
    customers

    Copy Database Without MySQLdump

    If we want to copy a database without using the mysqldump tool, we must manually create each table in the destination database and copy all the data from the tables present in the current database. This is a repitetive process that should be done for each table that needs to be copied.

    Example

    Let us create a new database in the MySQL server using the following query −

    CREATE DATABASE Tutorials;
    

    We can verify whether the database Tutorials is created or not using the following query −

    SHOW DATABASES;
    

    As we can see the output below, the ”Tutorials” database has been created successfully.

    Database
    information_schema
    mysql
    performance_schema
    tutorials

    Now, we are switching the current database to Tutorials, so that any operations we perform such as creating a table will be stored in this database.

    USE Tutorials;
    

    Once we have switched, create a table named CUSTOMERS using the following query −

    CREATE TABLE CUSTOMERS (
       ID INT AUTO_INCREMENT,
       NAME VARCHAR(20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Here, we are inserting some records into the table using the INSERT INTO statement below −

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00 ),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00 ),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 ),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00 ),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00 ),
    (7, ''Muffy'', 24, ''Indore'', 10000.00 );
    

    Using the below query, let us create another database Tutorials_copy, where we want to copy all the data objects and data of the Tutorials database.

    CREATE DATABASE Tutorials_copy;
    

    We can verify whether the database Tutorials_copy is created or not, using the following query −

    SHOW DATABASES;
    

    The database has been created.

    Database
    information_schema
    mysql
    performance_schema
    tutorials
    tutorials_copy

    Now, switch the current database to ”tutorials_copy” using the following query −

    USE Tutorials_copy;
    

    Here, we are creating an empty table named “CUSTOMERS” in the ”Tutorials_copy” database with the same schema as the original ”CUSTOMERS” table in the ”Tutorials” −

    CREATE TABLE Tutorials_copy.customers LIKE Tutorials.customers;
    

    This query inserts all the data from the original ”customers” table in the ”Tutorials” database into the new ”customers” table in the ”tutorials_copy” database.

    INSERT Tutorials_copy.customers SELECT * FROM Tutorials.customers;
    

    We can verify whether the database objects and data from the ”Tutorials” database have been copied to the ”Tutorials_copy” database or not.

    SHOW TABLES;
    

    Output

    As we can see in the list below, the table has been successfully copied −

    Tables_in_tutorials_copy
    customers

    Let us also retrieve the records of CUSTOMERS table in ”Tutorials_copy” database to verify whether the records have been copied or not −

    Select * from CUSTOMERS;
    

    As we can see the CUSTOMERS table in ”Tutorials_copy” database below, the records have been successfully copied −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Database Info nhận dự án làm có lương

    MySQL – Database Info

    Table of content


    MySQL usually stores two types of data in it: actual data stored in the form of tables and views, and information about the structure of a database and its objects. Such information is known as Metadata.

    For instance, whenever a user forgets certain information of a database or its objects, MySQL provides specific commands to retrieve the said information. There are actually three types of information, which you can retrieve from a MySQL database. They are as follows −

    • Information about the result of queries − This includes the number of records affected by any SELECT, UPDATE or DELETE statement.

    • Information about the tables and databases − This includes information related to the structure of the tables and the databases.

    • Information about the MySQL server − This includes the status of the database server, version number, etc.

    It is very easy to get all this information at the MySQL prompt, but while using PERL or PHP APIs, we need to call various APIs explicitly to obtain all this information.

    Obtaining Database Info from MySQL Prompt

    While accessing a MySQL server from MySQL prompt, which is a Command Prompt in Windows and a Terminal in Linux etc., any information regarding a database using following commands.

    • SHOW DATABASES: This command is used to retrieve the list of all databases present in MySQL.

    • SHOW TABLES: This command is used to display the list of tables present in a database.

    • mysql -V: This command is used to provide the current version of MySQL installed in your system.

    • DESC or DESCRIBE: This command is used to retrieve the structure or definition of a database table.

    mysql -V Command

    If you want to check the version of MySQL Server installed in your system, use the following mysql -V on Command Prompt or Terminal.

    Note: You must remember that the command prompt must be run as an administrator in Windows.

    Example

    In here, we are checking the current version of MySQL server in command prompt −

    C:WindowsSystem32> mysql -V
    

    Output

    As we can see the output below, the current MySQL server version is ”8.0.33” −

    mysql  Ver 8.0.33 for Win64 on x86_64 (MySQL Community Server - GPL)
    

    SHOW DATABASES Command

    To list or retrieve the names of all the databases in MySQL, you can use the following SHOW DATABASES command after logging into MySQL server −

    Note − This command will list both system databases and user-defined databases together. The user must identify their specific user-defined database all the data is stored in.

    Example

    In the following query, we are fetching list of databases that exists in the current MySQL server −

    SHOW DATABASES;
    

    Here, the first three rows are system databases and the last two rows are user-defined databases −

    Database
    information_schema
    mysql
    performance_schema
    tutorials
    tutorials_copy

    SHOW TABLES Command

    To list all the tables in a MySQL database, you can use the SHOW TABLES command after selecting a database with USE command −

    Example

    In the below query, we are selecting a database named ”Tutorials” −

    USE Tutorials;
    

    Now, let us use the SHOW TABLES to fetch all the names of tables present in the above database −

    Show Tables;
    

    Output

    Following is the list of tables exist in the ”Tutorials” database −

    Tables_in_tutorials
    customers
    employees
    students

    DESC Command

    If we want to check the structure of a MySQL table, we need to use the DESC or DESCRIBE query. DESC is a shortcut for DESCRIBE query, but retrieves the same result.

    Example

    Here, we are fetching the structure of MySQL CUSTOMERS table −

    DESC CUSTOMERS;
    

    Following is the structure −

    Field Type Null Key Default Extra
    ID int NO PRI NULL auto_increment
    NAME varchar(20) NO NULL
    AGE int NO NULL
    ADDRESS char(25) YES NULL
    SALARY decimal(18,2) YES NULL

    Obtaining the Number of Rows Affected by a Query

    Let is now see how to obtain this information.

    PERL Example

    In DBI scripts, the affected row count is returned by the do( ) or by the execute( ) command, depending on how you execute the query.

    # Method 1
    # execute $query using do( )
    my $count = $dbh->do ($query);
    # report 0 rows if an error occurred
    printf "%d rows were affectedn", (defined ($count) ? $count : 0);
    
    # Method 2
    # execute query using prepare( ) plus execute( )
    my $sth = $dbh->prepare ($query);
    my $count = $sth->execute ( );
    printf "%d rows were affectedn", (defined ($count) ? $count : 0);
    

    PHP Example

    In PHP, invoke the mysql_affected_rows( ) function to find out how many rows a query changed.

    $result_id = mysql_query ($query, $conn_id);
    # report 0 rows if the query failed
    $count = ($result_id ? mysql_affected_rows ($conn_id) : 0);
    print ("$count rows were affectedn");
    

    Listing Tables and Databases

    It is very easy to list down all the databases and the tables available with a database server. Your result may be null if you don”t have the sufficient privileges.

    Apart from the method which is shown in the following code block, you can use SHOW TABLES or SHOW DATABASES queries to get the list of tables or databases either in PHP or in PERL.

    PERL Example

    # Get all the tables available in current database.
    my @tables = $dbh->tables ( );
    
    foreach $table (@tables ){
       print "Table Name $tablen";
    }
    

    PHP Example

    Try the following example to get database info −

    Copy and paste the following example as mysql_example.php −

    <html>
       <head>
          <title>Getting MySQL Database Info</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $dbname = ''TUTORIALS
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
             $tutorial_count = null;
    
             if($mysqli->connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli->connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
    
             if ($result = mysqli_query($mysqli, "SELECT DATABASE()")) {
                $row = mysqli_fetch_row($result);
                printf("Default database is %s<br />", $row[0]);
                mysqli_free_result($result);
             }
             $mysqli->close();
          ?>
       </body>
    </html>
    

    Output

    Access the mysql_example.php deployed on apache web server and verify the output.

    Connected successfully.
    Default database is tutorials
    

    Getting Server Metadata

    There are a few important commands in MySQL which can be executed either at the MySQL prompt or by using any script like PHP to get various important information about the database server.

    Sr.No. Command & Description
    1

    SELECT VERSION( )

    Server version string

    2

    SELECT DATABASE( )

    Current database name (empty if none)

    3

    SELECT USER( )

    Current username

    4

    SHOW STATUS

    Server status indicators

    5

    SHOW VARIABLES

    Server configuration variables


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc