Category: mysql

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

    MySQL – Copy Database

    Table of content


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

    Copy Database in MySQL

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

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

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

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

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

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

    Example

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

    CREATE DATABASE testdb;
    

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

    SHOW DATABASES;
    

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

    Database
    information_schema
    mysql
    performance_schema
    testdb

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

    USE testdb;
    

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

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

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

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

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

    SHOW TABLES;
    

    The table is successfully created in the testdb database.

    Tables_in_testdb
    customers

    Creating Copy database (Manually)

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

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

    CREATE DATABASE testdb_copy;
    

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

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

    C:> CD C:Program FilesMySQLMySQL Server 8.0bin
    

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

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

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

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

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

    mysql -u root -p testdb_copy
    

    Verification

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

    USE testdb_copy;
    

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

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

    SHOW TABLES;
    

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

    Tables_in_testdb
    customers

    Copy Database Without MySQLdump

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

    Example

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

    CREATE DATABASE Tutorials;
    

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

    SHOW DATABASES;
    

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

    Database
    information_schema
    mysql
    performance_schema
    tutorials

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

    USE Tutorials;
    

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

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

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

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

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

    CREATE DATABASE Tutorials_copy;
    

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

    SHOW DATABASES;
    

    The database has been created.

    Database
    information_schema
    mysql
    performance_schema
    tutorials
    tutorials_copy

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

    USE Tutorials_copy;
    

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

    CREATE TABLE Tutorials_copy.customers LIKE Tutorials.customers;
    

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

    INSERT Tutorials_copy.customers SELECT * FROM Tutorials.customers;
    

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

    SHOW TABLES;
    

    Output

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

    Tables_in_tutorials_copy
    customers

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

    Select * from CUSTOMERS;
    

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

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

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

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

    MySQL – Database Info

    Table of content


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

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

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

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

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

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

    Obtaining Database Info from MySQL Prompt

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

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

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

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

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

    mysql -V Command

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

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

    Example

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

    C:WindowsSystem32> mysql -V
    

    Output

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

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

    SHOW DATABASES Command

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

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

    Example

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

    SHOW DATABASES;
    

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

    Database
    information_schema
    mysql
    performance_schema
    tutorials
    tutorials_copy

    SHOW TABLES Command

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

    Example

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

    USE Tutorials;
    

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

    Show Tables;
    

    Output

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

    Tables_in_tutorials
    customers
    employees
    students

    DESC Command

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

    Example

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

    DESC CUSTOMERS;
    

    Following is the structure −

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

    Obtaining the Number of Rows Affected by a Query

    Let is now see how to obtain this information.

    PERL Example

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

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

    PHP Example

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

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

    Listing Tables and Databases

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

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

    PERL Example

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

    PHP Example

    Try the following example to get database info −

    Copy and paste the following example as mysql_example.php −

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

    Output

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

    Connected successfully.
    Default database is tutorials
    

    Getting Server Metadata

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

    Sr.No. Command & Description
    1

    SELECT VERSION( )

    Server version string

    2

    SELECT DATABASE( )

    Current database name (empty if none)

    3

    SELECT USER( )

    Current username

    4

    SHOW STATUS

    Server status indicators

    5

    SHOW VARIABLES

    Server configuration variables


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

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

    MySQL – Create Users

    Table of content


    In MySQL, you can create multiple user accounts to access the database, each with specific authentication detail such as password. These users can be granted specific privileges using SQL statements like CREATE USER for authentication when creating a new user, and GRANT and REVOKE for assigning and removing administrative privileges, respectively.

    The MySQL CREATE USERS Statement

    We can create a new user account using the CREATE USER Statement in MySQL. To execute this statement, the current account must have the CREATE USER privilege or the INSERT privilege for the MySQL system schema.

    Syntax

    Following is the syntax of the MySQL CREATE USER statement −

    CREATE USER ''user_name''@''host_name'' IDENTIFIED BY ''password
    

    Where,

    • user_name is the name of the user you need to create.

    • hostname specifies the host from which the user can connect.

    • password is the user”s password.

    Example

    In the following query, we are creating a user named ”sample” who can only connect from the ”localhost” host and sets their password as ”123456”. Make sure that you have logged in with a user with admin privileges (root) −

    CREATE USER ''sample''@''localhost'' IDENTIFIED BY ''123456
    

    Output

    The output will be displayed as −

    Query OK, 0 rows affected (0.12 sec)
    

    Verification

    You can verify the list of users using the following query −

    SELECT USER FROM MySQL.USER;
    

    The table will be displayed as shown below −

    USER
    mysql.infoschema
    mysql.session
    mysql.sys
    myuser
    openkm
    root
    sample

    Granting Privileges in MySQL

    You can grant all privileges to the created user using the GRANT ALL statement. This allows you to give specific permissions to users for actions like accessing databases, tables, and performing operations, such as SELECT, INSERT, or DELETE, on them.

    Syntax

    Following is the syntax to grant all privileges in MySQL −

    GRANT ALL PRIVILEGES ON database_name.* TO ''username''@''host
    

    Example

    The following query grants the user ”sample” full privileges to perform any action on any database or table when connecting from the ”localhost” host, giving complete control over the MySQL server locally −

    GRANT ALL PRIVILEGES ON * . * TO ''sample''@''localhost
    

    Output

    The output will be displayed as −

    Query OK, 0 rows affected (0.02 sec)
    

    Logging as a Different User

    To log in as a different user in MySQL, you should first exit the current MySQL session if you are already logged in and then execute the command -u user_name -p in your system”s command prompt or terminal, not within the MySQL shell itself.

    Example

    Here, we are executing the -u sample -p command. After running the command, you will be prompted to enter the password for the specified user. Enter the correct password to log in as shown below −

    mysql -u sample -p
    Enter password: ******
    

    Output

    This will log you in as the sample user with the appropriate privileges and permissions as shown below −

    Welcome to the MySQL monitor. Commands end with ; or g.
    Your MySQL connection id is 12
    Server version: 8.0.22 MySQL Community Server - GPL
    
    Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type ''help;'' or ''h'' for help. Type ''c'' to clear the current input statement.
    

    The Expire Clause

    If you use the expire clause, the old password (current password) will expire immediately and the user need to choose new password at first connection.

    Example

    Here, we are first removing the existing user ”sample”@”localhost” −

    DROP user sample@localhost;
    

    We are now creating a new user ”sample”@”localhost” with the password ”MyPassword” while immediately expiring the password, forcing the user to set a new password upon the first login −

    CREATE USER ''sample''@''localhost''
    IDENTIFIED BY ''MyPassword'' PASSWORD EXPIRE;
    

    Now, if you log in as a newly created user, an error will be generated. So, to login as newly created user, open command prompt browse through bin folder of the MySQL directory and execute the following command −

    C:Program FilesMySQLMySQL Server 8.0bin> mysql -u sample@localhost -p
    Enter password: **********
    

    Any MySQL command execution at this point will trigger an error message as shown below −

    select now();
    

    The output obtained is as shown below −

    ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
    

    Since the password is expired, the above error message is generated. To make this right we need to change (reset) the password using the following command −

    SET PASSWORD=''passwordtest
    

    Following is the output produced −

    Query OK, 0 rows affected (0.34 sec)
    

    You can also set an interval for the EXPIRE clause to implement periodic password changes as shown below −

    DROP user sample@localhost;
    CREATE USER ''sample''@''localhost''
       IDENTIFIED BY ''MyPassword''
       PASSWORD EXPIRE INTERVAL 25 DAY
       FAILED_LOGIN_ATTEMPTS 5 PASSWORD_LOCK_TIME 1;
    

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

    Query OK, 0 rows affected (0.20 sec)
    

    User Comment

    You can add comments to the user while creating a user in MySQL using the COMMENT clause. This provides additional information or context about the user.

    Example

    In the following example, we are first removing the existing ”sample”@”localhost” user. Then, we are creating a new ”sample”@”localhost” user while adding a comment to describe the user −

    drop user sample@localhost;
    CREATE USER ''sample''@''localhost'' COMMENT ''Sample information
    

    Output

    The result obtained is as shown below −

    Query OK, 0 rows affected (0.10 sec)
    

    Verification

    You can verify the attributes and comments info using the SELECT query given below −

    SELECT * FROM INFORMATION_SCHEMA.USER_ATTRIBUTES
    WHERE USER=''sample'' AND HOST=''localhost
    

    The result produced is as shown below −

    USER HOST ATTRIBUTE
    sample localhost {“comment”: “Sample information”}

    User Attribute

    You can add attributes to a user in MySQL using the ATTRIBUTE clause when creating a user account. These attributes can store additional information about the user.

    Example

    In here, we are first removing the existing ”sample@localhost” user. Then, we are creating a new ”sample”@”localhost” user with attributes ”attr1” and ”attr2” set to ”val1” and ”val2,” respectively, associated with the user account −

    DROP user sample@localhost;
    CREATE USER ''sample''@''localhost''
    ATTRIBUTE ''{"attr1": "val1", "attr2": "val2"}
    

    The result obtained is as shown below −

    Output

    Query OK, 0 rows affected (0.09 sec)
    

    Verification

    You can verify the attributes and comments info using the SELECT query given below −

    SELECT * FROM INFORMATION_SCHEMA.USER_ATTRIBUTES
    WHERE USER=''sample'' AND HOST=''localhost
    

    The result obtained is as shown below −

    USER HOST ATTRIBUTE
    sample localhost {“attr1”: “val1”, “attr2”: “val2”}

    The IF NOT EXISTS Clause

    If you try to create a user with an existing name, an error will be generated. To prevent this error and ensure the user is created only if it does not already exist, you can use the “IF NOT EXISTS” clause.

    Example

    In the example below we are creating a user ”sample@localhost” without the “IF NOT EXISTS” clause −

    CREATE USER ''sample@localhost
    

    We can see in the below output that an error is generated −

    ERROR 1396 (HY000): Operation CREATE USER failed for ''sample@localhost''@''%''
    

    However, if we use the “IF NOT EXISTS” clause along with the CREATE statement, a new user will be created, and if a user with the given name already exists, the query will be ignored −

    CREATE USER IF NOT EXISTS ''sample@localhost
    

    Following is the output obtained −

    Query OK, 0 rows affected, 1 warning (0.01 sec)
    

    Creating User Using a Client Program

    In addition to creating a user into MySQL Database using the MySQL query, we can also create using a client program.

    Syntax

    Following are the syntaxes to create a MySQL user in various programming languages −

    The MySQL PHP connector mysqli provides a function named query() to execute an SQL query in the MySQL database. To create a user in MySQL, we need to execute the CREATE USER statement using this function as −

    $sql = "CREATE USER ''user_name''@''localhost'' IDENTIFIED WITH mysql_native_password BY ''password''";
    $mysqli->query($sql);
    

    To create a user using a NodeJS program, we need to execute the CREATE USER statement using the function named query() as −

    sql= " CREATE USER [IF NOT EXISTS] account_name IDENTIFIED BY ''password
    con.query(sql, function (err, result) {
       if (err) throw err;
          console.log(result);
    });
    

    To create a user in a MySQL database using Java program, we need to execute the CREATE USER statement using the JDBC function named execute() as −

    sql = "CREATE USER ''USER_NAME''@LOCALHOST INDENTIFIED WITH MYSQL_NATIVE_PASSWORD BY ''PASSWORD''";
    statement.execute(sql);
    

    The MySQL Connector/Python provides a function named execute() to execute an SQL query in the MySQL database. To create a user into a MySQL database, we need to execute the CREATE USER statement using this function as −

    sql = "CREATE USER ''UserNew''@''localhost'' IDENTIFIED BY ''newPassword''";
    cursorObj.execute(sql)
    

    Example

    Following are the client programs to create an user in MySQL −

    $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 = "CREATE USER ''Revathi''@''localhost'' IDENTIFIED WITH mysql_native_password BY ''password''"; if($mysqli->query($sql)){ printf("User created successfully...!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    User created successfully...!
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
       host: "localhost",
       user: "root",
       password: "Nr5a0204@123"
    });
    
    //Connecting to MySQL
    con.connect(function (err) {
       if (err) throw err;
       console.log("Connected!");
       console.log("--------------------------");
    
       //Creating User
       sql = "CREATE USER ''sample''@''localhost'' IDENTIFIED BY ''123456"
       con.query(sql);
    
       //List of users
       sql = "select user from MySQl.user;"
       con.query(sql, function(err, result){
          if (err) throw err
          console.log(result)
       });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    [
      { user: ''mysql.infoschema'' },
      { user: ''mysql.session'' },
      { user: ''mysql.sys'' },
      { user: ''root'' },
      { user: ''sample'' }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    public class CreateUsers {
       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 = "CREATE USER ''Vivek''@''localhost'' IDENTIFIED WITH mysql_native_password BY ''password''";
             st.execute(sql);
             System.out.println("User ''Vivek'' created successfully...!");
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    User ''Vivek'' created successfully...!
    
    import mysql.connector
    # creating the connection object
    connection = mysql.connector.connect(
       host=''localhost'',
       user=''root'',
       password=''password'',
       database=''textx''
    )
    # Create a cursor object for the connection
    cursorObj = connection.cursor()
    cursorObj.execute("CREATE USER ''UserNew''@''localhost'' IDENTIFIED BY ''newPassword''")
    print("User ''newUser'' is created successfully.")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    User ''newUser'' 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 – Drop Users nhận dự án làm có lương

    MySQL – Drop User

    Table of content


    Dropping users in MySQL will remove a user”s access and permissions on a specific database. This is performed by database administrators to maintain security and control over who can interact with the database system, ensuring that only authorized users can access and manipulate the data.

    The MySQL Drop User Statement

    You can drop/delete one or more existing users in MySQL using the DROP USER Statement. Once you delete an account, all privileges of it are deleted. To execute this statement, you need to have CREATE USER privilege.

    Syntax

    Following is the syntax of the DROP USER statement −

    DROP USER [IF EXISTS] ''username''@''hostname
    

    Where, user_name is the name of the MySQL user you need to delete.

    Example

    Suppose, we have created a MySQL user account named ”TestUser” as shown below −

    CREATE USER TestUser@localhost IDENTIFIED BY ''password1
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.04 sec)
    

    You can verify the list of users using the following query −

    SELECT user FROM MySQl.user;
    

    The table will be displayed as shown below −

    user
    TestUser
    mysql.infoschema
    mysql.session
    mysql.sys
    newUser
    root
    sample

    Now, let us delete the ”TestUser” account created above using the DROP USER statement as shown below −

    DROP USER TestUser@localhost;
    

    After executing the above code, we can see the output as shown below −

    Query OK, 0 rows affected (0.02 sec)
    

    Verification

    Once a table is dropped, if you verify the list of the users as shown below using the SELECT statement, you will find that its name is missing from the list −

    SELECT user FROM MySQl.user;
    

    The table obtained is as follows −

    user
    mysql.infoschema
    mysql.session
    mysql.sys
    newUser
    root
    sample

    Removing Multiple Users

    You can also delete multiple users at once using the DROP ROLE statement. Roles are used to manage permissions and access control in a database system. By dropping a role, you revoke all privileges associated with that role. −

    Example

    Let us start by creating two roles ”MyAdmin” and ”MyDeveloper” −

    CREATE ROLE ''MyAdmin'', ''MyDeveloper
    

    The output obtained is as follows −

    Query OK, 0 rows affected (0.01 sec)
    

    Now, let us remove these roles using the DROP ROLE statement −

    DROP ROLE ''MyAdmin'', ''MyDeveloper
    

    This query will effectively delete both roles from the database −

    Query OK, 0 rows affected (0.01 sec)
    

    The IF EXISTS clause

    If you try to drop a MySQL user that doesn”t exist, an error will be generated. To address this issue, MySQL provides the IF EXISTS clause, which can be used with the DROP USER statement.

    Hence, the IF EXISTS clause allows you to drop a user if they exist, and it handles situations where the specified user is not found in the database.

    Example

    In the below query, we are attempting to drop the ”demo” user. However, it results in an error because the user doesn”t exist in the database −

    DROP USER demo@localhost;
    

    The output produced is as shown below −

    ERROR 1396 (HY000): Operation DROP USER failed for ''demo''@''localhost''
    

    If you use the IF EXISTS clause along with the DROP USER statement as shown below, the specified user will be dropped and if a user with the given name doesn”t exist, the query will be ignored −

    DROP USER IF EXISTS demo;
    

    The output obtained is as follows −

    Query OK, 0 rows affected, 1 warning (0.01 sec)
    

    Dropping User Using a Client Program

    In this section we are going to see various client programs to drop an existing user from MySQL.

    Syntax

    Following are the syntaxes to drop a MySQL user in various programming languages −

    The MySQL PHP connector mysqli provides a function named query() to execute an SQL query in the MySQL database. To drop a user from a MySQL database, we need to execute the DROP USER statement using this function as −

    $sql = "DROP USER ''username''@''localhost''";
    $mysqli->query($sql);
    

    To drop a user using a NodeJS program, we need to execute the DROP USER statement using the function named query() as −

    sql= "DROP USER [IF EXISTS] user_name ...";
    con.query(sql, function (err, result) {
       if (err) throw err;
          console.log(result);
    });
    

    To drop an user in a MySQL database using Java program, we need to execute the DROP USER statement using the JDBC function named execute() as −

    String sql = "DROP USER "USER_NAME''@''LOCALHOST''";
    statement.execute(sql);
    

    The MySQL Connector/Python provides a function named execute() to execute an SQL query in the MySQL database. To drop a user from a MySQL dataBase, we need to execute the DROP USER statement using this function as −

    sql = "DROP USER ''UserName''@''localhost''";
    cursorObj.execute(sql);
    

    Example

    Following are the client programs to drop an user in MySQL −

    $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 = "DROP USER ''Revathi''@''localhost''"; if($mysqli->query($sql)){ printf("User dropped successfully...!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    User dropped successfully...!
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "Nr5a0204@123"
    });
    
      //Connecting to MySQL
      con.connect(function (err) {
      if (err) throw err;
      console.log("Connected!");
      console.log("--------------------------");
    
      //Deleting Users
      sql = "DROP USER TestUser1@localhost;"
      con.query(sql);
      sql = "DROP USER TestUser2@localhost;"
      con.query(sql);
    
      //Listing the users after deleting
      sql = "select user from MySQl.user;"
      con.query(sql, function(err, result){
        console.log("**List of Users after deleting:**")
        if (err) throw err
        console.log(result)
      })
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    *List of Users after deleting:**
    [
      { user: ''TestUser3'' },
      { user: ''TestUser4'' },
      { user: ''mysql.infoschema'' },
      { user: ''mysql.session'' },
      { user: ''mysql.sys'' },
      { user: ''root'' },
      { user: ''sample'' }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    public class DropUsers {
    	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 = "DROP USER ''Vivek''@''localhost''";
                st.execute(sql);
                System.out.println("User ''Vivek'' dropped successfully...!");
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Output

    The output obtained is as shown below −

    User ''Vivek'' created successfully...!
    
    import mysql.connector
    # creating the connection object
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password''
    )
    # Create a cursor object for the connection
    cursorObj = connection.cursor()
    cursorObj.execute("DROP USER ''UserNew''@''localhost''")
    print("User ''UserNew'' is dropped successfully.")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    User ''UserNew'' is dropped successfully.
    

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

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

    MySQL – Show Users

    Table of content


    As you might have already known, MySQL is a multi-user database that allows multiple users to work on it simultaneously. But have you ever wondered who these users might be?

    MySQL provides an account to each user that is authenticated with a username and a password. And details of these accounts are stored in the “user” table in the database. This table contains details like username, the host this user is connected from, and other privileges the said user has etc.

    The MySQL SHOW Users

    MySQL does not provide any direct command to show (list out) all the users. However, the details of these user accounts is stored in the “user” table within the database. Hence, we can use the SELECT statement to list out the contents of this table.

    There is no limit for how many users can connect to a MySQL database but the default user is always “root”. And it does not have any password, unless it is set manually.

    Syntax

    Following is the syntax to show users in a MySQL database −

    SELECT * FROM mysql.user;
    

    Example

    To see the structure of this “user” table, use the following query with the DESC command −

    DESC mysql.user;
    

    Now, in this example, we are listing out all the users in the MySQL database local to a system −

    SELECT Host, User, User_attributes, account_locked
    FROM mysql.user;
    

    Output

    The output obtained is as shown below −

    Host User User_attr account_locked
    localhost mysql.infoschema NULL Y
    localhost mysql.session NULL Y
    localhost mysql.sys NULL Y
    localhost root NULL N

    The actual user table contains a lot more columns/fields than what is displayed in this chapter. Here, however, only some information is displayed for simplicity.

    Note that list of these users are local to a system. Hence, not all systems would give the same output (apart from the default users).

    Show Current User

    Not only the list of all users, MySQL also has a provision to see the current user. This is done with the help of user() or current_user() functions.

    Syntax

    Following is the syntax to show the current user −

    SELECT user();
    or
    SELECT current_user();
    

    Example

    Using the following query, let us display the username of the currently logged in user in MySQL database using the user() function −

    SELECT user();
    

    Output

    Following is the output obtained −

    user()
    root@localhost

    Example

    In here, we are using the current_user() function to show the current user −

    SELECT current_user();
    

    Output

    The output obtained is as follows −

    current_user()
    root@localhost

    Show Currently Logged in Users

    The difference between current users and currently logged in users is that, current user is the user that is executing the queries; whereas, currently logged in user list includes all the active users that are connected to the MySQL server at the moment.

    This information can be extracted from the “information_schema.processlist” table using the SELECT statement.

    Example

    In the following query, we are retrieving the information of all the currently logged in users −

    DESC information_schema.processlist;
    

    Output

    Following is the output of the above code −

    Field Type Null Key Default Extra
    ID bigint unsigned NO
    USER varchar(32) NO
    HOST varchar(261) NO
    DB varchar(64) YES
    COMMAND varchar(16) NO
    TIME int NO
    STATE varchar(64) YES
    INFO varchar(65535) YES

    Example

    In here, we are retrieving information of current users, host, database, and command from the information_schema −

    SELECT user, host, db, command
    FROM information_schema.processlist;
    

    Output

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

    user host db command
    root localhost:49958 customers Query
    event_scheduler localhost NULL Daemon

    Show Users Using a Client Program

    We can also display information about the MySQL users using a client program.

    Syntax

    Following are the syntaxes to display information regarding MySQL users in various programming languages −

    To display info regarding user(s) in a MySQL database using a PHP program, we need to execute the SELECT USER statement using the query() function of the PHP mysqli library as −

    $sql = "SELECT USER FROM MYSQL.user";
    $mysqli->query($sql);
    

    To display the user information We need to execute the SELECT * FROM statement using the query() function of mysql2 library using JavaScript (NodeJS) program as follows −

    sql= "SELECT * FROM mysql.user";
    con.query(sql, function (err, result) {
       if (err) throw err;
          console.log(result);
    });
    

    Similarly in Java we can use the JDBC executeQuery() function to execute the SQL query that displays the user info as follows −

    String sql = "SELECT USER FROM MYSQL.USER";
    statement.executeQuery(sql);
    

    The MySQL Connector/Python provides a function named execute() to execute an SQL query in the MySQL database.To show user info in MySQL database, we need to execute the SELECT USER statement using this function as −

    sql = "SELECT user, host FROM mysql.user";
    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 = "SELECT USER FROM MYSQL.user"; if($result = $mysqli->query($sql)){ printf("User found successfully...!"); printf("Users list 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 −

    User found successfully...!Users list are: Array
    (
        [0] => Vivek Verma
        [USER] => Vivek Verma
    )
    Array
    (
        [0] => Revathi
        [USER] => Revathi
    )
    Array
    (
        [0] => Sarika
        [USER] => Sarika
    )
    Array
    (
        [0] => mysql.infoschema
        [USER] => mysql.infoschema
    )
    Array
    (
        [0] => mysql.session
        [USER] => mysql.session
    )
    Array
    (
        [0] => mysql.sys
        [USER] => mysql.sys
    )
    Array
    (
        [0] => root
        [USER] => root
    )
    
    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 Users
      sql = "CREATE USER TestUser1@localhost IDENTIFIED BY ''password1"
      con.query(sql);
      sql = "CREATE USER TestUser2@localhost IDENTIFIED BY ''password2"
      con.query(sql);
      sql = "CREATE USER TestUser3@localhost IDENTIFIED BY ''password3"
      con.query(sql);
      sql = "CREATE USER TestUser4@localhost IDENTIFIED BY ''password4"
      con.query(sql);
    
      //Listing the users
      sql = "SELECT USER FROM mysql.user;"
      con.query(sql, function(err, result){
        if (err) throw err
        console.log("**List of Users:**")
        console.log(result)
      });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    **List of Users:**
    [
      { USER: ''TestUser1'' },
      { USER: ''TestUser2'' },
      { USER: ''TestUser3'' },
      { USER: ''TestUser4'' },
      { USER: ''mysql.infoschema'' },
      { USER: ''mysql.session'' },
      { USER: ''mysql.sys'' },
      { USER: ''root'' },
      { USER: ''sample'' }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class ShowUsers {
    	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 = "CREATE USER ''Vivek''@''localhost'' IDENTIFIED WITH mysql_native_password BY ''password''";
                st.execute(sql);
                System.out.println("User ''Vivek'' created successfully...!");
                String sql1 = "SELECT USER FROM MYSQL.user";
                rs = st.executeQuery(sql1);
                System.out.println("Users: ");
                while(rs.next()) {
                	String users = rs.getNString(1);
                	System.out.println(users);
                }
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Output

    The output obtained is as shown below −

    User ''Vivek'' created successfully...!
    Users:
    Sarika
    Vivek Verma
    Revathi
    Sarika
    Vivek
    mysql.infoschema
    mysql.session
    mysql.sys
    root
    
    import mysql.connector
    # creating the connection object
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
    )
    # Create a cursor object for the connection
    cursorObj = connection.cursor()
    cursorObj.execute("SELECT user, host FROM mysql.user")
    users = cursorObj.fetchall()
    print("Existing users are:")
    for user, host in users:
        print(f"User: {user}, Host: {host}")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Existing users are:
    User: UserNew, Host: localhost
    User: mysql.infoschema, Host: localhost
    User: mysql.session, Host: localhost
    User: mysql.sys, Host: localhost
    User: newUser, Host: localhost
    User: root, Host: 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 – Change Password nhận dự án làm có lương

    MySQL – Change Password

    Table of content


    MySQL provides an account to each user which is authenticated with a username and a password. The default account in MySQL is a root with no password (One can however set a password to the root using a statement). Similarly, other user-defined accounts can have passwords set explicitly using an SQL statement or can have it system generated by MySQL.

    MySQL Change User Password

    Just like any other authenticated accounts, MySQL has a provision to change the user password. But one must make sure that there is currently no application being used by the user. If the password is reset without disconnecting the application, the application cannot connect to the server through this user again.

    We can change the password for a MySQL user account using the following three SQL statements −

    • UPDATE statement

    • SET PASSWORD statement

    • ALTER USER statement

    The UPDATE Statement

    The most basic way to change a user”s password in MySQL is by using the UPDATE statement. This statement is used to update account details, including the account password, from the ”root” account. But, once the modifications are done using this statement, you must use the FLUSH PRIVILEGES statement to reload privileges from the grant table of the MySQL database.

    Syntax

    Following is the syntax to change password using the UPDATE statement −

    UPDATE mysql.user
    SET authentication_string = PASSWORD(password_string)
    WHERE User = user_name AND
          Host = host_name
    FLUSH PRIVILEGES;
    

    Example

    Following example demonstrates how to change the password of a user account using the UPDATE statement. Firstly, we are creating a user account “sample” with a password ”123456” −

    CREATE USER ''sample''@''localhost'' IDENTIFIED BY ''123456
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.02 sec)
    

    Now, you can verify the list of users using the following query −

    SELECT User FROM mysql.user;
    

    The table will be displayed as shown below −

    User
    mysql.infoschema
    mysql.session
    mysql.sys
    root
    sample

    If you have the MySQL version 5.7.6 and later, you can directly modify the mysql.user table with the following query −

    UPDATE user
    SET authentication_string = PASSWORD(''xxxxxx'')
    WHERE User = ''sample'' AND Host = ''localhost
    

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

    Query OK, 1 row affected (0.02 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    

    After making changes to user accounts, you need to use the FLUSH PRIVILEGES statement to apply these changes immediately −

    FLUSH PRIVILEGES;
    

    The output obtained is as shown below −

    Query OK, 0 rows affected (0.01 sec)
    

    The SET PASSWORD statement

    The SET PASSWORD statement is used to set a password for a MySQL account. It contains a “password-verification” clause which lets the system know that the current user password needs to be replaced by another.

    Syntax

    Following is the syntax for the SET PASSWORD statement −

    SET PASSWORD FOR username@localhost = password_string;
    

    You can also change the password using SET PASSWORD without using the FOR clause. To use this syntax however, you must already be logged in on the user account you wish to change the password of −

    SET PASSWORD = password_string;
    

    Example

    Now, using the SET PASSWORD statement, we are changing the password to ”hello” −

    SET PASSWORD = ''hello
    

    Output

    Following is the output of the above code −

    Query OK, 0 rows affected (0.01 sec)
    

    The ALTER USER Statement

    To alter anything regarding a user account in MySQL, including changing passwords, ALTER USER statement is more preferable than SET PASSWORD statement. This statement is not used alone, instead is followed by the IDENTIFIED BY clause to authenticate the new password.

    Note that the user must be connected to the MySQL server for this statement to work.

    Syntax

    Following is the syntax to change the password using the ALTER USER statement −

    ALTER USER username IDENTIFIED BY ''password
    

    Example

    Here, we are changing the password of the sample@localhost account to ”000000” using the ALTER USER query given below −

    ALTER USER sample@localhost IDENTIFIED BY ''000000
    

    Output

    Output of the above code is shown below −

    Query OK, 0 rows affected (0.01 sec)
    

    The password is now changed. To verify, log in to the sample account again using the new password −

    C:WindowsSystem32> mysql -u sample -p
    Enter password: ******
    
    mysql>
    

    Changing User password Using a Client Program

    Besides using MySQL queries to change the user password in MySQL, we can also use client programs like Node.js, PHP, Java, and Python to achieve the same result.

    Syntax

    Following are the syntaxes −

    To change the user”s password MySQL database, we need to execute the ALTER USER statement using this function as −

    $sql = "ALTER USER ''root''@''localhost'' IDENTIFIED BY ''new_password''";
    $mysqli->query($sql);
    

    To change the user”s password MySQL, we need to execute the ALTER USER statement using the function named query() as −

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

    To change the user”s password into MySQL database, we need to execute the ALTER USER statement using the JDBC execute() function as −

    String sql = "ALTER USER ''USER_NAME''@''LOCALHOST'' IDENTIFIED BY ''NEW_PASSWORD''";
    statement.execute(sql);
    

    The MySQL Connector/Python provides a function named execute() to execute an SQL query in the MySQL database. To change the user”s password MySQL database, we need to execute the ALTER USER statement using this function as −

    sql = f"ALTER USER ''{username_to_change}''@''localhost'' IDENTIFIED BY ''{new_password}''";
    cursorObj.execute(sql);
    

    Example

    Following are the client programs to change the user password in MySQL −

    $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 ''root''@''localhost'' IDENTIFIED BY ''password1''"; if($mysqli->query($sql)){ printf("User password has been changed successfully...!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Your password has been changed 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("--------------------------");
    
      //Listing the users
      sql = "SELECT USER FROM mysql.user;"
      con.query(sql, function(err, result){
        if (err) throw err
        console.log("**List of Users:**")
        console.log(result)
        console.log("--------------------------");
      });
    
      sql = "ALTER USER ''sample''@''localhost'' IDENTIFIED BY ''tutorials";
      con.query(sql, function(err){
        if (err) throw err;
        console.log("Password changed Successfully...");
      });
      sql = "FLUSH PRIVILEGES;"
      con.query(sql);
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    **List of Users:**
    [
      { USER: ''mysql.infoschema'' },
      { USER: ''mysql.session'' },
      { USER: ''mysql.sys'' },
      { USER: ''root'' },
      { USER: ''sample'' }
    ]
    --------------------------
    Password changed Successfully...
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    public class ChangePassword {
    	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 ''root''@''localhost'' IDENTIFIED BY ''password1''";
                st.execute(sql);
                System.out.println("User ''root'' password changed successfully...!");
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Output

    The output obtained is as shown below −

    User ''root'' password changed successfully...!
    
    import mysql.connector
    # creating the connection object
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password''
    )
    username_to_change = ''newUser''
    new_password = ''passwordSet!''
    # Create a cursor object for the connection
    cursorObj = connection.cursor()
    cursorObj.execute(f"ALTER USER ''{username_to_change}''@''localhost'' IDENTIFIED BY ''{new_password}''")
    print(f"Password for user ''{username_to_change}'' changed successfully.")
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Password for user ''newUser'' changed 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 – Introduction nhận dự án làm có lương

    MySQL – Introduction

    Table of content


    What is a Database?

    A database is used to store a collection of data (which can either be structured or unstructured). Each database has one or more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.

    Other kinds of data storages can also be used to manage data, such as files on the file system or large hash tables in memory, but data fetching and writing would not be so fast and easy with those type of systems.

    Nowadays, we use relational database management systems (RDBMS) to store and manage huge volume of data. In such a database, the data is stored in a structured way with the help of different tables. Relations are established among these tables using primary keys or other keys known as Foreign Keys.

    A Relational DataBase Management System (RDBMS) is a software that −

    • Enables you to implement a database with tables, columns and indexes.

    • Guarantees the Referential Integrity between rows of various tables.

    • Updates the indexes automatically.

    • Interprets an SQL query and combines information from various tables.

    RDBMS Terminology

    Before we proceed to explain the MySQL database system, let us revise a few definitions related to the database.

    • Database − A database is a collection of tables, with related data.

    • Table − A table is a matrix with data. A table in a database looks like a simple spreadsheet.

    • Column − One column (data element) contains data of one and the same kind, for example the column postcode.

    • Row − A row (= tuple, entry or record) is a group of related data, for example the data of one subscription.

    • Redundancy − Storing data twice, redundantly to make the system faster.

    • Primary Key − A primary key is unique. A key value can not occur twice in one table. With a key, you can only find one row.

    • Foreign Key − A foreign key is the linking pin between two tables.

    • Compound Key − A compound key (composite key) is a key that consists of multiple columns, because one column is not sufficiently unique.

    • Index − An index in a database resembles an index at the back of a book.

    • Referential Integrity − Referential Integrity makes sure that a foreign key value always points to an existing row.

    MySQL Database

    MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. It is developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is becoming so popular because of many good reasons −

    • MySQL is released under an open-source license. So you have nothing to pay to use it.

    • MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages.

    • MySQL uses a standard form of the well-known SQL data language.

    • MySQL works on many operating systems and with many languages including PHP, PERL, C, C++, JAVA, etc.

    • MySQL works very quickly and works well even with large data sets.

    • MySQL is very friendly to PHP, the most appreciated language for web development.

    • MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB).

    • MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL software to fit their own specific environments.

    History of MySQL

    • Development of MySQL by Michael Widenius & David Axmark beginning in 1994.

    • First internal release on 23rd May 1995.

    • Windows Version was released on the 8th January 1998 for Windows 95 and NT.

    • Version 3.23: beta from June 2000, production release January 2001.

    • Version 4.0: beta from August 2002, production release March 2003 (unions).

    • Version 4.1: beta from June 2004, production release October 2004.

    • Version 5.0: beta from March 2005, production release October 2005.

    • Sun Microsystems acquired MySQL AB on the 26th February 2008.

    • Version 5.1: production release 27th November 2008.

    • Oracle acquired Sun Microsystems on 27th January 2010.

    • Version 5.5: general availability on 3rd December 2010

    • Version 5.6: general availability on 5th February 2013

    • Version 5.7: general availability on 21st October 2015

    • Version 8.0: general availability on 19th April 2018

    Before You Begin

    Before you begin this tutorial, you should have a basic knowledge of the information covered in our PHP and HTML tutorials.

    This tutorial focuses heavily on using MySQL in a PHP environment. Many examples given in this tutorial will be useful for PHP Programmers.

    We recommend you check our for your reference.


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

    MySQL – PHP Syntax

    Table of content


    Various programming languages like PERL, C, C++, JAVA, PHP, etc. are used as client programs to request query executions on a MySQL Server. Out of these languages, PHP is the most popular one because of its web application development capabilities.

    A PHP library is like a toolbox for web developers, providing pre-built functions and code snippets to simplify common tasks. It saves time and effort by offering ready-made solutions for tasks such as handling databases, processing forms, and managing files. Developers can easily include these libraries in their PHP projects to boost efficiency and create robust web applications.

    PHP MySQLi Library

    The MySQL PHP connector, often referred to as MySQLi, enables communication between PHP scripts and MySQL databases. It provides a set of functions and methods that allow PHP applications to connect, query, and manipulate data in MySQL databases, providing efficient and secure database interactions in PHP web development.

    This tutorial focuses on using MySQL in a various environments. If you are interested in MySQL with PERL, then you can consider reading the Tutorial.

    How to Install MySQLi

    To install MySQLi on Windows, you can follow these general steps −

    Download PHP:

    • Download the latest version of PHP from the official PHP website (https://www.php.net/downloads.php).
    • Choose the Windows version that matches your system architecture (e.g., 32-bit or 64-bit).
    • Download the ZIP file for the Thread Safe or Non-Thread Safe version, depending on your needs.

    Extract the ZIP File:

    • Extract the contents of the downloaded ZIP file to a location on your computer (e.g., C:php).

    Configure PHP:

    • In the extracted PHP folder, find the “php.ini-development” file.
    • Copy and rename it to “php.ini”.
    • Open “php.ini” in a text editor (e.g., Notepad) and find the line: “;extension=mysqli”. Remove the semicolon (;) at the beginning of the line to uncomment it: “extension=mysqli”.
    • Save the php.ini file.

    Set Environment Variables:

    • Add the PHP installation directory to the system”s PATH environment variable. This allows you to run PHP from any command prompt.
    • To do this, right-click on “This PC” or “Computer” on your desktop or in File Explorer, select “Properties,” and click on “Advanced system settings.” Then, click on the “Environment Variables” button. In the “System variables” section, select the “Path” variable and click “Edit.” Add the path to your PHP installation directory (e.g., C:php).

    Restart your Web Server:

    • If you are using a web server like Apache or Nginx, restart it to apply the changes.

    Verify Installation:

    • Create a PHP file with the following content and save it in your web server”s document root (e.g., C:Apache24htdocs for Apache):
    <?php
    phpinfo();
    ?>
    
  • Open the file in your web browser and search for “mysqli” to verify that the MySQLi extension is now enabled.
  • PHP Functions to Access MySQL

    PHP provides various functions to access the MySQL database and to manipulate the data records inside the MySQL database −

    S.No Function & Description
    1

    mysqli_connect()

    Establishes a connection to the MySQL server.

    2

    mysqli_query()

    Performs a query on the database.

    3

    mysqli_fetch_assoc()

    Fetches a result row as an associative array.

    4

    mysqli_fetch_array()

    Fetches a result row as an associative array, a numeric array, or both.

    5

    mysqli_close()

    Closes a previously opened database connection.

    6

    mysqli_num_rows()

    Gets the number of rows in a result.

    7

    mysqli_error()

    Returns a string description of the last error.

    8

    mysqli_prepare()

    Used for prepared statements to help prevent SQL injection.

    9

    mysqli_fetch_row()

    Fetches a result row as an enumerated array.

    10

    mysqli_insert_id()

    Gets the ID generated in the last query.

    Basic Example

    Following are the steps to connect to a MySQL database, execute a query, process the results, and close the connection using PHP and MySQLi −

    • Define the parameters needed to connect to your MySQL database, such as ”$dbhost” (host name), ”$dbuser” (username), ”$dbpass” (password), and ”$dbname” (database name).
    • Create a new instance of the ”mysqli” class to establish a connection to the MySQL database.
    • Use the ”query” method of the ”mysqli” object to execute a MySQL query.
    • Fetch and process the results returned by the query.
    • Close the connection to the MySQL database when you are done.

    The following example shows a generic syntax of PHP to call any MySQL query.

    <html>
       <head>
          <title>PHP with MySQL</title>
       </head>
    
       <body>
          <?php
             // Include database connection parameters
             $dbhost = "localhost";
             $dbuser = "your_username";
             $dbpass = "your_password";
             $dbname = "your_database";
    
             // Establish a connection to MySQL
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
             if ($mysqli->connect_error) {
                 die("Connection failed: " . $mysqli->connect_error);
             }
    
             // Execute a MySQL query
             $sql = "SELECT * FROM your_table";
             $result = $mysqli->query($sql);
    
             if (!$result) {
                 die("Error: " . $mysqli->error);
             }
    
             // Process the query results
             while ($row = $result->fetch_assoc()) {
                 // Process each row of data
                 echo "ID: " . $row["id"] . " Name: " . $row["name"] . "<br>";
             }
    
             // Close the database connection
             $mysqli->close();
          ?>
       </body>
    </html>
    

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

    MySQL – Features

    Table of content


    MySQL is a type of relational database that stores and manages the data based on Structured Query Language (SQL) queries. Thus, making it a structured database, i.e., the data stored in this relational databases is in the form of tables.

    It is a fast, easy-to-use RDBMS being used for many small and big businesses, it is developed, marketed and supported by a Swedish Company called MySQL AB.

    Features of MySQL

    One of the major reasons MySQL is considered one of the most popular relational databases is because of its abundant features. Let us look at them one by one −

    Open-Source

    MySQL is open-source, which means this software can be downloaded, used and modified by anyone. It is free-to-use and easy-to-understand. The source code of MySQL can be studied, and changed based on the requirements. It uses GPL, i.e. GNU General Public license which defines rules and regulations regarding what can and can”t be done using the application.

    Quick and Reliable

    MySQL stores data efficiently in the memory ensuring that data is consistent, and not redundant. Hence, data access and manipulation using MySQL is quick. It is considered one of the fastest relational databases with higher productivity as well.

    High Performance

    MySQL provides comparatively higher performance without affecting its functionality. It also has a very little memory leakage making it memory efficient as well.

    Scalable

    Scalability refers to the ability of systems to work easily with small amounts of data, large amounts of data, clusters of machines, and so on. MySQL server was developed to work with large databases.

    Data Types

    It contains multiple data types such as unsigned integers, signed integers, float (FLOAT), double (DOUBLE), character (CHAR), variable character (VARCHAR), text, blob, date, time, datetime, timestamp, year, and so on.

    Character Sets

    It supports different character sets, and this includes latin1 (cp1252 character encoding), German, Ujis, other Unicode character sets and so on.

    Secure

    It provides a secure interface since it has a password system which is flexible, and ensures that it is verified based on the host before accessing the database. The password is encrypted while connecting to the server.

    Support for large databases

    It comes with support for large databases, which could contain about 40 to 50 million records, 150,000 to 200,000 tables and up to 5,000,000,000 rows.

    Platform Independent

    MySQL can be run on various operating systems including Windows, Linux, macOS etc. in several programming languages like C, C++, Java, Python, Perl, PHP etc.

    Client and Utility Programs

    MySQL server also comes with many client and utility programs. This includes Command line programs such as ”mysqladmin” and graphical programs such as ”MySQL Workbench”. MySQL client programs are written in a variety of languages. Client library (code encapsulated in a module) can be written in C or C++ and would be available for clients that have C bindings.


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

    MySQL tutorial

    MySQL Tutorial

    Table of content






    MySQL Tutorial

    MySQL is the most popular and a free Open Source Relational Database Management System (RDBMS). An RDBMS system stores the data in the form of tables that might be related to each other. MySQL uses Structured Query Language (SQL) to store, manage and retrieve data, and control the accessibility to the data. It is one of the best RDBMS being used for developing web-based software applications.

    MySQL is written in C and C++. Its SQL parser is written in yacc, but it uses a home-brewed lexical analyzer.

    MySQL works on many system platforms, such as, Linux, macOS, Microsoft Windows, AIX, BSDi, FreeBSD, HP-UX, ArcaOS, eComStation, IBM i, IRIX, NetBSD, Novell NetWare, OpenBSD, OpenSolaris, OS/2 Warp, QNX, Oracle Solaris, Symbian, SunOS, SCO OpenServer, SCO UnixWare, Sanos and Tru64.

    This tutorial will give you quick start with MySQL and make you comfortable with MySQL programming.

    MySQL Examples

    Consider an example table CUSTOMERS created in the MySQL database. This table contains the details of customers like ID, NAME, AGE, ADDRESS, SALARY.

    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

    Since MySQL uses SQL to manage data, it also uses almost all DDL, DML and DCL statements. For instance, the following DML statement lists the records of all customers who are 25 years old.

    SELECT * FROM CUSTOMERS WHERE AGE = 25;
    

    Following records are displayed as a result-set −

    ID NAME AGE ADDRESS SALARY
    2 Khilan 25 Delhi 1500.00
    4 Chaitali 25 Mumbai 6500.00

    MySQL Online Editor

    In this tutorial, we provide a MySQL Online Editor which helps you to Edit and Execute the MySQL code directly from your browser. Click on the run button icon to run the following MySQL code to be executed on the CUSTOMERS table and retrieve the records matching with the given condition.

    SELECT * FROM CUSTOMERS WHERE NAME = ''Chaitali
    

    This Online Editor will save you the time to install the MySQL setup in order to execute any query. Try our now.

    Why to Learn MySQL?

    MySQL is generally faster, more secure and efficient than other relational databases. Some of world”s fastest growing organizations make use of MySQL to efficiently power their high-volume web sites, business-critical systems and packaged software.

    However, whether you choose MySQL for your application or not, totally depends on your organization”s resources and aim. Usually, MySQL is used by smaller businesses that do not have large data sets, because of its cost efficiency and simple setup.

    MySQL Jobs and Opportunities

    MySQL professionals are in high demand as more and more organizations are using this open-source database system for efficient data management. If you have the skills, you could earn an average salary of around $150,000 per year, but it can vary depending on your location, experience, and job role.

    Here are some of the top companies actively looking for MySQL experts for roles like Database Administrator, Database Developer, Database Tester, Data Scientist, ETL Developer, Database Migration Expert, Cloud Database Expert, and more. They need people who can manage and optimize their databases, build data-driven applications, and extract insights from large datasets −

    • Google
    • Amazon
    • Netflix
    • Infosys
    • Tata Consultancy Services (TCS)
    • Tech Mahindra
    • Wipro
    • Pinterest
    • Uber
    • Wipro
    • Trello
    • And many more…

    To get started, you can use our user-friendly tutorials, which are designed to help you learn MySQL and prepare for technical interviews or certification exams. You can learn at your own pace, anytime and anywhere.

    With the right MySQL skills and knowledge, you can kickstart a rewarding career in the ever-expanding field of data management and analytics. You could be the part of the professionals who are driving innovation and data-driven decision-making in some of the world”s most renowned companies.

    Who Should Learn MySQL

    This MySQL tutorial has been prepared for beginners to help them understand the basics to advanced concepts related to MySQL database.

    Prerequisites to Learn MySQL

    Before you start doing practice with various types of examples given in this reference, I”m making an assumption that you are already aware about what is database, especially RDBMS and what is a computer programming language.

    Frequently Asked Questions about MySQL

    Following are very Frequently Asked Questions(FAQ) about MySQL, and this section tries to answer them briefly.

    MySQL is a popular open-source relational database management system (RDBMS). It organizes data into tables with rows and columns. Users can interact with MySQL using SQL (Structured Query Language) to perform operations like inserting, updating, and querying data. The system works by processing SQL commands to manage and retrieve data efficiently.

    MySQL was developed by Swedish company MySQL AB, founded by David Axmark, Allan Larsson, and Michael “Monty” Widenius. It was later bought by Sun Microsystems in 2008, which was subsequently acquired by Oracle Corporation in 2010.

    You can install MySQL from the MySQL Installer Community, along with other MySQL products you require. The MySQL Installer will allow you to install a certain version of MySQL or you can customize the installation as per your requirements. For more detailed information on how to install MySQL, .

    Since MySQL uses SQL to store and manage the data, the data types used in MySQL are also the same as data types in SQL. Following are three categories of SQL data types.

    • String Data types.
    • Numeric Data types.
    • Date and time Data types.

    Here are the summarized list of tips which you can follow to start learning MySQL.

    • Install MySQL database on your computer system.
    • Follow our tutorial step by step from the very beginning.
    • Read more articles, watch online courses or buy a book on MySQL to enhance your knowledge.
    • Try to develop a small software using PHP or Python which makes use of the MySQL database.

    The time it takes to learn MySQL varies, but basic proficiency can be gained in a few weeks with consistent practice. Mastering more advanced features may take a few months of dedicated learning and hands-on experience. Regular practice and real-world application contribute to the speed of learning MySQL.

    The latest version of MySQL was 8.0. Upgrading to the latest version is recommended for security and feature enhancements.

    To check the MySQL version in Linux, you can use the following command in the terminal:

    • mysql –version

    This command will display the MySQL client version. If you want to check the server version, you can use:

    • mysql -u your_username -p -e “SELECT version();”

    Replace “your_username” with your MySQL username, and you will be prompted to enter your password. After entering the password, the command will display the MySQL server version.

    To access your MySQL database, you can use the MySQL command-line client or a graphical user interface (GUI) tool. Here are the basic steps for both:

    Using MySQL Command-Line Client

    • Open terminal/command prompt.
    • Enter: mysql -u your_username -p.
    • Enter your password when prompted.

    Using GUI Tool (e.g., MySQL Workbench)

    • Download and install the tool.
    • Create a new connection with your details.
    • Test the connection.
    • Use the GUI to manage your MySQL database.

    MySQL is a popular open-source relational database management system (RDBMS) known for its ease of use and scalability. Its main features include support for SQL queries, efficient data storage and retrieval, and robust transaction management, making it suitable for a wide range of applications, from small websites to large enterprise systems. Additionally, MySQL offers strong security measures and a vibrant community for support and development.

    To start, stop, or restart the MySQL server, you can use the command-line interface. The exact commands may vary depending on your operating system. Here are instructions for different operating systems:

    Windows:

    • To Start MySQL Server: Open a command prompt with administrator privileges and run the following command: net start mysql.
    • To Stop MySQL Server: Open a command prompt with administrator privileges and run the following command: net stop mysql.
    • To Restart MySQL Server: You can stop and start the MySQL service using the commands mentioned above. Alternatively, you can use the MySQL Notifier or the Services application to restart the MySQL service.

    Linux (Ubuntu/Debian):

    • To Start MySQL Server: sudo service mysql start.
    • To Stop MySQL Server: sudo service mysql stop.
    • To Restart MySQL Server: sudo service mysql restart.

    macOS:

    • To Start MySQL Server: sudo brew services start mysql.
    • To Stop MySQL Server: sudo brew services stop mysql.
    • To Restart MySQL Server: sudo brew services restart mysql.

    These are general commands, and depending on your specific setup, you might need to adjust them. Also, note that on Linux, the service management commands may vary depending on the distribution (e.g., Ubuntu, CentOS).

    Remember to replace “mysql” with the actual service name if it”s different in your system.

    A MySQL schema can simply be defined as a blueprint of the database. It stores all the information of the tables, its attributes and entities. As MySQL is a relational database management system, it is important to have schema as it also represents the relationship between the attributes and entities of multiple tables.

    As a beginner, you can use our simple and the best MySQL tutorial to learn MySQL. We have removed all the unnecessary complexity while teaching you these MySQL concepts. You can start learning it now: .

    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