Category: mysql

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

    MySQL – Python Syntax

    Table of content


    The MySQL-Python connector specifically refers to a library in Python that enables communication between a Python program and a MySQL database. It acts as a bridge, allowing Python programs to interact with and manipulate data stored in a MySQL database. Essentially, the MySQL-Python connector simplifies the process of connecting, querying, and managing databases, enabling developers to seamlessly integrate their Python applications with MySQL databases.

    Installing “python-mysql” connector

    To use MySQL with Python, you typically need to install a MySQL connector or library. Here are the general steps to install it −

    Step 1: Install MySQL Server

    Make sure you have MySQL Server installed on your machine or have access to a remote MySQL server.

    Step 2: Install MySQL Connector for Python

    Open a command prompt or terminal and use the following command to install the MySQL Connector for Python using pip, which is the package installer for Python:

    pip install mysql-connector-python
    

    If you are using Python 3, you might need to use ”pip3” instead of ”pip”.

    Step 3: Verify Installation

    After the installation is complete, you can verify that the library is installed by opening a Python interactive shell and trying to import the connector:

    import mysql.connector
    

    Python Functions to Access MySQL

    When working with MySQL in Python, the ”mysql-connector-python” library provides various functions to interact with a MySQL database. Here are some important functions commonly used −

    S.No Function & Description
    1

    connect()

    Establishes a connection to the MySQL server.

    2

    cursor()

    Creates a cursor object to execute SQL queries.

    3

    execute(query, params=None)

    Executes a SQL query. ”params” is an optional parameter for query parameters.

    4

    fetchone()

    Fetches the next row from the result set.

    5

    fetchall()

    Fetches all rows from the result set.

    6

    commit()

    Commits the current transaction to the database.

    7

    rollback()

    Rolls back the current transaction, undoing any changes since the last commit.

    8

    close()

    Closes the cursor and the connection to the database.

    9

    executemany()

    Executes a SQL command against all parameter sequences in the provided list.

    Basic Example

    To connect and communicate with a MySQL database using Python, you can follow these steps −

    • Use ”pip install mysql-connector-python” to install the MySQL Connector for Python.
    • Import the MySQL Connector module in your Python script: “import mysql.connector”.
    • Create a connection using “mysql.connector.connect()” with your database details.
    • Create a cursor using “connection.cursor()”.
    • Use the cursor”s “execute()” method to run SQL queries.
    • If applicable, use “fetchone()” or “fetchall()” to retrieve query results.
    • If you modify data, commit changes using “connection.commit()”.
    • Close the cursor and connection with “cursor.close()” and “connection.close()”.

    The following example shows a generic syntax of a Python program to call any MySQL query −

    import mysql.connector
    # Establish connection
    connection = mysql.connector.connect(host=''localhost'', user=''user'', password=''pass'', database=''db'')
    # Create cursor
    cursor = connection.cursor()
    # Execute query
    cursor.execute("SELECT * FROM table")
    # Fetch and print results
    rows = cursor.fetchall()
    print(rows)
    # Close cursor and connection
    cursor.close()
    connection.close()
    

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

    MySQL – Connection

    Table of content


    While working with MySQL database, we use a client program to communicate with the database server. To do so, we must first establish a connection between them.

    To connect a client program with MySQL server, we must ensure all the connection parameters are properly used. These parameters work just like any other login parameters: consisting of a username and a password. Where, a username is the name of the host where the server is running and a password needs to be set according to the user.

    Generally, each connection parameter holds a default value, but we can override them either on the command line or in an option file.

    This tutorial only uses the mysql client program to demonstrate the connection, but these principles also apply to other clients such as mysqldump, mysqladmin, or mysqlshow.

    Set Password to MySQL Root

    Usually, during the installation of MySQL server, we will be asked to set an initial password to the root. Other than that, we can also set the initial password using the following command −

    mysql -u root password "new_password";
    

    Where, new_password is the password set initially.

    Reset Password

    We can also change the existing password using the SET PASSWORD statement. However, we can only do so after logging in to the user account using the existing password. Look at the query below −

    SET PASSWORD FOR ''root''@''localhost'' = PASSWORD(''password_name'');
    FLUSH PRIVILEGES;
    

    Every time a connection is needed to be established, this password must be entered.

    MySQL Connection Using MySQL Binary

    We can establish the MySQL database using the mysql binary at the command prompt.

    Example

    Here is a simple example to connect to the MySQL server from the command prompt −

    [root@host]# mysql -u root -p
    Enter password:******
    

    This will give us the ”mysql>” command prompt where we will be able to execute any SQL query. Following is the result of above command −

    The following code block shows the result of above code −

    Welcome to the MySQL monitor.  Commands end with ; or g.
    Your MySQL connection id is 2854760 to server version: 5.0.9
    
    Type ''help;'' or ''h'' for help. Type ''c'' to clear the buffer.
    

    In the above example, we have used root as a user but we can use any other user as well. Any user will be able to perform all the SQL operations, which are allowed to that user.

    We can disconnect from the MySQL database any time using the exit command at mysql> prompt.

    mysql> exit
    Bye
    

    MySQL Connection Using PHP Script

    We can open/establish connection to MySQL database using the PHP mysqli() constructor or, mysqli_connect() function. This function takes six parameters and returns a MySQL link identifier on success or FALSE on failure.

    Syntax

    Following is the syntax to open a MySQL connection using the constructor mysqli() −

    $mysqli = new mysqli($host, $username, $passwd, $dbName, $port, $socket);
    

    Parameters

    Following are its parameters −

    Sr.No. Parameter & Description
    1

    $host

    Optional − The host name running the database server. If not specified, then the default value will be localhost:3306.

    2

    $username

    Optional − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process.

    3

    $passwd

    Optional − The password of the user accessing the database. If not specified, then the default will be an empty password.

    4

    $dbName

    Optional − database name on which query is to be performed.

    5

    $port

    Optional − the port number to attempt to connect to the MySQL server.

    6

    $socket

    Optional − socket or named pipe that should be used.

    Closing the Connection

    We can disconnect from the MySQL database anytime using another PHP function close(). Following is the syntax −

    $mysqli->close();
    

    Example

    Try the following example to connect to a MySQL server. Save the file as mysql_example.php −

    <html>
       <head>
          <title>Connecting MySQL Server</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass);
    
             if($mysqli->connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli->connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
             $mysqli->close();
          ?>
       </body>
    </html>
    

    Output

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

    Connected successfully.
    

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

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

    MySQL – Create Database

    Table of content


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

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

    MySQL CREATE Database Statement

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

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

    Syntax

    Following is the syntax to create a database in MySQL

    CREATE DATABASE DatabaseName;
    

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

    Example

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

    CREATE DATABASE TUTORIALS;
    

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

    Verification

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

    SHOW DATABASES;
    

    Following are the list of databases present in the server −

    Database
    information_schema
    mysql
    performance_schema
    tutorials

    CREATE Database with IF NOT EXISTS clause

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

    CREATE DATABASE myDatabase
    

    An error will be generated as shown below −

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

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

    CREATE DATABASE IF NOT EXISTS myDatabase
    

    Create Database Using mysqladmin

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

    Example

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

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

    This will create a MySQL database called TUTORIALS.

    Creating Database Using a Client Program

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

    Syntax

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

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

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

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

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

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

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

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

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

    Example

    Following are the programs −

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

    Output

    The output obtained is as follows −

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

    Output

    The output produced is as follows −

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

    Output

    The output obtained is as shown below −

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

    Output

    Following is the output of the above code −

    Database Created Successfully
    

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

  • Khóa học miễn phí MySQL – 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