Category: mysql

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

    MySQL – INDEXES



    An index is a data structure that improves the speed of operations on a database table. They are a special type of lookup tables pointing to the data. Indexes can be created on one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.

    Indexes, however, reduce the efficiency of INSERT and UPDATE operations on a table. This is because when we insert or update a data value in a table, indexes also need to be modified accordingly. So, they are not always appropriate to use.

    Users cannot see the indexes, they are just used to speed up queries and will be used by the Database Search Engine to locate records very fast.

    Types of MySQL Indexes

    Indexes can be defined on single or multiple columns of a MySQL table. The decision to add indexes on a table column(s) depends on the type of data that needs to be searched. MySQL provides the following types of indexes −

    • Simple Index

    • Unique Index

    • Primary Key Index

    • Fulltext Index

    • Descending Index

    Simple Index

    A simple index is a basic type of index where the values inserted into the column, containing this index, are searched easily. In such case, the column can contain duplicate values or NULL.

    Unique Index

    A Unique index does not allow any duplicate values to be inserted into a table column (where the index is defined on).It can be added to single or multiple columns of a table. If it is added to a single column, the values of that column must be unique. But if it is added to multiple columns, the combination of values in these columns must be unique.

    Primary Key Index

    Primary Key Index is an extension of unique index, as the primary key column must always contain unique values and these values must not be NULL. Primary key can be set to a single column of a database table, or multiple columns as well (which is not recommended).

    Fulltext Index

    In a database, sometimes you would have to search for a blob of text instead of a record. You can use fulltext index for it. As its name suggests, it is used to make the text searches in a table easier.

    Descending Index

    The descending index is only available in MySQL versions after 8.0. It is simple index used to store data in a reverse order. Using this index, it is easy to search for the latest values inserted into the database 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 – Rename Views nhận dự án làm có lương

    MySQL – Rename View

    Table of content


    Renaming Views in MySQL

    The MySQL RENAME TABLE statement in MySQL is generally used to rename the name of a table. But this statement can also be used to rename views because views are typically virtual tables created by a query.

    Before renaming a view, we need to ensure that no active transactions are being performed on the view using its old name. It is, however, recommended to delete the existing view and re-create it with a new name instead of renaming it.

    Syntax

    Following is the basic syntax of the RENAME TABLE query to rename a view in MySQL −

    RENAME TABLE original_view_name
    TO new_view_name;
    

    Example

    First of all, let us create a table with the name CUSTOMERS using the following query −

    CREATE TABLE CUSTOMERS(
       ID int NOT NULL,
       NAME varchar(20) NOT NULL,
       AGE int NOT NULL,
       ADDRESS varchar(25),
       SALARY decimal(18, 2),
       PRIMARY KEY (ID)
    );
    

    Here, we are inserting some records into the above-created table using the query below −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', ''32'', ''Ahmedabad'', 2000),
    (2, ''Khilan'', ''25'', ''Delhi'', 1500),
    (3, ''Kaushik'', ''23'', ''Kota'', 2500),
    (4, ''Chaitali'', ''26'', ''Mumbai'', 6500),
    (5, ''Hardik'',''27'', ''Bhopal'', 8500),
    (6, ''Komal'', ''22'', ''MP'', 9000),
    (7, ''Muffy'', ''24'', ''Indore'', 5500);
    

    Creating a view −

    Now, let us create a view based on the above created table using the following query −

    CREATE VIEW CUSTOMERS_VIEW AS SELECT * FROM CUSTOMERS;
    

    The view will be created as follows −

    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

    Renaming the view −

    Now, we know that we are having an existing view in our database named “CUSTOMERS_VIEW”. So, we are going to rename this view to VIEW_CUSTOMERS using the below query −

    RENAME TABLE CUSTOMERS_VIEW TO VIEW_CUSTOMERS;
    

    Verification

    Using the following SELECT statement, we can verify whether the view is renamed or not −

    SELECT * FROM VIEW_CUSTOMERS;
    

    The “VIEW_CUSTOMERS” view displayed is as follows −

    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

    Rules to be followed while Renaming Views

    There are some rules and practices to ensure that the renaming process goes smoothly and one should follow them while renaming a view in MySQL. They are listed below:

    • Avoid renaming system views: In MySQL, the system views are views that contain all the information about the database management system. It is recommended not to rename these views because it can cause issues with the functioning of the database.

    • Update all references to the view: After renaming a view in MySQL, any stored procedures, triggers, or other database objects that reference the view will need to be updated to use the new name of the view. If we failed to update these references results in errors or issues with the functioning of the database system.

    • Test thoroughly: It is important to test the renaming process thoroughly in the development or testing environment to make sure that all references to the view have been updated correctly.

    • Use a consistent naming convention: While working with views in MySQL, it”s recommended to use a consistent naming convention. If you need to rename a view, follow the same naming convention you”ve used for other views in the database.

    • Backup the database: Before renaming a view, it is recommended to have a backup of the database to make sure that you have a restore point.

    Renaming a View Using a Client Program

    Until now, we used an SQL statement to rename a view directly in the MySQL database. But, we can also perform the same rename operation on a view using another client program.

    Syntax

    To Rename a view into MySQL Database through a PHP program, we need to execute the RENAME statement using the mysqli function named query() as follows −

    $sql = "RENAME TABLE first_view To tutorial_view";
    $mysqli->query($sql);
    

    To Rename a view into MySQL Database through a JavaScript program, we need to execute the RENAME statement using the query() function of mysql2 library as follows −

    sql = "RENAME TABLE CUSTOMERS_VIEW TO VIEW_CUSTOMERS";
    con.query(sql);
    

    To Rename a view into MySQL Database through a Java program, we need to execute the RENAME statement using the JDBC function named executeQuery() as follows −

    String sql = "RENAME TABLE first_view TO tutorial_view";
    st.executeQuery(sql);
    

    To Rename a view into MySQL Database through a python program, we need to execute the RENAME statement using the execute() function of the MySQL Connector/Python as follows −

    rename_view_query = "RENAME TABLE tutorial_view TO new_tutorial_view"
    cursorObj.execute(rename_view_query)
    

    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.
    ''); // A view can be renamed by using the RENAME TABLE old_view_name TO new_view_name $sql = "RENAME TABLE first_view To tutorial_view"; if ($mysqli->query($sql)) { printf("View renamed successfully!.
    "); } if ($mysqli->errno) { printf("View could not be renamed!.
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    View renamed 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 = "create database TUTORIALS"
      con.query(sql);
    
      sql = "USE TUTORIALS"
      con.query(sql);
    
      sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL,NAME VARCHAR (20) NOT NULL,AGE INT NOT NULL,ADDRESS CHAR (25),SALARY DECIMAL (18, 2),PRIMARY KEY (ID));"
      con.query(sql);
    
      sql = "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, ''MP'', 4500.00 ),(7, ''Muffy'', 24, ''Indore'', 10000.00 );"
      con.query(sql);
    
      //Creating View
      sql = "Create view CUSTOMERS_VIEW AS SELECT * FROM CUSTOMERS";
      con.query(sql);
    
      //Renaming View
      sql = "RENAME TABLE CUSTOMERS_VIEW TO VIEW_CUSTOMERS;"
      con.query(sql);
    
      //Displaying records from view
      sql = "SELECT * FROM VIEW_CUSTOMERS;"
      con.query(sql, function(err, result){
        if (err) throw err
        console.log("**Views after deleting:**");
        console.log(result);
      });
    
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    [
      {ID: 1, NAME: ''Ramesh'', AGE: 32, ADDRESS: ''Ahmedabad'', SALARY: ''2000.00''},
      {ID: 2, NAME: ''Khilan'', AGE: 25, ADDRESS: ''Delhi'', SALARY: ''1500.00''},
      {ID: 3, NAME: ''kaushik'', AGE: 23, ADDRESS: ''Kota'', SALARY: ''2000.00''},
      {ID: 4, NAME: ''Chaitali'', AGE: 25, ADDRESS: ''Mumbai'', SALARY: ''6500.00''},
      {ID: 5, NAME: ''Hardik'', AGE: 27, ADDRESS: ''Bhopal'', SALARY: ''8500.00''},
      {ID: 6, NAME: ''Komal'', AGE: 22, ADDRESS: ''MP'', SALARY: ''4500.00'' },
      {ID: 7, NAME: ''Muffy'', AGE: 24, ADDRESS: ''Indore'', SALARY: ''10000.00''}
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class RenameView {
       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...!");
    
             //Rename Created View.....
             String sql = "RENAME TABLE first_view TO tutorial_view";
             statement.executeUpdate(sql);
             System.out.println("Renamed view Successfully...!");
             ResultSet resultSet = statement.executeQuery("SELECT * FROM tutorial_view");
             while (resultSet.next()) {
                System.out.print(resultSet.getInt(1)+" "+ resultSet.getString(2)+ " "+ resultSet.getString(3));
                System.out.println();
             }
             connection.close();
          } catch (Exception e) {
             System.out.println(e);
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    Renamed view Successfully...!
    1 Learn PHP John Paul
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    cursorObj = connection.cursor()
    rename_view_query = "RENAME TABLE tutorial_view TO new_tutorial_view"
    cursorObj.execute(rename_view_query)
    connection.commit()
    print("View renamed successfully.")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    View renamed 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 – Show Privileges nhận dự án làm có lương

    MySQL – Show Privileges

    Table of content


    The users in MySQL must have enough privileges to interact with the server. This is possible by assigning authentication details, like passwords to the users. In addition to this, operational or administrative privileges are granted separately if a user wants to interact with and operate on the data.

    The MySQL SHOW Privileges

    The MySQL SHOW PRIVILEGES Statement displays the list of privileges that are supported by the MYSQL server. The displayed list includes all static and currently registered dynamic privileges.

    The information (returned list) contains three columns −

    • Privilege − Name of the privilege
    • Context − Name of the MySQL object for which the privilege is applicable.
    • Comment − A string value describing the purpose of the privilege.

    Syntax

    Following is the syntax to list out all privileges in a MySQL Server −

    SHOW PRIVILEGES;
    

    Example

    Following query lists out all the privileges supported by the MySQL server −

    SHOW PRIVILEGES
    

    Output

    After executing the above code, we get the following output −

    Privilege Context Comment
    Alter Tables To alter the table
    Alter routine Functions, Procedures To alter or drop stored functions/procedures
    Create Databases, Tables, Indexes To create new databases and tables
    Create routine Databases To use CREATE FUNCTION/PROCEDURE
    Create role Server Admin To create new roles
    Create temporary tables Databases To use CREATE TEMPORARY TABLE
    Create view Tables To create new views
    Create user Server Admin To create new users
    Delete Tables To delete existing rows
    Drop Databases, Tables To drop databases, tables, and views
    Drop role Server Admin To drop roles
    Event Server Admin To create, alter, drop and execute events
    Execute Functions, Procedures To execute stored routines
    File File access on server To read and write files on the server
    Grant option Databases, Tables, Funcs, Procedures To give to other users those privileges you possess
    Index Tables To create or drop indexes
    Insert Tables To insert data into tables
    Lock tables Databases To use LOCK TABLES (together with SELECT privilege)
    Process Server Admin To view the plain text of currently executing queries
    Proxy Server Admin To make proxy user possible
    References Databases,Tables To have references on tables
    Reload Server Admin To reload or refresh tables, logs and privileges
    Replication client Server Admin To ask where the slave or master servers are
    Replication slave Server Admin To read binary log events from the master
    Select Tables To retrieve rows from table
    Show databases Server Admin To see all databases with SHOW DATABASES
    Show view Tables To see views with SHOW CREATE VIEW
    Shutdown Server Admin To shut down the server
    Super Server Admin To use KILL thread, SET GLOBAL, CHANGE MASTER, etc.
    Trigger Tables To use triggers
    Create tablespace Server Admin To create/alter/drop tablespaces
    Update Tables To update existing rows
    Usage Server Admin No privileges – allow connect only
    BINLOG_ENCRYPTION_ADMIN Server Admin
    AUDIT_ADMIN Server Admin
    ENCRYPTION_KEY_ADMIN Server Admin
    INNODB_REDO_LOG_ARCHIVE Server Admin
    APPLICATION_PASSWORD_ADMIN Server Admin
    SHOW_ROUTINE Server Admin
    BACKUP_ADMIN Server Admin
    BINLOG_ADMIN Server Admin
    CLONE_ADMIN Server Admin
    CONNECTION_ADMIN Server Admin
    SET_USER_ID Server Admin
    SERVICE_CONNECTION_ADMIN Server Admin
    GROUP_REPLICATION_ADMIN Server Admin
    REPLICATION_APPLIER Server Admin
    INNODB_REDO_LOG_ENABLE Server Admin
    PERSIST_RO_VARIABLES_ADMIN Server Admin
    TABLE_ENCRYPTION_ADMIN Server Admin
    ROLE_ADMIN Server Admin
    REPLICATION_SLAVE_ADMIN Server Admin
    SESSION_VARIABLES_ADMIN Server Admin
    RESOURCE_GROUP_ADMIN Server Admin
    RESOURCE_GROUP_USER Server Admin
    SYSTEM_USER Server Admin
    SYSTEM_VARIABLES_ADMIN Server Admin
    XA_RECOVER_ADMIN Server Admin

    Listing Privileges Using a Client Program

    Now, let us see how to retrieve/list all the privileges granted to the current MySQL user using a client program in programming languages like Java, PHP, Python, JavaScript, C++ etc.

    Syntax

    Following are the syntaxes −

    To show all the privileges granted to an user, we need to pass the SHOW PRIVILEGES statement as a parameter to the query() function of the PHP mysqli library as −

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

    Following is the syntax to show all the privileges granted to the current user through a JavaScript program −

    sql= "SHOW PRIVILEGES;"
    con.query(sql, function (err, result) {
       if (err) throw err;
          console.log(result);
    });
    

    To show the privileges of the current user, we need to execute the SHOW PRIVILEGES statement using the JDBC executeQuery() function as −

    String sql = "SHOW PRIVILEGES";
    statement.executeQuery(sql);
    

    Following is the syntax to show all the privileges granted to the current MySQL user through a Python program −

    sql = f"SHOW GRANTS FOR ''{username_to_show}''@''localhost''";
    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.
    ''); $sql = "SHOW PRIVILEGES"; if($result = $mysqli->query($sql)){ printf("PRIVILEGES found successfully...!"); printf("Lists are: "); while($row = mysqli_fetch_array($result)){ print_r($row); } } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    PRIVILEGES found successfully...!Lists are: Array
    (
        [0] => Alter
        [Privilege] => Alter
        [1] => Tables
        [Context] => Tables
        [2] => To alter the table
        [Comment] => To alter the table
    )
    Array
    (
        [0] => Alter routine
        [Privilege] => Alter routine
        [1] => Functions,Procedures
        [Context] => Functions,Procedures
        [2] => To alter or drop stored functions/procedures
        [Comment] => To alter or drop stored functions/procedures
    )
    Array
    (
        [0] => Create
        [Privilege] => Create
        [1] => Databases,Tables,Indexes
        [Context] => Databases,Tables,Indexes
        [2] => To create new databases and tables
        [Comment] => To create new databases and tables
    )
    Array
    (
        [0] => Create routine
        [Privilege] => Create routine
        [1] => Databases
        [Context] => Databases
        [2] => To use CREATE FUNCTION/PROCEDURE
        [Comment] => To use CREATE FUNCTION/PROCEDURE
    )
    Array
    (
        [0] => Create role
        [Privilege] => Create role
        [1] => Server Admin
        [Context] => Server Admin
        [2] => To create new roles
        [Comment] => To create new roles
    )
    ..........
    
     (
        [0] => REPLICATION_SLAVE_ADMIN
        [Privilege] => REPLICATION_SLAVE_ADMIN
        [1] => Server Admin
        [Context] => Server Admin
        [2] =>
        [Comment] =>
    )
    Array
    (
        [0] => SENSITIVE_VARIABLES_OBSERVER
        [Privilege] => SENSITIVE_VARIABLES_OBSERVER
        [1] => Server Admin
        [Context] => Server Admin
        [2] =>
        [Comment] =>
    )
    
    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 = "SHOW PRIVILEGES";
      con.query(sql, function(err, result){
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    [
      {
        Privilege: ''Alter'',
        Context: ''Tables'',
        Comment: ''To alter the table''
      },
    .
    .
    .
      {
        Privilege: ''TELEMETRY_LOG_ADMIN'',
        Context: ''Server Admin'',
        Comment: ''''
      }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class ShowPriv {
    	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 st = con.createStatement();
                //System.out.println("Database connected successfully...!");
                String sql = "SHOW PRIVILEGES";
                rs = st.executeQuery(sql);
                System.out.println("All privileges: ");
                while(rs.next()) {
                	String priv = rs.getNString(1);
                	System.out.println(priv);
                }
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Output

    The output obtained is as shown below −

    All privileges:
    Alter
    Alter routine
    Create
    Create routine
    Create role
    Create temporary tables
    Create view
    Create user
    Delete
    Drop
    Drop role
    Event
    Execute
    File
    Grant option
    Index
    Insert
    Lock tables
    Process
    Proxy
    References
    Reload
    Replication client
    Replication slave
    Select
    Show databases
    Show view
    Shutdown
    Super
    
    import mysql.connector
    # creating the connection object
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password''
    )
    username_to_show = ''newUser''
    # Create a cursor object for the connection
    cursorObj = connection.cursor()
    cursorObj.execute(f"SHOW GRANTS FOR ''{username_to_show}''@''localhost''")
    privileges = cursorObj.fetchall()
    print(f"Privileges for user ''{username_to_show}'' are:")
    for grant in privileges:
        print(grant[0])
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Privileges for user ''newUser'' are:
    GRANT USAGE ON *.* TO `newUser`@`localhost`
    GRANT SELECT, INSERT, UPDATE ON `your_database`.* TO `newUser`@`localhost`
    

    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 – 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 – Revoke Privileges nhận dự án làm có lương

    MySQL – REVOKE Statement

    Table of content


    Earlier, we discussed how a root user gets access to a MySQL server with default privileges after installation. These privileges are sufficient for performing basic operations on the data. However, in some special situations, users might need to request the server”s host to take away certain privileges. To do so, we use the MySQL REVOKE statement.

    The MySQ REVOKE statement

    The MySQL REVOKE statement is used to remove certain administrative privileges or roles from users. It revokes permissions that were previously granted.

    Syntax

    Following is the syntax of the MySQL REVOKE Statement −

    REVOKE privileges
       ON database_name.table_name
       FROM ''user''@''host
    

    Example

    Assume we have created a user named ”test_user”@”localhost” in MySQL using the CREATE USER statement as shown below −

    CREATE USER ''test_user''@''localhost'' IDENTIFIED BY ''testpassword
    

    Following is the output produced −

    Query OK, 0 rows affected (0.23 sec)
    

    Now, let us create a database named ”test_database” −

    CREATE DATABASE test_database;
    

    The output produced is as follows −

    Query OK, 1 row affected (0.56 sec)
    

    Next, we will use the created database −

    USE test_database;
    

    We get the output as shown below −

    Database changed
    

    Now, let us create a table in the database −

    CREATE TABLE MyTable(data VARCHAR(255));
    

    The output obtained is as follows −

    Query OK, 0 rows affected (0.67 sec)
    

    Following query grants privileges on the table created above to the user ”test_user”@”localhost −

    GRANT SELECT ON test_database.MyTable TO ''test_user''@''localhost
    

    After executing the above code, we get the following output −

    Query OK, 0 rows affected (0.31 sec)
    

    You can verify the granted privileges using the SHOW GRANTS statements −

    SHOW GRANTS FOR ''test_user''@''localhost
    

    The output we get is as shown below −

    Grants for test_user@localhost
    GRANT USAGE ON *.* TO `test_user`@`localhost`
    GRANT SELECT ON `test_database`.`mytable` TO `test_user`@`localhost`

    Now, you can revoke the above granted privilege using the REVOKE statement as shown below −

    REVOKE SELECT ON test_database.MyTable FROM ''test_user''@''localhost
    

    We get the output as follows −

    Query OK, 0 rows affected (0.25 sec)
    

    Verification

    We can verify whether the SELECT privilege has been revoked or not using the SHOW GRANTS statements as shown below −

    SHOW GRANTS FOR ''test_user''@''localhost
    

    We can see that the output no longer lists the SELECT privilege, indicating that it has been revoked −

    Grants for test_user@localhost
    GRANT USAGE ON *.* TO `test_user`@`localhost`

    Revoking All Privileges

    If a user has multiple privileges with a user, you can revoke all those privileges at once using the REVOKE ALL statement in MySQL.

    Syntax

    Following is the syntax to revoke all privileges in MySQL −

    REVOKE ALL PRIVILEGES ON *.* FROM ''user''@''host
    

    Example

    Assume we have created a user as follows −

    CREATE USER ''sample_user''@''localhost
    

    Following is the output produced −

    Query OK, 0 rows affected (0.18 sec)
    

    We also create a procedure as shown below −

    DELIMITER //
    CREATE PROCEDURE sample ()
       BEGIN
          SELECT ''This is a sample procedure
       END//
    DELIMITER ;
    

    The output obtained is as follows −

    Query OK, 0 rows affected (0.29 sec)
    

    Additionally, we create a table named ”sample” in a database −

    CREATE TABLE sample(data INT);
    

    We get the output as shown below −

    Query OK, 0 rows affected (0.68 sec)
    

    Now, the following queries grants ALTER ROUTINE, EXECUTE privileges on the above created procedure to the user named ”sample_user”@”localhost”.

    GRANT ALTER ROUTINE, EXECUTE
    ON PROCEDURE test_database.sample TO ''sample_user''@''localhost
    

    Output of the above code is as shown below −

    Query OK, 0 rows affected (0.20 sec)
    

    Similarly, following query grants SELECT, INSERT and UPDATE privileges on the table ”sample” to the user ”sample_user”@”localhost −

    GRANT SELECT, INSERT, UPDATE
    ON test.sample TO ''sample_user''@''localhost
    

    The result produced is −

    Query OK, 0 rows affected (0.14 sec)
    

    You can verify the list of all privileges granted for the user using the SHOW GRANTS statement −

    SHOW GRANTS FOR ''sample_user''@''localhost
    

    The result obtained is as follows −

    Grants for sample_user@localhost
    GRANT USAGE ON *.* TO `sample_user`@`localhost`
    GRANT SELECT, INSERT, UPDATE ON `test`.`sample` TO `sample_user`@`localhost`
    GRANT EXECUTE, ALTER ROUTINE ON PROCEDURE `test_database`.`sample` TO `sample_user`@`localhost`

    Finally, to revoke all the privileges granted to ”sample_user”@”localhost”, you can use the following statement −

    REVOKE ALL PRIVILEGES, GRANT OPTION FROM ''sample_user''@''localhost
    

    The result produced is −

    Query OK, 0 rows affected (0.30 sec)
    

    Verification

    After revoking privileges, you can check the user”s grants again −

    SHOW GRANTS FOR ''sample_user''@''localhost
    

    The output below confirms that all privileges have been revoked −

    Grants for sample_user@localhost
    GRANT USAGE ON *.* TO `sample_user`@`localhost`

    Revoking Proxy Privilege

    You can make one user as a proxy of another by granting the PROXY privilege to it. If you do so, both users have the same privileges.

    Example

    Assume we have created users named sample_user, proxy_user in MySQL using the CREATE statement −

    CREATE USER sample_user, proxy_user IDENTIFIED BY ''testpassword
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.52 sec)
    

    Now, we are creating a table ”Employee” −

    CREATE TABLE Employee (
    ID INT, Name VARCHAR(15), Phone INT, SAL INT);
    

    We get the output as shown below −

    Query OK, 0 rows affected (6.47 sec)
    

    Following query grants SELECT and INSERT privileges on the table created above, to the user sample_user

    GRANT SELECT, INSERT ON Emp TO sample_user;
    

    The output obtained is as follows −

    Query OK, 0 rows affected (0.28 sec)
    

    Now, we can assign proxy privileges to the user proxy_user using the GRANT statement as shown below −

    GRANT PROXY ON sample_user TO proxy_user;
    

    The result produced is −

    Query OK, 0 rows affected (1.61 sec)
    

    You can revoke a proxy privilege using the REVOKE PROXY statement as shown below −

    REVOKE PROXY ON sample_user FROM proxy_user;
    

    We get the following result −

    Query OK, 0 rows affected (0.33 sec)
    

    Revoking a Role

    A role in MySQL is a set of privileges with name. You can create one or more roles in MySQL using the CREATE ROLE statement. If you use the GRANT statement without the ON clause, you can grant a role instead of privileges.

    Example

    Following query creates a role named TestRole_ReadOnly

    CREATE ROLE ''TestRole_ReadOnly
    

    Following is the output of the above code −

    Query OK, 0 rows affected (0.13 sec)
    

    Now, let us grant read only privilege to the created role using the GRANT statement −

    GRANT SELECT ON * . * TO ''TestRole_ReadOnly
    

    The result obtained is −

    Query OK, 0 rows affected (0.14 sec)
    

    Then, you can GRANT the created role to a user as follows −

    CREATE USER ''newuser''@''localhost'' IDENTIFIED BY ''password
    

    Output of the above code is as follows −

    Query OK, 0 rows affected (0.14 sec)
    

    Next, you can grant the ”TestRole_ReadOnly” role to the ”newuser”@”localhost”−

    GRANT ''TestRole_ReadOnly'' TO ''newuser''@''localhost
    

    We get the following result −

    Query OK, 0 rows affected (0.13 sec)
    

    Following query revokes the role from the user −

    REVOKE ''TestRole_ReadOnly'' FROM ''newuser''@''localhost
    

    After executing the above code, we get the following output −

    Query OK, 0 rows affected (1.23 sec)
    

    Revoking Privileges Using a Client Program

    We can also revoke privileges from a MySQL user using a client program.

    Syntax

    Following are the syntaxes to revoke MySQL Privileges in various programming languages −

    To revoke all the privileges granted to an user in MySQL database using the PHP program, we need to execute the REVOKE ALL statement as shown below −

    $sql = "REVOKE ALL, GRANT OPTION FROM user_name";
    $mysqli->query($sql);
    

    Following is the syntax to revoke a particular privilege from the desired user using a JavaScript program −

    sql= "REVOKE privilege_name(s) ON object FROM user_account_name";
    con.query(sql, function (err, result) {
       if (err) throw err;
          console.log(result);
    });
    

    To revoke all the privileges granted to a particular user, we need to execute the REVOKE ALL PRIVILEGES statement using the JDBC execute() function as −

    String sql = "REVOKE ALL PRIVILEGES, GRANT OPTION FROM USER_NAME";
    statement.execute(sql);
    

    Following is the syntax to revoke a particular privilege to the desired user using a Python program −

    sql = f"REVOKE {privileges} ON your_database.* FROM ''{username_to_revoke}''@''localhost''";
    cursorObj.execute(sql);
    

    Example

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

    $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.
    ''); $sql = "REVOKE ALL, GRANT OPTION FROM Sarika"; if($result = $mysqli->query($sql)){ printf("Revoke privileges executed successfully...!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Revoke privileges executed 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 = "CREATE USER ''test_user''@''localhost'' IDENTIFIED BY ''testpassword"
      con.query(sql);
    
      sql = "CREATE DATABASE test_database;"
      con.query(sql);
    
      sql = "USE test_database;"
      con.query(sql);
    
      sql = "CREATE TABLE MyTable(data VARCHAR(255));"
      con.query(sql);
    
      sql = "GRANT SELECT ON test_database.MyTable TO ''test_user''@''localhost"
      con.query(sql);
    
      sql = "SHOW GRANTS FOR ''test_user''@''localhost";
      con.query(sql, function(err, result){
        if (err) throw err;
        console.log("**Granted privileges:**");
        console.log(result);
        console.log("--------------------------");
      });
      sql = "REVOKE SELECT ON test_database.MyTable FROM ''test_user''@''localhost"
      con.query(sql);
    
      sql = "SHOW GRANTS FOR ''test_user''@''localhost";
      con.query(sql, function(err, result){
        if (err) throw err;
        console.log("**Grants after revoking:**");
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    **Granted privileges:**
    [
      {
        ''Grants for test_user@localhost'': ''GRANT USAGE ON *.* TO `test_user`@`localhost`''
      },
      {
        ''Grants for test_user@localhost'': ''GRANT SELECT ON `test_database`.`mytable` TO `test_user`@`localhost`''
      }
    ]
    --------------------------
    **Grants after revoking:**
    [
      {
        ''Grants for test_user@localhost'': ''GRANT USAGE ON *.* TO `test_user`@`localhost`''
      }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    public class RevokePriv {
    	public static void main(String[] args) {
    		String url = "jdbc:mysql://localhost:3306/TUTORIALS";
    		String user = "root";
    		String password = "password";
    		try {
    			Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st = con.createStatement();
                //System.out.println("Database connected successfully...!");
                String sql = "REVOKE ALL PRIVILEGES, GRANT OPTION FROM Vivek";
                st.execute(sql);
                System.out.println("You revoked all the privileges form user ''Vivek''");
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Output

    The output obtained is as shown below −

    You revoked all the privileges form user ''Vivek''
    
    import mysql.connector
    # creating the connection object
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password''
    )
    username_to_revoke = ''newUser''
    # privileges we want to revoke
    privileges = ''SELECT, INSERT, UPDATE''
    # Create a cursor object for the connection
    cursorObj = connection.cursor()
    cursorObj.execute(f"REVOKE {privileges} ON your_database.* FROM ''{username_to_revoke}''@''localhost''")
    print(f"Privileges revoked from the user ''{username_to_revoke}'' successfully.")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Privileges revoked from the user ''newUser'' 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 – Unlock User Account nhận dự án làm có lương

    MySQL – Unlock User Account

    Table of content


    Account Locking and Unlocking in MySQL is introduced to increase security of the database by preventing unauthorized transactions or suspicious activities.

    MySQL Unlock User Account

    To check whether an account is unlocked or not, MySQL provides the ”account_locked” attribute in the ”mysql.user” table that will hold either ”Y” or ”N” values respectively. If the attribute holds the ”N” value, then the account is said to be in the unlock mode.

    By default, all the new user accounts created in MySQL are unlocked.

    Unlocking New Accounts

    You can use the CREATE USER… ACCOUNT UNLOCK statement to unlock new accounts created in MySQL. By default, the newly created accounts are always unlocked unless specified otherwise. However, the ACCOUNT UNLOCK clause is mostly used when an account is in the locked state.

    Syntax

    Following is the syntax of CREATE USER… ACCOUNT UNLOCK statement −

    CREATE USER username@hostname
    IDENTIFIED BY ''new_password'' ACCOUNT UNLOCK;
    

    Example

    In the following query, we are creating a new user account in MySQL using the CREATE USER statement −

    CREATE USER testuser@localhost
    IDENTIFIED BY ''qwerty'' ACCOUNT UNLOCK;
    

    Output

    Following is the output of the above code −

    Query OK, 0 rows affected (0.02 sec)
    

    Verification

    We can verify whether the account of the ”testuser” is unlocked or not using the following SELECT statement −

    SELECT User, Host, account_locked
    FROM mysql.user WHERE User = ''testuser
    

    Output of the above code is as shown below −

    User Host account_locked
    testuser localhost N

    Example

    As we have learned above, the newly created user accounts are unlocked by default. Look at the example below −

    CREATE USER demo@localhost IDENTIFIED BY ''000000
    

    Output

    The result produced is as follows −

    Query OK, 0 rows affected (0.02 sec)
    

    Verification

    We can verify whether the newly created account is unlocked by default using the following SELECT statement −

    SELECT User, Host, account_locked
    FROM mysql.user WHERE User = ''demo
    

    The output obtained is as follows −

    User Host account_locked
    demo localhost N

    Unlocking Existing Accounts

    We can use the ALTER USER… ACCOUNT UNLOCK statement unlock existing accounts in MySQL that are locked beforehand.

    Syntax

    Following is the syntax of ALTER USER… ACCOUNT UNLOCK statement −

    ALTER USER username@hostname ACCOUNT UNLOCK;
    

    Example

    We are first retrieving the information of the existing account ”sample”, including its username, host, and the status of its account lock −

    SELECT User, Host, account_locked
    FROM mysql.user WHERE User = ''sample
    

    We can see in the output below that the user account is locked −

    User Host account_locked
    test localhost Y

    Now, we will unlock the existing account ”sample” using the ALTER USER statement −

    ALTER USER sample@localhost ACCOUNT UNLOCK;
    

    Output

    Following is the output of the above query −

    Query OK, 0 rows affected (0.00 sec)
    

    Verification

    We can verify whether the account is unlocked or not using the following SELECT query −

    SELECT User, Host, account_locked
    FROM mysql.user WHERE User = ''sample
    

    As we can see in the below output, the ”sample@localhost” account is now unlocked and can be accessed according to its privileges −

    User Host account_locked
    sample localhost N

    Unlock User Account Using a Client Program

    Now, in this section let us discuss how to unlock a MySQL user using various client programs.

    Syntax

    Following are the syntaxes −

    Following is the syntax to unlock a MySQL user account using PHP −

    $sql = "ALTER USER user_name ACCOUNT UNLOCK";
    $mysqli->query($sql);
    

    Following is the syntax to unlock a MySQL user account using JavaScript −

    sql= "CREATE USER username@hostname IDENTIFIED BY
      ''new_password'' ACCOUNT UNLOCK";
    con.query(sql, function (err, result) {
       if (err) throw err;
          console.log(result);
    });
    

    Following is the syntax to unlock a MySQL user account using Java −

    String sql = "ALTER USER USER_NAME@LOCALHOST ACCOUNT UNLOCK";
    statement.execute(sql);
    

    Following is the syntax to unlock a MySQL user account using Python −

    sql = f"ALTER USER ''{username_to_unlock}''@''localhost'' ACCOUNT UNLOCK";
    cursorObj.execute(sql);
    

    Example

    Following are the programs to unlock users in various programming languages −

    $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.
    ''); $sql = "ALTER USER Sarika ACCOUNT UNLOCK"; if($mysqli->query($sql)){ printf("User has been unlocked successfully..!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    User has been unlocked 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 = "CREATE USER testuser@localhost IDENTIFIED BY ''qwerty'' ACCOUNT UNLOCK;"
      con.query(sql);
    
      sql = "SELECT User, Host, account_locked FROM mysql.user WHERE User = ''testuser";
      con.query(sql, function(err, result){
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    [ { User: ''testuser'', Host: ''localhost'', account_locked: ''N'' } ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    public class UnlockUserAccount {
    	public static void main(String[] args) {
    		String url = "jdbc:mysql://localhost:3306/TUTORIALS";
    		String user = "root";
    		String password = "password";
    		try {
    			Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user, password);
                Statement st = con.createStatement();
                //System.out.println("Database connected successfully...!");
                String sql = "ALTER USER Vivek@localhost ACCOUNT UNLOCK";
                st.execute(sql);
                System.out.println("User ''Vivek'' account unlocked successfully...!");
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Output

    The output obtained is as shown below −

    User ''Vivek'' account unlocked successfully...!
    
    import mysql.connector
    # creating the connection object
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password''
    )
    username_to_unlock = ''newUser''
    # Create a cursor object for the connection
    cursorObj = connection.cursor()
    cursorObj.execute(f"ALTER USER ''{username_to_unlock}''@''localhost'' ACCOUNT UNLOCK")
    print(f"User ''{username_to_unlock}'' account is unlocked successfully.")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    User ''newUser'' account is unlocked 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 Tables nhận dự án làm có lương

    MySQL – Create Tables

    Table of content


    In the MySQL relational database system, SQL is used to store data in the form of structured tables. These tables consist of fields and records. A field represents a column that defines the type of data to be stored in a table, and a record is a row containing the actual data. MySQL provides various queries to interact with the data, allowing you to create tables, update them, delete them, etc.

    MySQL Create Table Statement

    To create a table in MySQL RDBMS in prompt, CREATE TABLE statement is used.

    One can create any number of tables in an SQL Server database. However, a limit exists on the number of objects that can be present in a database. Including tables, views, indexes etc., a database cannot exceed 2,147,483,647 objects. Therefore, a single user-defined table can define a maximum of 1024 columns.

    A MySQL query to create a table must define the structure of a table. The structure consists of the name of a table and names of columns in the table with each column”s data type. Note that each table must be uniquely named in a database.

    To begin with, the table creation command requires the following details −

    • Name of the table.
    • Name of the columns.
    • Definitions for each column.

    Syntax

    Following is the basic SQL syntax to create a MySQL table −

    CREATE TABLE table_name(
       column1 datatype,
       column2 datatype,
       .....
       columnN datatype,
       PRIMARY KEY( one or more columns )
    );
    

    Example

    In the following query, we are creating a table named CUSTOMERS using the CREATE TABLE Statement −

    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, a few items need explanation −

    • Field Attribute AUTO_INCREMENT in MySQL automatically increments the value in the ID column by one for each new record you add. It starts from the next available number.

    • Field Attribute NOT NULL is being used because we do not want this field to be NULL. So, if a user tries to create a record with a NULL value in that field, then MySQL will raise an error.

    • Keyword PRIMARY KEY is used to define a column as a primary key. It ensures that every record in that column is unique. You can also use it for multiple columns by separating them with commas.

    Output

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

    Query OK, 0 rows affected (0.03 sec)
    

    Verification

    Once we have finished creating the table, we can check whether it has been created successfully or not using the following query −

    DESC CUSTOMERS;
    

    The above query displays the structure of the CUSTOMERS table: column names, their datatypes, etc.

    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

    Creating Tables from Command Prompt

    We can create a MySQL table from the command prompt by defining its structure and columns.

    Following are the steps to perform to create a MySQL table from Command Prompt:

    • Firstly, open the command prompt and enter the following command: mysql -u root -p to access the MySQL database management system.

    • After entering the command, enter the password to log into the MySQL server.

    • Then, we can start creating a table using the respected SQL CREATE TABLE query.

    Example

    In the following example, we are creating a MySQL table named CUSTOMERS from command prompt.

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

    NOTE − MySQL does not terminate a command until you give a semicolon (;) at the end of SQL command.

    Output

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

    Query OK, 0 rows affected (0.03 sec)
    

    Verification

    We can verify if the table has been created successfully or not using the following query −

    mysql> DESC CUSTOMERS;
    

    The above query will show the structure and description of the CUSTOMERS table −

    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

    Creating a Table from an Existing Table

    We can create a duplicate table of an existing table including its structure and data, by using the SQL CREATE TABLE and SELECT statements. The duplicate table has the same columns and their definitions, and it also gets filled with the same data as the original table.

    Note − As it is a completely new table, any changes made in it would not be reflected in the original table.

    Syntax

    Following is the syntax for creating a table from another table −

    CREATE TABLE NEW_TABLE_NAME AS
    SELECT [column1, column2...columnN]
    FROM EXISTING_TABLE_NAME
    [WHERE CONDITION];
    

    Here, column1, column2… are the fields of the existing table and the same would be used to create fields of the new table. And the WHERE clause is optional to use.

    Example

    Let us consider an existing table CUSTOMERS in the TUTORIALS database −

    mysql> USE TUTORIALS;
    Database changed
    mysql> SELECT * FROM CUSTOMERS;
    

    Following is the CUSTOMERS table −

    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

    Now, Using the following query, we are creating a new table named SAMPLE with the same structure and records as CUSTOMERS.

    CREATE TABLE SAMPLE AS
    SELECT * FROM CUSTOMERS;
    

    Output

    As we can see in the output, the table SAMPLE is created successfully.

    Query OK, 7 rows affected (0.03 sec)
    Records: 7  Duplicates: 0  Warnings: 0
    

    Verification

    Using the following SELECT statement, let us verify if the new table SAMPLE contains the records or not.

    SELECT * FROM SAMPLE;
    

    As we can in the output below, the SAMPLE table has been created with all the records from the CUSTOMERS table. −

    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

    The IF NOT EXISTS clause

    If you try to create a table with an existing name an error will be generated −

    CREATE TABLE Employee(Name VARCHAR(255));
    ERROR 1050 (42S01): Table ''employee'' already exists
    

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

    CREATE TABLE Test(Name VARCHAR(255));
    Query OK, 0 rows affected (0.69 sec)
    

    Create table into MySQL Database Using a Client Program

    In addition to Create a table into MySQL Database using the MySQL query, we can also perform the CREATE TABLE operation using a client program.

    Syntax

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

    To Create a table in MySQL Database through a PHP program, we need to execute the CREATE TABLE statement using the mysqli function query() as −

    $sql = "CREATE TABLE table_name (column_name column_type)";
    $mysqli->query($sql);
    

    To Create a table in MySQL Database through a Node.js program, we need to execute the CREATE TABLE statement using the query() function of the mysql2 library as −

    sql = "CREATE TABLE table_name (column_name column_type)";
    con.query(sql);
    

    To Create a table in MySQL Database through a Java program, we need to execute the CREATE TABLE statement using the JDBC function executeUpdate() as −

    String sql = "CREATE TABLE table_name (column_name column_type)";
    statement.execute(sql);
    

    To Create a table in MySQL Database through a Pyhton program, we need to execute the CREATE TABLE statement using the execute() function of the MySQL Connector/Python as −

    sql = "CREATE TABLE table_name (column_name column_type)";
    cursorObj.execute(sql);
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''root@123
    $dbname = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    
    if($mysqli->connect_errno ) {
       printf("Connect failed: %s<br />", $mysqli->connect_error);
       exit();
    }
    printf(''Connected successfully.<br />'');
    
    $sql = "CREATE TABLE tutorials_tbl( ".
       "tutorial_id INT NOT NULL AUTO_INCREMENT, "
       "tutorial_title VARCHAR(100) NOT NULL, ".
       "tutorial_author VARCHAR(40) NOT NULL, ".
       "submission_date DATE, ".
       "PRIMARY KEY ( tutorial_id )); ";
    if ($mysqli->query($sql)) {
       printf("Table tutorials_tbl created successfully.<br />");
    }
    if ($mysqli->errno) {
       printf("Could not create table: %s<br />", $mysqli->error);
    }
    $mysqli->close();
    

    Output

    The output obtained is as follows −

    Connected successfully.
    Table tutorials_tbl created successfully.
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
       host: "localhost",
       user: "root",
       password: "*****"
    });
    
      //Connecting to MySQL
      con.connect(function (err) {
      if (err) throw err;
      console.log("Connected!");
      console.log("--------------------------");
    
      //Creating a table
      sql = "CREATE TABLE tutorials_tbl(tutorial_id INT NOT NULL AUTO_INCREMENT,tutorial_title VARCHAR(100) NOT NULL,tutorial_author VARCHAR(40) NOT NULL,submission_date DATE,PRIMARY KEY ( tutorial_id ));"
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log("The table tutorials_tbl is created successfully!");
      });
    });
    
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    The table tutorials_tbl is created successfully!
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class CreateTable {
       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...!");
    
                //Create new table...!
                String sql = "CREATE TABLE tutorials_tbl (ID Int Auto_Increment not null, tutorial_title Varchar(50) Not Null, tutorial_author Varchar(30) Not Null, Primary Key(ID))";
                statement.executeUpdate(sql);
                System.out.println("Table created successfully...!");
    
                ResultSet resultSet = statement.executeQuery("DESCRIBE tutorials_tbl");
                while (resultSet.next()) {
                    System.out.print(resultSet.getNString(1));
                    System.out.println();
                }
                connection.close();
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    Table created successfully...!
    ID
    tutorial_title
    tutorial_author
    
    import mysql.connector
    #establishing the connection
    conn = mysql.connector.connect(
       user=''root'', password=''password'', host=''localhost'', database=''tut''
    )
    #Creating a cursor object
    cursor = conn.cursor()
    #Creating a table
    sql =''''''CREATE TABLE tutorials_tbl(
       tutorial_id INT NOT NULL AUTO_INCREMENT,
       tutorial_title VARCHAR(100) NOT NULL,
       tutorial_author VARCHAR(40) NOT NULL,
       submission_date DATE,
       PRIMARY KEY ( tutorial_id )
    )''''''
    cursor.execute(sql)
    print ("The table tutorials_tbl is created successfully!")
    #Closing the connection
    conn.close()
    

    Output

    Following is the output of the above code −

    The table tutorials_tbl is 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 – Alter Tables nhận dự án làm có lương

    MySQL – ALTER Command

    Table of content


    MySQL ALTER Command

    The MySQL ALTER command is used to modify the structure of an existing table. It allows you to make various changes, such as adding, deleting, or modify columns within the table.

    Additionally, the ALTER command is also used to add and drop different constraints associated with an existing table.

    Since this command modifies the structure of a table, it is a part of Data Definition Language in SQL. This is also where the ALTER command differs from UPDATE command; while ALTER interacts with the structure of a table to modify it, UPDATE only interacts with the data present in the table without disturbing its structure.

    Syntax

    Following is the syntax of ALTER command in MySQL −

    ALTER TABLE table_name [alter_option ...];
    

    Example

    Let us begin with the creation of a table named CUSTOMERS.

    CREATE TABLE CUSTOMERS (
       ID INT,
       NAME VARCHAR(20)
    );
    

    Now, execute the following query to display information about the columns in CUSTOMERS table.

    SHOW COLUMNS FROM CUSTOMERS;
    

    Output

    Following are the details of the columns of the CUSTOMERS table −

    Field Type Null Key Default Extra
    ID int YES NULL
    NAME varchar(20) YES NULL

    Dropping a Column

    To drop a column in an existing table, we use the ALTER TABLE command with DROP clause.

    Example

    In the following example, we are dropping an existing column named ID from the above-created CUSTOMERS table −

    ALTER TABLE CUSTOMERS DROP ID;
    

    Output

    Executing the query above will produce the following output −

    Query OK, 0 rows affected (0.03 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    To verify whether the ID column has been dropped from the CUSTOMERS table, execute the following query −

    SHOW COLUMNS FROM CUSTOMERS;
    

    As we can see in the output below, there is no ID column present. Hence it is dropped.

    Field Type Null Key Default Extra
    NAME varchar(20) YES NULL

    Note: A DROP clause will not work if the column is the only one left in the table.

    Adding a Column

    To add a new column into an existing table, we use ADD keyword with the ALTER TABLE command.

    Example

    In the following query, we are adding a column named ID into an existing table CUSTOMERS.

    ALTER TABLE CUSTOMERS ADD ID INT;
    

    Output

    Executing the query above will produce the following output −

    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Now, the CUSTOMERS table will contain the same two columns that it had when you first created the table. But the newly added ID column will be added at the end of the table by default. In this case, it will add after the NAME column.

    Verification

    Let us verify using the following query −

    SHOW COLUMNS FROM CUSTOMERS;
    

    As we can see in the output below, the newly added ID column is inserted at the end of the table.

    Field Type Null Key Default Extra
    NAME varchar(20) YES NULL
    ID int YES NULL

    Repositioning a Column

    If we want a column to be placed at a specific position within the table, we can use FIRST to make it the first column or AFTER col_name to indicate that the new column should be positioned after the col_name.

    Example

    Consider the previously modified CUSTOMERS table, where the NAME is the first column and ID is the last column.

    In the following query, we are removing the ID column from the table and then adding it back, positioning it as the first column in the table using FIRST keyword −

    ALTER TABLE CUSTOMERS DROP ID;
    ALTER TABLE CUSTOMERS ADD ID INT FIRST;
    

    Output

    Executing the query above will produce the following output −

    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    Now, let us verify the positions of the column in the CUSTOMERS table −

    SHOW COLUMNS FROM CUSTOMERS;
    

    As we can see in the output below, the ID column is positioned first.

    Field Type Null Key Default Extra
    ID int YES NULL
    NAME varchar(20) YES NULL

    Example

    Here, we are removing the ID column from the table and then adding it back, positioning it after the NAME column using the AFTER col_name keyword.

    ALTER TABLE CUSTOMERS DROP ID;
    ALTER TABLE CUSTOMERS ADD ID INT AFTER NAME;
    

    Output

    Executing the query above will produce the following output −

    Query OK, 0 rows affected (0.01 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    Now, let us verify the positions of the column in the CUSTOMERS table −

    SHOW COLUMNS FROM CUSTOMERS;
    

    As we can see in the output below, the ID column is positioned first.

    Field Type Null Key Default Extra
    NAME varchar(20) YES NULL
    ID int YES NULL

    Note: The FIRST and AFTER specifiers work only with the ADD clause. This means that if you want to reposition an existing column within a table, you first must DROP it and then ADD it at the new position.

    Altering a Column Definition or a Name

    In MySQL, to change a column”s definition, we use MODIFY or CHANGE clause in conjunction with the ALTER command.

    Example

    In the query below, we are changing the definition of column NAME from varchar(20) to INT using the MODIFY clause −

    ALTER TABLE CUSTOMERS MODIFY NAME INT;
    

    Output

    Executing the query above will produce the following output −

    Query OK, 0 rows affected (0.04 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    Now, let us verify the definition of the NAME column in the CUSTOMERS table −

    SHOW COLUMNS FROM CUSTOMERS;
    

    As we can observe, the definition for NAME column has been changed to INT.

    Field Type Null Key Default Extra
    NAME int YES NULL
    ID int YES NULL

    Example

    We can also change the column definition using CHANGE, but the syntax is a bit different from MODIFY. After the CHANGE keyword, we specify the name of the column (twice) that we want to change, then specify the new definition.

    Here, we are changing the definition of column ID from INT to varchar(20) using the CHANGE clause −

    ALTER TABLE CUSTOMERS MODIFY ID VARCHAR(20);
    

    Output

    Executing the query above will produce the following output −

    Query OK, 0 rows affected (0.04 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    Now, let us verify the definition of the NAME column in the CUSTOMERS table −

    SHOW COLUMNS FROM CUSTOMERS;
    

    As we can observe, the definition for NAME column has been changed to INT.

    Field Type Null Key Default Extra
    NAME int YES NULL
    ID varchar(20) YES NULL

    Altering a Column”s Default Value

    In MySQL, we can change a default value for any column by using the DEFAULT constraint with ALTER command.

    Example

    In the following example, we are changing the default value of NAME column.

    ALTER TABLE CUSTOMERS ALTER NAME SET DEFAULT 1000;
    

    Output

    Executing the query above will produce the following output −

    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    Now, let us verify the default value of the NAME column in the CUSTOMERS table −

    SHOW COLUMNS FROM CUSTOMERS;
    

    As we can observe, the default value for NAME column has been changed to 1000.

    Field Type Null Key Default Extra
    NAME int YES 1000
    ID varchar(20) YES NULL

    Example

    We can remove the default constraint from any column by using DROP clause along with the ALTER command.

    Here, we are removing the default constraint of NAME column.

    ALTER TABLE CUSTOMERS ALTER NAME DROP DEFAULT;
    

    Output

    Executing the query above will produce the following output −

    Query OK, 0 rows affected (0.01 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    

    Verification

    Now, let us verify the default value of the NAME column in the CUSTOMERS table −

    SHOW COLUMNS FROM CUSTOMERS;
    

    As we can observe, the default value for NAME column has been changed to NULL.

    Field Type Null Key Default Extra
    NAME int YES NULL
    ID varchar(20) YES NULL

    Altering (Renaming) a Table

    To rename a table, use the RENAME option of the ALTER TABLE statement.

    Example

    The following query renames the table named CUSTOMERS to BUYERS.

    ALTER TABLE CUSTOMERS RENAME TO BUYERS;
    

    Output

    Executing the query above will produce the following output −

    Query OK, 0 rows affected (0.02 sec)
    

    Verification

    Now, let us verify the default value of the NAME column in the CUSTOMERS table −

    SHOW COLUMNS FROM BUYERS;
    

    The table has been renamed to BUYERS, as we can see from the columns within it.

    Field Type Null Key Default Extra
    NAME int YES NULL
    ID varchar(20) YES NULL

    Altering Table Using a Client Program

    Besides altering an existing table in a MySQL database with a MySQL query, we can also use a client program to perform the ALTER TABLE operation.

    Syntax

    Following are the syntaxes of Altering a table from MySQL Database in various programming languages −

    To Alter a table From MySQL Database through a PHP program, we need to execute the Alter statement using the mysqli function query() as −

    $sql = "ALTER TABLE table_name";
    $mysqli->query($sql);
    

    To Alter a table From MySQL Database through a Node.js program we need to execute the Alter statement using the query() function of the mysql2 library as −

    sql = "ALTER TABLE table_name";
    con.query(sql);
    

    To Alter a table From MySQL Database through a Java program we need to execute the Alter statement using the JDBC function executeUpdate() as −

    String sql = "ALTER TABLE table_name";
    statement.execute(sql);
    

    To Alter a table From MySQL Database through a Python program we need to execute the Alter statement using the execute() function of the MySQL Connector/Python as −

    sql = "ALTER TABLE table_name";
    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.
    ''); $sql = "ALTER TABLE testalter_tbl DROP i"; if ($mysqli->query($sql)) { printf("table altered successfully.
    "); } if ($mysqli->errno) { printf("table could not alter: %s
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    table altered 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);
    
      //Altering a table
      sql = "ALTER TABLE testalter_tbl  DROP i";
        con.query(sql, function(err){
        if (err) throw err
        console.log("Altered table successfully...");
      });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    Altered table successfully...
    
    import java.sql.*;
    public class AlterTable {
        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...!");
    
                //Alter table statement...!
                String sql = "ALTER TABLE testalter_tbl  DROP i";
                statement.executeUpdate(sql);
                System.out.println("Table altered successfully...!");
                connection.close();
            }
            catch(Exception e){
                System.out.println(e);
            }
        }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    Table altered successfully...!
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    table_name = ''testalter_tbl''
    # ALTER TABLE statement
    alter_statement = ''testalter_tbl  DROP i''
    #Creating a cursor object
    cursorObj = connection.cursor()
    cursorObj.execute(f"ALTER TABLE {table_name} {alter_statement}")
    print(f"Table ''{table_name}'' is altered successfully.")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Table ''testalter_tbl'' is altered 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 – Rename Tables nhận dự án làm có lương

    MySQL – Rename Tables

    Table of content


    There can be a situation where both users and database administrators might want to change the name of a table in a relational database to make the table”s name more suitable for a specific situation.

    MySQL provides two different ways to rename an MySQL table. We can use either the RENAME TABLE or ALTER TABLE statement. In this tutorial, we will understand them with suitable examples.

    MySQL RENAME TABLE Statement

    The MySQL RENAME TABLE statement is used to rename an existing table in a database with another name.

    Syntax

    Following is the basic syntax of the MySQL RENAME TABLE statement −

    RENAME TABLE table_name TO new_name;
    

    Where, table_name is the name of an existing table and new_name is the new name which you want to assign.

    Example

    Let us start by creating a table with name CUSTOMERS in MySQL database using CREATE statement as shown below −

    CREATE TABLE CUSTOMERS (
    	ID INT,
    	NAME VARCHAR(20),
    	AGE INT
    );
    

    Here, we are renaming the above-created CUSTOMERS table to BUYERS using the following query −

    RENAME TABLE CUSTOMERS to BUYERS;
    

    Output

    The table has been renamed without any errors.

    Query OK, 0 rows affected (0.01 sec)
    

    Verification

    Execute the following query to retrieve the description of the CUSTOMERS table −

    DESC CUSTOMERS;
    

    It display an error because, we have changed the CUSTOMERS table name to BUYERS and there is no CUSTOMERS table in our database.

    ERROR 1146 (42S02): Table ''tutorials.customers'' doesn''t exist
    

    Renaming Multiple Tables

    Using the MySQL RENAME TABLE statement, we can also rename multiple tables in a single query.

    Syntax

    Following is the syntax for renaming multiple tables using MySQL RENAME TABLE statement −

    RENAME TABLE old_table1 TO new_table1,
       old_table2 TO new_table2,
       old_table3 TO new_table3;
    

    Example

    In the following example, we are creating three different tables named Cust1, Cust2, and Cust3

    CREATE TABLE Cust1(ID INT);
    CREATE TABLE Cust2(ID INT);
    CREATE TABLE Cust3(ID INT);
    

    Here, we are verifying whether the above tables are created or not using the following query −

    SHOW TABLES;
    

    As we can see in the output below, the above tables have been successfully created.

    Tables_in_tutorials
    cust1
    cust2
    cust3

    Now, let us rename all the above-created tables using the following query −

    RENAME TABLE Cust1 TO Buyer1, Cust2 TO Buyer2, Cust3 TO Buyer3;
    

    Output

    All three tables has been renamed without any errors.

    Query OK, 0 rows affected (0.03 sec)
    

    Verification

    Let us verify the list of the tables again to find whether the table names have been changed or not −

    SHOW TABLES;
    

    As we can see the output below, all three tables have been successfully renamed.

    Tables_in_tutorials
    buyer1
    buyer2
    buyer3

    Renaming a Table using ALTER TABLE statement

    In MySQL, we can also use the RENAME with ALTER TABLE statement to modify the name of an existing table.

    Syntax

    Following is the syntax to rename a table with ALTER TABLE statement −

    ALTER TABLE existing_table_name RENAME TO new_table_name
    

    Example

    In the following query, we are creating a table named PLAYERS.

    CREATE TABLE PLAYERS (
    	ID INT,
    	NAME VARCHAR(20),
    	AGE INT
    );
    

    Now, let us rename the above-created table with a new name TEAMS using the following query −

    ALTER TABLE PLAYERS RENAME TO TEAMS;
    

    Output

    The table has been renamed without any errors.

    Query OK, 0 rows affected (0.02 sec)
    

    Verification

    Execute the following query to retrieve the description of the PLAYERS table −

    DESC PLAYERS;
    

    It will display an error because, we have renamed the PLAYERS table to TEAMS and there is no PLAYERS table in our database.

    ERROR 1146 (42S02): Table ''tutorials.players'' doesn''t exist
    

    Renaming Table Using a Client Program

    In addition to renaming a table in MySQL Database using MySQL query, we can also perform the RENAME TABLE operation on a table using a client program.

    Syntax

    Following are the syntaxes to rename table in MySQL database in various programming languages −

    To rename a table into MySQL database through PHP program, we need to execute RENAME TABLE statement using the mysqli function query() as −

    $sql = "RENAME TABLE old_table_name TO new_table_name";
    $mysqli->query($sql);
    

    To rename a table into MySQL database through Node.js program, we need to execute RENAME TABLE statement using the query() function of the mysql2 library as −

    sql = "RENAME TABLE table_name TO new_name";
    con.query(sql);
    

    To rename a table into MySQL database through Java program, we need to execute RENAME TABLE statement using the JDBC function executeUpdate() as −

    String sql = "RENAME TABLE old_table_name TO new_table_name";
    statement.executeUpdate(sql);
    

    To rename a table into MySQL database through Python program, we need to execute RENAME TABLE statement using the execute() function of the MySQL Connector/Python as −

    sql = "RENAME TABLE old_table_name TO new_table_name"
    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.
    ''); $sql = "RENAME TABLE tutorials_table TO tutorials_tbl "; if ($mysqli->query($sql)) { printf("table renamed successfully.
    "); } if ($mysqli->errno) { printf("table could not rename: %s
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    table renamed 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);
    
      //Selecting a Database
      sql = "USE tutorials"
      con.query(sql);
    
      //Creating DEMO table
      sql = "CREATE TABLE Demo(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255));"
      con.query(sql);
    
      //Inserting records
      sql = "INSERT INTO Demo VALUES(1, ''Shikhar'', ''Dhawan''),(2, ''Jonathan'', ''Trott''),(3, ''Kumara'', ''Sangakkara'');"
      con.query(sql);
    
      //Fetching the DEMO table
      sql = "SELECT * FROM Demo;"
      con.query(sql, function(err, result){
        if (err) throw err
        console.log("**Following is the DEMO table**");
        console.log(result);
        console.log("--------------------------");
      });
    
      //Renaming the DEMO table as PLAYERS
      sql = "RENAME TABLE Demo to Players;"
      con.query(sql, function(err, result){
        if (err) throw err
        console.log("**Renamed the DEMO table as Players**");
        console.log(result);
        console.log("--------------------------");
      });
    
      //Trying to Retrieve the DEMO table, Leads to an error.
      sql = "SELECT * FROM Demo;"
      con.query(sql, function(err, result){
        if (err) throw err
        console.log("Trying to retrieve DEMO table");
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    **Following is the DEMO table**
    [
      { ID: 1, First_Name: ''Shikhar'', Last_Name: ''Dhawan'' },
      { ID: 2, First_Name: ''Jonathan'', Last_Name: ''Trott'' },
      { ID: 3, First_Name: ''Kumara'', Last_Name: ''Sangakkara'' }
    ]
    --------------------------
    **Renamed the DEMO table as Players**
    ResultSetHeader {
      fieldCount: 0,
      affectedRows: 0,
      insertId: 0,
      info: '''',
      serverStatus: 2,
      warningStatus: 0,
      changedRows: 0
    }
    --------------------------
    C:UsersLenovodesktopJavaScriptconnectDB.js:52
        if (err) throw err
                 ^
    
    Error: Table ''tutorials.demo'' doesn''t exist
        at Packet.asError (C:UsersLenovodesktopJavaScriptnode_modulesmysql2libpacketspacket.js:728:17)
        at Query.execute (C:UsersLenovodesktopJavaScriptnode_modulesmysql2libcommandscommand.js:29:26)
        at Connection.handlePacket (C:UsersLenovodesktopJavaScriptnode_modulesmysql2libconnection.js:478:34)
        at PacketParser.onPacket (C:UsersLenovodesktopJavaScriptnode_modulesmysql2libconnection.js:97:12)
        at PacketParser.executeStart (C:UsersLenovodesktopJavaScriptnode_modulesmysql2libpacket_parser.js:75:16)
        at Socket. (C:UsersLenovodesktopJavaScriptnode_modulesmysql2libconnection.js:104:25)
        at Socket.emit (node:events:513:28)
        at addChunk (node:internal/streams/readable:315:12)
        at readableAddChunk (node:internal/streams/readable:289:9)
        at Socket.Readable.push (node:internal/streams/readable:228:10) {
      code: ''ER_NO_SUCH_TABLE'',
      errno: 1146,
      sqlState: ''42S02'',
      sqlMessage: "Table ''tutorials.demo'' doesn''t exist",
      sql: ''SELECT * FROM Demo;'',
      fatal: true
    }
    
    import java.sql.*;
    public class RenameTable {
        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...!");
    
                //Rename tables...!
                String sql = "RENAME TABLE tutorials_tbl TO new_table";
                statement.executeUpdate(sql);
                System.out.println("Table renamed successfully successfully...!");
                connection.close();
            }
            catch(Exception e){
                System.out.println(e);
            }
        }
    }
    

    Output

    The output obtained is as shown below −

    Table renamed successfully successfully...!
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    old_table_name = ''tutorials_tbl''
    new_table_name = ''tutorials_table''
    #Creating a cursor object
    cursorObj = connection.cursor()
    cursorObj.execute(f"RENAME TABLE {old_table_name} TO {new_table_name}")
    print(f"Table ''{old_table_name}'' is renamed to ''{new_table_name}'' successfully.")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Table ''tutorials_tbl'' is renamed to ''tutorials_table'' 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 – Show Tables nhận dự án làm có lương

    MySQL − Show Tables

    Table of content


    MySQL Show Tables Statement

    In MySQL, we use the SHOW TABLES command to retrieve the names of tables that are present in a specific database. This command is useful in various situations, such as:

    • When we want to view names of tables present in a database to verify if a specific table exists or not.

    • When we want to display additional information about each table present in a database, we use the SHOW TABLES command with the MySQL FULL modifier.

    • Additionally, we can use the SHOW TABLES command with WILDCARDS to filter and display only the tables that match a specific pattern.

    Syntax

    Following is the syntax of MySQL SHOW TABLES command−

    SHOW TABLES;
    

    Before proceeding with the examples, assume that the following tables exist in two databases, testdb1 and testdb2:

    Databases testdb1 testdb2
    Tables employee_remarks employee_age
    employee_salary students_marks
    students_attendance
    students_fees
    students_remarks

    Example

    First of all, we are changing the database to testdb1 to perform the SHOW TABLES operation on it.

    mysql> USE testdb1;
    Database changed
    

    Now, execute the following query to list down all the tables from testdb1 database.

    SHOW TABLES;
    

    Output

    Following are the tables that are present in the testdb1 database −

    Tables_in_testdb1
    employee_remarks
    employee_salary
    students_attendance
    students_fees
    students_remarks

    SHOW TABLES with FULL modifier

    In MySQL, we use the optional FULL modifier along with the SHOW TABLES command to display a second output column that contains additional information about the tables present in a database, such as their types: BASE TABLE for a table, VIEW for a view, or SYSTEM VIEW for an INFORMATION_SCHEMA table.

    Example

    In the following query, we are using the FULL modifier along with the SHOW TABLES command to list the tables and their types in the testdb1 database.

    SHOW FULL TABLES;
    

    Output

    Following is the output of the above query −

    Tables_in_testdb1 Table_type
    employee_remarks BASE TABLE
    employee_salary BASE TABLE
    students_attendance BASE TABLE
    students_fees BASE TABLE
    students_remarks BASE TABLE

    SHOW TABLES in different Database

    In MySQL, we can retrieve the list of tables present in another database. To do so, we need to use the IN operator or the FROM clause in conjunction with the SHOW TABLES statement.

    Example

    In the following query, we are fetching the list of tables that exist in another database testdb2, using the SHOW TABLES command with IN operator.

    SHOW TABLES IN testdb2;
    

    Output

    Following are the names of the tables that are present in testdb2 database −

    Tables_in_testdb2
    employee_age
    students_marks

    Example

    We can also perform the above operation using the SHOW TABLES command with FROM clause.

    SHOW TABLES FROM testdb2;
    

    Output

    As we can observe, both outputs are the same.

    Tables_in_testdb2
    employee_age
    students_marks

    SHOW TABLES using Pattern Matching

    In some scenarios where there are large amount of tables present in a database, and we want to retrieve only specific tables, we use the LIKE operator with WILDCARD characters such as ”%”. These wildcards will filter and display only the tables that match a specific pattern.”

    Example

    In the following query, we are using the LIKE operator with SHOW TABLES command to select all the tables (in testdb1 database) where the name starts with “stud”.

    SHOW TABLES IN testdb1 LIKE "stud%";
    

    Output

    Following are the tables present in testdb1 database whose name starts with “stud” −

    Tables_in_testdb1 (stud%)
    students_attendance
    students_fees
    students_remarks

    Example

    Here, we are trying to retrieve the tables from testdb2 database where the name starts with “stud” −

    SHOW TABLES IN testdb2 LIKE "stud%";
    

    Output

    This will produce following result −

    Tables_in_testdb2 (stud%)
    students_marks

    Example

    We are using the SHOW TABLES along with WHERE clause to check if there is a table named “employee_remarks” in testdb1 database −

    SHOW TABLES FROM testdb1 WHERE Tables_in_testdb1 = "employee_remarks";
    

    Output

    This will produce following result −

    Tables_in_testdb1
    employee_remarks

    Showing tables Using a Client Program

    Besides showing the list of tables present in a MySQL database with a MySQL query, we can also use a client program to perform the SHOW TABLES operation.

    Syntax

    Following are the syntaxes to Show list of tables in MySQL Database in various programming languages −

    To show the list of tables in MySQL Database through a PHP program, we need to execute SHOW TABLES statement using the mysqli function query() as −

    $sql = "SHOW TABLES FROM DATABASE";
    $mysqli->query($sql);
    

    To show the list of tables in MySQL Database through a Node.js program, we need to execute SHOW TABLES statement using the query() function of the mysql2 library as −

    sql= "SHOW TABLES FROM DATABASE";
    con.query(sql);
    

    To show the list of tables in MySQL Database through a Java program, we need to execute SHOW TABLES statement using the JDBC function executeUpdate() as −

    String sql = "SHOW TABLES FROM DATABASE";
    statement.executeQuery(sql);
    

    To show the list of tables in MySQL Database through a Java program, we need to execute SHOW TABLES statement using the execute() function of the MySQL Connector/Python as −

    show_table_query = "SHOW TABLES FROM DATABASE"
    cursorObj.execute(show_table_query);
    

    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.
    ''); $sql = "SHOW TABLES FROM TUTORIALS"; if ($result = $mysqli->query($sql)) { printf("Show table executed successfully.
    "); while ($row = mysqli_fetch_array($result)) { print_r($row); } } if ($mysqli->errno) { printf("Could not show table: %s
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Show table executed successfully.
    Array
    (
        [0] => articles
        [Tables_in_tutorials] => articles
    )
    Array
    (
        [0] => courses
        [Tables_in_tutorials] => courses
    )
    Array
    (
        [0] => customers
        [Tables_in_tutorials] => customers
    )
    Array
    (
        [0] => customerss
        [Tables_in_tutorials] => customerss
    )
    Array
    (
        [0] => demo_table
        [Tables_in_tutorials] => demo_table
    )
    Array
    (
        [0] => employee
        [Tables_in_tutorials] => employee
    )
    Array
    (
        [0] => films
        [Tables_in_tutorials] => films
    )
    Array
    (
        [0] => films_watched
        [Tables_in_tutorials] => films_watched
    )
    Array
    (
        [0] => myplayers
        [Tables_in_tutorials] => myplayers
    )
    Array
    (
        [0] => new_tutorial_tbl
        [Tables_in_tutorials] => new_tutorial_tbl
    )
    Array
    (
        [0] => orders
        [Tables_in_tutorials] => orders
    )
    Array
    (
        [0] => persons
        [Tables_in_tutorials] => persons
    )
    Array
    (
        [0] => products
        [Tables_in_tutorials] => products
    )
    Array
    (
        [0] => sales
        [Tables_in_tutorials] => sales
    )
    Array
    (
        [0] => students
        [Tables_in_tutorials] => students
    )
    
    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 = "CREATE DATABASE TUTORIALS;"
      con.query(sql);
    
      sql = "USE TUTORIALS;"
      con.query(sql);
    
      sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR(20) NOT NULL);"
      con.query(sql);
    
      sql = "CREATE TABLE ORDERS (OID INT NOT NULL, CUSTOMER_ID INT);"
      con.query(sql);
    
      sql = "SHOW TABLES;"
      con.query(sql, function(err, result){
        if (err) throw err
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    [
      { Tables_in_tutorials: ''customers'' },
      { Tables_in_tutorials: ''orders'' }
    ]
    
    import java.sql.*;
    public class JDBCconnection {
    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...!");
    
            //show table statement...!
            String sql = "SHOW TABLES FROM TUTORIALS";
            ResultSet resultSet = statement.executeQuery(sql);
            System.out.println("Tables in the current database: ");
            while(resultSet.next()) {
                System.out.print(resultSet.getString(1));
                System.out.println();
            }
            connection.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    Tables in the current database:
    articles
    blackpink
    blog
    courses
    customer
    customers
    data
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    #Creating a cursor object
    cursorObj = connection.cursor()
    cursorObj.execute("SHOW TABLES")
    tables = cursorObj.fetchall()
    print("Tables in the database are:")
    for table in tables:
        print(table[0])
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Tables in the database are:
    books
    novel
    novels
    tutorials_tbl
    

    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