Category: mysql

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

    MySQL – Boolean Datatype

    Table of content


    A Boolean data type is used to represent truth values of logic and Boolean algebra. It has two possible values: either true or false.

    For example, if a customer wants to see all the bikes that are black in colour, we can filter them using BOOLEAN operator, as given in the following table −

    Boolean

    Here, ”IS_BLACK” is the BOOLEAN column that returns either true or false values based on the colours of the bikes.

    Boolean in MySQL

    In MySQL, there is no built-in Boolean or Bool data type. Instead MySQL provides us with the TINYINT datatype to store the Boolean values.

    MySQL considers the value 0 as FALSE and 1 as TRUE. We can also store NULL values using the TINYINT datatype.

    The Boolean values (such as TRUE and FALSE) are not case-sensitive.

    Syntax

    Following is the syntax of the BOOLEAN operator in MySQL −

    CREATE TABLE table_name (
       Column_name BOOLEAN
    );
    

    Example

    In MySQL, 0 is defined as FALSE and any non-zero values are defined as TRUE −

    SELECT TRUE, FALSE;
    

    Output

    As we can see in the output below, TRUE and FALSE are represented as 1 and 0 −

    TRUE FALSE
    1 0

    Example

    In MySQL, the Boolean values (TRUE and FALSE) are case-insensitive −

    SELECT true, false, TRUE, FALSE, True, False;
    

    Output

    The output produced is as given below −

    true false TRUE FALSE True False
    1 0 1 0 1 0

    Example

    Now, let”s create a table with the name CUSTOMERS using the following query. Here, the AVAILABILITY column specifies whether the customer is available or not. If the bit value is 0 (FALSE), the customer is not available. If it is 1(TRUE), the customer is available −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
       NAME VARCHAR(40),
       AVAILABILITY BOOLEAN
    );
    

    Following is the output produced −

    Query OK, 0 rows affected (0.02 sec)
    

    To get the information about the CUSTOMERS table, use the following query −

    DESCRIBE CUSTOMERS;
    

    If we look at the AVAILABILITY column, which has been set to BOOLEAN while creating the table, it now shows type of TINYINT −

    Field Type Null Key Default Extra
    ID int NO PRI NULL auto_increment
    NAME varchar(40) YES NULL
    AVAILABILITY tinyint(1) YES NULL

    Now, let us insert some records into the CUSTOMERS table using the following INSERT query −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', FALSE),
    (2, ''Khilan'', TRUE),
    (4, ''Kaushik'', NULL);
    

    Using the below query, we can display all the values in the table −

    SELECT * FROM CUSTOMERS;
    

    We can see the values in the AVAILABILITY column are set to 0 and 1 respectively. −

    ID NAME AVAILABILITY
    1 Ramesh 0
    2 Khilan 1
    4 Kaushik NULL

    Replacing BOOLEAN 0,1 with TRUE and FALSE

    As we can see in the above CUSTOMERS table, the BOOLEAN data type shows 0 and 1 values instead of TRUE and FALSE. In MySQL, we can convert BOOLEAN data type to TRUE and FALSE values using the CASE statement.

    The MySQL CASE statement is a conditional statement that goes through conditions and return a values when the first condition is met. Therefore, once a condition is true, it will stop reading the next piece of code and return the result.

    If no conditions are true, it will return the value in the ELSE clause. If no ELSE clause is present and no conditions are true, it returns NULL.

    Syntax

    Following is the syntax of CASE statement in MySQL −

    CASE
       WHEN condition1 THEN result1
       WHEN condition2 THEN result2
       ...
       WHEN conditionN THEN resultN
       ELSE result
    END;
    

    Example

    To get a better understanding, let us consider the BIKES table created using the query below −

    CREATE TABLE BIKES (
       S_NO INT AUTO_INCREMENT PRIMARY KEY,
       COMPANY VARCHAR(40) NOT NULL,
       PRICE INT NOT NULL,
       COLOUR VARCHAR(40) NOT NULL,
       IS_BLACK BOOLEAN
    );
    

    Example

    Output of the above code is as follows −

    Query OK, 0 rows affected (0.03 sec)
    

    Now, let us insert values into the BIKES table using the INSERT statement as shown below −

    INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK)
    VALUES (''Royal Enfield'', 300000, ''Black'', 1);
    INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK)
    VALUES (''BMW'', 900000, ''Blue'', 0);
    INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK)
    VALUES (''Jawa'', 150000, ''Black'', 1);
    INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK)
    VALUES (''Triumph'', 1200000, ''Red'', 0);
    

    The BIKES table obtained is as follows −

    S_NO COMPANY PRICE COLOUR IS_BLACK
    1 Royal Enfield 300000 Black 1
    2 BMW 900000 Blue 0
    3 Jawa 150000 Black 1
    4 Triumph 1200000 Red 0

    Now, let us display all the records from the BIKES table, where the colour BLACK is represented by either TRUE or FALSE −

    SELECT *,
    CASE IS_BLACK
    WHEN 1 THEN ''TRUE''
    WHEN 0 THEN ''FALSE''
    END AS IS_BOOLEAN
    FROM BIKES;
    

    Output

    The output is displayed as follows −

    S_NO COMPANY PRICE COLOUR IS_BLACK IS_BOOLEAN
    1 Royal Enfield 300000 Black 1 TRUE
    2 BMW 900000 Blue 0 FALSE
    3 Jawa 150000 Black 1 TRUE
    4 Triumph 1200000 Red 0 FALSE

    Example

    In the following query, we are filtering the records from the BIKES table where colour black is TRUE −

    SELECT * FROM BIKES WHERE IS_BLACK IS TRUE;
    

    Output

    As we can see the output below, Royal Enfield and Jawa are black in color (true) −

    S_NO COMPANY PRICE COLOUR IS_BLACK
    1 Royal Enfield 300000 Black 1
    3 Jawa 150000 Black 1

    Example

    In here, we are filtering the records from the BIKES table where color black is FALSE −

    SELECT * FROM BIKES WHERE IS_BLACK IS FALSE;
    

    Output

    The output says that BMW and Triumph are not black in colour(false) −

    S_NO COMPANY PRICE COLOUR IS_BLACK
    2 BMW 900000 Blue 0
    4 Triumph 1200000 Red 0

    Boolean Operator Using a Client Program

    In addition to perform the Boolean Operator in MySQL table using MySQL query, we can also perform the another operation on a table using a client program.

    MySQL provides various Connectors and APIs using which you can write programs (in the respective programming languages) to communicate with the MySQL database. The connectors provided are in programming languages such as, Java, PHP, Python, JavaScript, C++ etc. This section provides programs to execute Boolean Operator in MySQL Table.

    Syntax

    Following are the syntaxes of the MySQL Boolean Operator in various programming languages −

    The MySQL PHP connector mysqli provides a function named query() to execute an SQL query in the MySQL database. Depending on the type of query, it retrieves data or performs modifications within the database.

    This function accepts two parameters namely −

    • $sql: This is a string value representing the query.
    • $resultmode: This is an optional parameter which is used to specify the desired format of the result. Which can be MYSQLI_STORE_RESULT (buffered result set object) or, MYSQLI_USE_RESULT (unbuffered result set object) or, MYSQLI_ASYNC.

    To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −

    $sql = "CREATE TABLE table_name ( Column_name BOOLEAN )";
    $mysqli->query($sql);
    

    The MySQL NodeJS connector mysql2 provides a function named query() to execute an SQL query in the MySQL database. This function accepts a string value as a parameter representing the query to be executed.

    To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −

    sql= "CREATE TABLE table_name ( Column_name BOOLEAN )";
    con.query(sql);
    

    We can use the JDBC type 4 driver to communicate to MySQL using Java. It provides a function named execute() to execute an SQL query in the MySQL database. This function accepts a String value as a parameter representing the query to be executed.

    To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −

    String sql = "CREATE TABLE table_name ( Column_name BOOLEAN )";
    statement.execute(sql);
    

    The MySQL Connector/Python provides a function named execute() to execute an SQL query in the MySQL database. This function accepts a string value as a parameter representing the query to be executed.

    To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −

    query = "CREATE TABLE table_name (Column_name BOOLEAN)"
    cursorObj.execute(query);
    

    Example

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

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $dbname = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if($mysqli->connect_errno ) {
       printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); //create table with boolean column $sql = ''CREATE TABLE CUSTOMERS ( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(40), AVAILABILITY BOOLEAN); $result = $mysqli->query($sql); if($result){ printf("Table created successfully...!n"); } //insert data into created table $q = "INSERT INTO CUSTOMERS(ID, NAME, AVAILABILITY) VALUES (1, ''Ramesh'', TRUE)"; If($res = $mysqli->query($q)){ printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM CUSTOMERS"; If($r = $mysqli->query($s)){ printf("Select query executed successfully...!n"); printf("Table records: n"); while($row = $r->fetch_assoc()) { printf("Id %d, Name: %s, AVAILABILITY: %s", $row["ID"], $row["NAME"], $row["AVAILABILITY"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table created successfully...!
    Data inserted successfully...!
    Select query executed successfully...!
    Table records:
    Id 1, Name: Ramesh, AVAILABILITY: 1
    
    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("--------------------------");
    
      //Select database
      sql = "CREATE DATABASE TUTORIALS";
      con.query(sql);
    
      //Select database
      sql = "USE TUTORIALS";
      con.query(sql);
    
      //Creating CUSTOMERS table
      sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(40), AVAILABILITY BOOLEAN);"
      con.query(sql , function(err){
        if (err) throw err;
        console.log("Table created Successfully...");
      });
    
      //Inserting Records
      sql = "INSERT INTO CUSTOMERS(ID, NAME, AVAILABILITY) VALUES (1, ''Ramesh'', 0), (2, ''Khilan'', 1), (4, ''Kaushik'', NULL);"
      con.query(sql);
    
      //Displaying all the records of the CUSTOMERS table
      sql = "SELECT * FROM CUSTOMERS;"
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    Connected!
    --------------------------
    Table created Successfully...
    [
      { ID: 1, NAME: ''Ramesh'', AVAILABILITY: 0 },
      { ID: 2, NAME: ''Khilan'', AVAILABILITY: 1 },
      { ID: 4, NAME: ''Kaushik'', AVAILABILITY: null }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class BooleanOperator {
      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...!");
                //create a table(having boolean field/column)
                String sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,NAME VARCHAR(40),AVAILABILITY BOOLEAN)";
                st.execute(sql);
                System.out.println("Table created successfully...!");
                //now lets insert some records
                String sql1 = "INSERT INTO CUSTOMERS(ID, NAME, AVAILABILITY) VALUES (1, ''Ramesh'', 0), (2, ''Khilan'', 1), (4, ''Kaushik'', NULL)";
                st.executeUpdate(sql1);
                System.out.println("Records inserted successfully...!");
                //lets display the records....
                String sql2 = "SELECT * FROM CUSTOMERS";
                rs = st.executeQuery(sql2);
                System.out.println("Table records are: ");
                while(rs.next()) {
                  String id = rs.getString("Id");
                  String name = rs.getString("Name");
                  String is_available = rs.getString("AVAILABILITY");
                  System.out.println("Id: " + id + ", Name: " + name + ", Is_available: " + is_available);
                }
        }catch(Exception e) {
          e.printStackTrace();
        }
      }
    }
    

    Output

    The output obtained is as shown below −

    Table created successfully...!
    Records inserted successfully...!
    Table records are:
    Id: 1, Name: Ramesh, Is_available: 0
    Id: 2, Name: Khilan, Is_available: 1
    Id: 4, Name: Kaushik, Is_available: null
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    table_name = ''customer''
    # Creating a cursor object
    cursorObj = connection.cursor()
    # Create table with boolean column
    sql = '''''' CREATE TABLE CUSTOMER(
        ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        NAME VARCHAR(40),
        AVAILABILITY BOOLEAN)''''''
    cursorObj.execute(sql)
    print("The table is created successfully!")
    # Insert data into the created table
    insert_query = ''INSERT INTO CUSTOMER(ID, NAME, AVAILABILITY) VALUES (1, "Ramesh", TRUE);''
    cursorObj.execute(insert_query)
    print("Row inserted successfully.")
    # Now display the table records
    select_query = "SELECT * FROM CUSTOMER"
    cursorObj.execute(select_query)
    result = cursorObj.fetchall()
    print("Tutorial Table Data:")
    for row in result:
        print(row)
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    The table is created successfully!
    Row inserted successfully.
    Tutorial Table Data:
    (1, ''Ramesh'', 1)
    

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

    MySQL – FLOAT

    Table of content


    The FLOAT data type is a part of the numeric data type. Numeric data types are used to store numbers, and they can be categorized into various subtypes based on their characteristics, such as storage size and precision.

    The MySQL FLOAT Data Type

    The MySQL FLOAT datatype is a floating-point number type that stores approximate numeric values. It stores approximate numeric values in 4 bytes and represents single-precision values.

    FLOAT is suitable for a wide range of numeric values but stores them in an approximate manner due to the IEEE 754 standard limitations.

    FLOAT data type can represent both signed and unsigned attributes of a data value in versions prior to MySQL 8.0.17, but the unsigned FLOAT is deprecated in MySQL 8.0.17 and later versions.

    Syntax

    Following is the basic syntax to set the datatype of a field as FLOAT −

    CREATE TABLE (column_name FLOAT, ...);
    

    Example

    In this example, let us create a new database table named ”datatype_demo” using CREATE TABLE statement with columns representing FLOAT values −

    CREATE TABLE datatype_demo(
       ID INT,
       NAME VARCHAR(50),
       HEIGHT FLOAT,
       WEIGHT FLOAT
    );
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.03 sec)
    

    Verification

    Once the table is created, we can verify the data types of the ”HEIGHT” and ”WEIGHT” fields by retrieving the table”s definition as shown below −

    DESC datatype_demo;
    

    The result of the DESC command will show that the ”HEIGHT” and ”WEIGHT” fields have the FLOAT data type −

    Field Type Null Key Default Extra
    ID int YES NULL
    NAME varchar(50) YES NULL
    HEIGHT float YES NULL
    WEIGHT float YES NULL

    To verify further, let us insert some values into the table using the following INSERT statement −

    INSERT INTO datatype_demo VALUES
    (1, ''John'', 171.3, 65.7),
    (2, ''Rob'', 45, 75),
    (3, ''Salman'', 12.74839, 54.262),
    (4, ''Arush'', NULL, NULL),
    (5, ''James'', ''h'', ''w'');
    

    Following is the output obtained −

    ERROR 1265 (01000): Data truncated for column ''HEIGHT'' at row 1
    

    As expected, the FLOAT fields accept single precision floating-point numbers without any issues. However, when attempting to insert non-numeric values into these fields, such as ”h” and ”w,” MySQL raises an error, indicating data truncation.

    Finally, to view the data that has been inserted into the table, we can use the SELECT statement as shown below −

    SELECT * FROM datatype_demo;
    

    The resultant table is as follows −

    ID NAME HEIGHT WEIGHT
    1 John 171.3 65.7
    2 Rob 45 75
    3 Salman 12.7484 54.262
    4 Arush NULL NULL

    Other Representations of MySQL FLOAT

    MySQL has a provision to specify the range of precision (not the exponent) for the FLOAT datatype in the form of bits. These bits are specified within the parenthesis following the keyword FLOAT, i.e. FLOAT(p).

    However, this precision value is only used to determine the storage size and only holds up to 7 decimal places, with the range from 0 to 23 bits. If the precision bit exceeds 23, the data type becomes DOUBLE.

    Example

    First, we will drop the existing ”datatype_demo” table −

    DROP TABLE datatype_demo;
    

    The output obtained is as follows −

    Query OK, 0 rows affected (0.01 sec)
    

    Then, we will create a new table ”datatype_demo” specifying a precision of 20 bits for the ”HEIGHT” column −

    CREATE TABLE datatype_demo(
       ID INT,
       NAME VARCHAR(50),
       HEIGHT FLOAT(20)
    );
    

    Following is the output of the above code −

    Query OK, 0 rows affected (0.02 sec)
    

    Verification

    Even though we specified a precision of 20 bits, the ”HEIGHT” column will still store float values within the single-precision range, holding up to 7 decimal places. To verify the table”s definition, we can use the DESC command as shown below −

    DESC datatype_demo;
    

    The table produced is as follows −

    Field Type Null Key Default Extra
    ID int YES NULL
    NAME varchar(50) YES NULL
    HEIGHT float YES NULL

    If the precision bit exceeds 23, the datatype becomes DOUBLE. Look at the query below −

    CREATE TABLE datatype_demo1(
       ID INT,
       NAME VARCHAR(50),
       HEIGHT FLOAT(30)
    );
    

    we get the following output −

    Query OK, 0 rows affected (0.02 sec)
    

    Again, we can verify the table”s definition using the DESC command −

    DESC datatype_demo1;
    

    Following is the table obtained −

    Field Type Null Key Default Extra
    ID int YES NULL
    NAME varchar(50) YES NULL
    HEIGHT double YES NULL

    Float Datatype Using a Client Program

    We can also create column of the Float datatype using the client program.

    Syntax

    To create a column of Float datatype through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −

    $sql = ''CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))
    $mysqli->query($sql);
    

    To create a column of Float datatype through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −

    sql = "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))";
    con.query(sql);
    

    To create a column of Float datatype through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −

    String sql = "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))";
    statement.execute(sql);
    

    To create a column of Float datatype through a python program, we need to execute the “CREATE TABLE” statement using the execute() function of the MySQL Connector/Python as follows −

    sql = ''CREATE TABLE datatype_demo(ID INT, NAME VARCHAR(50), HEIGHT FLOAT, WEIGHT FLOAT)''''
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $dbname = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); //creating a table temp where we are inserting the celsius and Fahrenheit values in float $sql = ''CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id)) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } // insert data into created table $q = " INSERT INTO temp(Celsius, Fahrenheit) VALUES ( 36.2, 97.16), ( 35.8, 96.44), ( 37.32, 99.17), ( 35.89, 96.602);"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM temp"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Celsius: %f, Fahrenheit: %f", $row["Id"], $row["Celsius"], $row["Fahrenheit"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table created successfully...!
    Data inserted successfully...!
    Table Records:
     ID: 1, Celsius: 36.200000, Fahrenheit: 97.160000
     ID: 2, Celsius: 35.800000, Fahrenheit: 96.440000
     ID: 3, Celsius: 37.320000, Fahrenheit: 99.170000
     ID: 4, Celsius: 35.890000, Fahrenheit: 96.602000
    
    var mysql = require("mysql2");
    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "password",
    }); //Connecting to MySQL
    
    con.connect(function (err) {
      if (err) throw err;
      //   console.log("Connected successfully...!");
      //   console.log("--------------------------");
      sql = "USE TUTORIALS";
      con.query(sql);
    
      //create a student table, that accepts one column of float type.
      sql =
        "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))";
      con.query(sql);
    
      //insert data into created table
      sql =
        "INSERT INTO temp(Celsius, Fahrenheit) VALUES ( 36.2, 97.16), ( 35.8, 96.44), ( 37.32, 99.17), ( 35.89, 96.602)";
      con.query(sql);
      //select datatypes of salary
      sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''temp'' AND COLUMN_NAME = ''Celsius''`;
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    [ { DATA_TYPE: ''float'' } ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class Float {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String username = "root";
          String password = "password";
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             Connection connection = DriverManager.getConnection(url, username, password);
             Statement statement = connection.createStatement();
             System.out.println("Connected successfully...!");
    
             //Float data types...!;
             String sql = "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))";
             statement.execute(sql);
             System.out.println("column of a Float type created successfully...!");
             ResultSet resultSet = statement.executeQuery("DESCRIBE temp");
             while (resultSet.next()){
                System.out.println(resultSet.getString(1)+" "+resultSet.getString(2));
             }
             connection.close();
          } catch (Exception e) {
             System.out.println(e);
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    column of a Float type created successfully...!
    Id int
    Celsius float
    Fahrenheit float
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    # Creating a cursor object
    cursorObj = connection.cursor()
    # Create table with float column
    sql = ''''''
    CREATE TABLE datatype_demo(ID INT,
    NAME VARCHAR(50),
    HEIGHT FLOAT,
    WEIGHT FLOAT
    )
    ''''''
    cursorObj.execute(sql)
    print("The table is created successfully!")
    # Data to be inserted
    data_to_insert = [
        (1, ''John'', 171.3, 65.7),
        (2, ''Rob'', 45, 75),
        (3, ''Salman'', 12.74839, 54.262),
        (4, ''Arush'', None, None),
    ]
    # Insert data into the created table
    insert_query = "INSERT INTO datatype_demo (ID, NAME, HEIGHT, WEIGHT) VALUES (%s, %s, %s, %s)"
    cursorObj.executemany(insert_query, data_to_insert)
    # Commit the changes after the insert operation
    connection.commit()
    print("Rows inserted successfully.")
    # Now display the table records
    select_query = "SELECT * FROM datatype_demo"
    cursorObj.execute(select_query)
    result = cursorObj.fetchall()
    print("Table Data:")
    for row in result:
        print(row)
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    The table is created successfully!
    Rows inserted successfully.
    Table Data:
    (1, ''John'', 171.3, 65.7)
    (2, ''Rob'', 45.0, 75.0)
    (3, ''Salman'', 12.7484, 54.262)
    (4, ''Arush'', None, None)
    

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

    MySQL – CREATE TRIGGER

    Table of content


    Triggers are generally defined as responses to an event. For instance, when we hover a mouse-pointer on a drop-down menu of a website, a various set of options to navigate through this website are then displayed. Here, the hovering of the mouse-pointer is an event while the display of options in the drop-down menu is a result of trigger execution. This concept is also introduced in MySQL.

    Triggers in MySQL are stored programs similar to procedures. These can be created on a table, schema, view and database that are associated with an event and whenever an event occurs the respective trigger is invoked.

    Triggers are, in fact, written to be executed in response to any of the following events −

    • A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
    • A database definition (DDL) statement (CREATE, ALTER, or DROP).
    • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

    Creating Trigger in MySQL

    You can create a trigger using the CREATE TRIGGER Statement.

    Syntax

    Following is the syntax of the MySQL CREATE TRIGGER Statement.

    CREATE TRIGGER trigger_name
    trigger_time trigger_event
    ON table_name FOR EACH ROW
    BEGIN
    ...
    END;
    

    Where,

    • trigger_name is the name of the trigger you need to create
    • trigger_time is the time of trigger activation
    • trigger_event can be INSERT, UPDATE, or DELETE. This event causes the trigger to be invoked.
    • table_name is the name of the table to which the trigger is associated with.

    Example

    Assume we have created a table with name student as shown below −

    CREATE TABLE STUDENT(
       Name varchar(35),
       Age INT,
       Score INT
    );
    

    Following query creates a trigger, this will set the score value 0 if you enter a value that is less than 0 as score.

    DELIMITER //
    CREATE TRIGGER sample_trigger BEFORE INSERT ON STUDENT FOR EACH ROW
    BEGIN
    IF NEW.Score < 0 THEN SET NEW.Score = 0;
    END IF;
    END //
    DELIMITER ;
    

    Verification

    If you try to insert records in the student table and if you use a value that is less than 0 as age it will be automatically set to 0.

    INSERT INTO STUDENT VALUES
    (''Jeevan'', 22, 8),
    (''Raghav'', 26, -3),
    (''Pooja'', 21, -9),
    (''Devi'', 30, 9);
    

    The STUDENT table created will have the following records −

    Name Age Score
    Jeevan 22 8
    Raghav 26 0
    Pooja 21 0
    Devi 30 9

    As we can see, there are no negative values inserted in the table as they are all replaced with zeroes.

    Creating Trigger Using a Client Program

    We can also Create a trigger using a client program.

    Syntax

    To Create a Trigger through a PHP program, we need to execute the CREATE statement using the mysqli function named query() as follows −

    $sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score";
    $mysqli->query($sql);
    

    To Create a Trigger through a JavaScript program, we need to execute the CREATE statement using the query() function of mysql2 library as follows −

    sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score"
    con.query(sql);
    

    To Create a Trigger through a Java program, we need to execute the CREATE statement using the JDBC function execute() as follows −

    String sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score";
    statement.execute(sql);
    

    To Create a Trigger through a python program, we need to execute the CREATE statement using the execute() function of the MySQL Connector/Python as follows −

    create_trigger_query = ''CREATE TRIGGER sample_trigger
    BEFORE INSERT ON students
    FOR EACH ROW
    BEGIN
       IF NEW.Score < 0 THEN
          SET NEW.Score = 0;
       END IF;
    END''
    cursorObj.execute(create_trigger_query)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $db = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    if($mysqli->connect_errno ) {
       printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); $sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score"; if($mysqli->query($sql)){ printf("Trigger created successfully...!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Trigger created successfully...!
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
       host:"localhost",
       user:"root",
       password:"password"
    });
    
    //Connecting to MySQL
    con.connect(function(err) {
       if (err) throw err;
       //console.log("Connected successfully...!");
       //console.log("--------------------------");
       sql = "USE TUTORIALS";
       con.query(sql);
       sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score"
       con.query(sql);
       console.log("Trigger created successfully....!");
       sql = "SHOW TRIGGERS";
       con.query(sql, function(err, result){
          if (err) throw err;
          console.log(result);
       });
    });
    

    Output

    The output produced is as follows −

    Trigger created successfully....!
    [
      {
        Trigger: ''testTrigger'',
        Event: ''UPDATE'',
        Table: ''student'',
        Statement: "INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score",
        Timing: ''AFTER'',
        Created: 2023-08-01T05:21:18.540Z,
        sql_mode: ''IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION'',
        Definer: ''root@localhost'',
        character_set_client: ''utf8mb4'',
        collation_connection: ''utf8mb4_unicode_ci'',
        ''Database Collation'': ''utf8mb4_0900_ai_ci''
      }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class CreateTrigger {
       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 TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score";
             st.execute(sql);
             System.out.print("Trigger created successfully....!");
    
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Trigger created successfully....!
    
    import mysql.connector
    #Establishing the connection
    connection = mysql.connector.connect(
       host=''localhost'',
       user=''root'',
       password=''password'',
       database=''tut''
    )
    table_name = ''Student''
    trigger_name = ''sample_trigger''
    # Creating a cursor object
    cursorObj = connection.cursor()
    # Create table
    create_table_query = ''''''
    CREATE TABLE Student(
       Name VARCHAR(35),
       age INT,
       Score INT
    )
    ''''''
    cursorObj.execute(create_table_query)
    print("The table is created successfully!")
    # Creating a trigger
    create_trigger_query = f''''''CREATE TRIGGER {trigger_name}
    BEFORE INSERT ON {table_name}
    FOR EACH ROW
    BEGIN
       IF NEW.Score < 0 THEN
          SET NEW.Score = 0;
       END IF;
    END''''''
    cursorObj.execute(create_trigger_query)
    print(f"Trigger ''{trigger_name}'' is created successfully.")
    # Commit the changes and close the cursor and connection
    connection.commit()
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    The table is created successfully!
    Trigger ''sample_trigger'' 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 – BIT nhận dự án làm có lương

    MySQL – BIT

    Table of content


    A bit represents the basic unit of data in programming languages. It can store only two values, represented as 0 or 1.

    The MySQL BIT Data Type

    The MySQL BIT data type is used to store binary values within a specified range. The range is determined by the number of bits you allocate to the BIT column.

    If we try to insert an integer value instead of BIT values, MySQL automatically converts them into BIT values. We have to ensure that the integer value we are adding must be within the range for conversion to BIT values.

    For instance, if you have a BIT(3) column, it can store values from 000 to 111 in binary, which corresponds to 0 to 7 in integer format. If you try to insert the integer 8 into this BIT(3) column, you”ll get an error because 8 in binary is 1000, which is outside the valid range of the column.

    Syntax

    Following is the syntax of the MySQL BIT datatype −

    BIT(n)
    

    Here, the range of n value is from 1 to 64. If you don”t provide the “n” value, the default is 1, resulting in a single-bit BIT column. Hence, the following queries will give the same output −

    Column_name BIT(1);
    and
    Column_name BIT;
    

    Bit Value Literal

    • To specify bit value literals, you can use the b”val or 0bval notations, where val is a binary value containing only 0s and 1s. The leading ”b” is case-insensitive.

    b01
    B11
    
  • Note that the 0b notation is case-sensitive, so 0B”1000” is an invalid bit literal value.

  • 0B''1000''
    

    Example

    Let us create a table named STUDENTS and use the BIT data type for the AGE column as shown below −

    CREATE TABLE STUDENTS(
       ID int auto_increment,
       NAME varchar(40),
       AGE BIT(3),
       primary key (ID)
    );
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.01 sec)
    

    Now, we are inserting the values “5” and “3” into the AGE column of the STUDENTS table −

    INSERT INTO STUDENTS (NAME, AGE) VALUES
    (''Varun'', 5),
    (''Akash'', 3);
    

    Output of the above query is as shown below −

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

    We can use the following query to display the inserted values in the AGE column of the STUDENTS table −

    SELECT * from STUDENTS;
    

    We can see in the output below that the values “5” and “3” are stored in binary format −

    ID NAME AGE
    1 Varun 0x05
    2 Akash 0x03

    Now, let us insert another value “10”. In binary format, “10” is represented as “1010”. However, we defined the AGE column to have a range of only three bits. Therefore, the following query will generate an error because the value 10 is greater than 7 −

    INSERT INTO STUDENTS (NAME, AGE) VALUES (''Priya'', 10);
    

    The output indicates that the data is too long for the AGE column.

    ERROR 1406 (22001): Data too long for column ''AGE'' at row 1
    

    To insert bit value literals into the “AGE” column, you can use the B”val notation. Here, we are inserting “110” which is equivalent to the integer value “6” as shown below −

    INSERT INTO STUDENTS (NAME, AGE) VALUES(''Priya'', B''110'');
    

    The result obtained is as follows −

    Query OK, 1 row affected (0.01 sec)
    

    Let us display all the records in the “STUDENTS” table using the following query −

    SELECT * from STUDENTS;
    

    We can see in the output below that the value “6” has been inserted in binary format as “0x06” −

    ID NAME AGE
    1 Varun 0x05
    2 Akash 0x03
    3 Priya 0x06

    Verification

    To verify and display the inserted values in the “AGE” column in binary/bit format, you can use the MySQL BIN() function −

    SELECT ID, NAME, BIN(AGE) FROM STUDENTS;
    

    The output shows the values in binary format −

    ID NAME BIN(AGE)
    1 Varun 101
    2 Akash 11
    3 NULL 110

    In the above output, we can see that the leading zeros are removed. If we want to display them, we can use the LPAD function as shown below −

    SELECT ID, NAME, LPAD(BIN(AGE), 5, "0") FROM STUDENTS;
    

    Following is the output obtained −

    ID NAME LPAD(BIN(AGE), 5, “0”)
    1 Varun 00101
    2 Akash 00011
    3 NULL 00110

    BIT Datatype Using a Client Program

    We can also create column of the BIT datatype using the client program.

    Syntax

    To create a column of BIT datatype through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −

    $sql = ''CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID) )
    $mysqli->query($sql);
    

    To create a column of BIT datatype through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −

    sql = "CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID) )";
    con.query(sql);
    

    To create a column of BIT datatype through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −

    String sql = "CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID))";
    statement.execute(sql);
    

    To create a column of BIT datatype through a python program, we need to execute the “CREATE TABLE” statement using the execute() function of the MySQL Connector/Python as follows −

    sql = ''CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3),  primary key (ID) )''
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $dbname = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); //creating a table student where age is bit data types $sql = ''CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID) ) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } // insert data into created table $q = " INSERT INTO students (NAME, AGE) VALUES (''Varun'', 5), (''Akash'', 3)"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM students"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Age: %d", $row["ID"], $row["AGE"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table created successfully...!
    Data inserted successfully...!
    Table Records:
    ID: 1, Age: 5
    ID: 2, Age: 3
    
    var mysql = require("mysql2");
    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "password",
    }); //Connecting to MySQL
    
    con.connect(function (err) {
      if (err) throw err;
      //   console.log("Connected successfully...!");
      //   console.log("--------------------------");
      sql = "USE TUTORIALS";
      con.query(sql);
    
      //create a students table, that accepts one column of bit type.
      sql = "CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID) )";
      con.query(sql);
    
      //insert data into created table
      sql = "INSERT INTO students (NAME, AGE) VALUES (''Varun'', 5), (''Akash'', 3)";
      con.query(sql);
    
      //select datatypes of salary
      sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''students'' AND COLUMN_NAME = ''AGE''`;
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    [ { DATA_TYPE: ''bit'' } ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class Bit {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String username = "root";
          String password = "password";
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             Connection connection = DriverManager.getConnection(url, username, password);
             Statement statement = connection.createStatement();
             System.out.println("Connected successfully...!");
    
             //Bit data types...!;
             String sql = "CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID))";
             statement.execute(sql);
             System.out.println("column of a BIT type created successfully...!");
             ResultSet resultSet = statement.executeQuery("DESCRIBE students");
             while (resultSet.next()){
                System.out.println(resultSet.getString(1)+" "+resultSet.getString(2));
             }
             connection.close();
          } catch (Exception e) {
             System.out.println(e);
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    column of a BIT type created successfully...!
    ID int
    NAME varchar(40)
    AGE bit(3)
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    # Creating a cursor object
    cursorObj = connection.cursor()
    # Create table with BIT column
    sql = ''''''
    CREATE TABLE students(
    ID int auto_increment,
    NAME varchar(40),
    AGE BIT(3),
    primary key (ID)
    )
    ''''''
    cursorObj.execute(sql)
    print("The table is created successfully!")
    # Data to be inserted
    data_to_insert = [
        (''Varun'', 5),
        (''Akash'', 3)
    ]
    # Insert data into the created table
    insert_query = "INSERT INTO students (NAME, AGE) VALUES (%s, %s)"
    cursorObj.executemany(insert_query, data_to_insert)
    # Commit the changes after the insert operation
    connection.commit()
    print("Rows inserted successfully.")
    # Now display the table records
    select_query = "SELECT * FROM students"
    cursorObj.execute(select_query)
    result = cursorObj.fetchall()
    print("Table Data:")
    for row in result:
        print(row)
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    The table is created successfully!
    Rows inserted successfully.
    Table Data:
    (1, ''Varun'', 5)
    (2, ''Akash'', 3)
    

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

    MySQL – Triggers

    Table of content


    Generally, a Trigger is defined as a response to an event. In MySQL, a trigger is a special stored procedure that resides in the system catalogue, that is executed automatically (without being called explicitly like regular stored procedures) whenever an event is performed. These events include statements like INSERT, UPDATE and DELETE etc.

    To run a MySQL trigger, the user must have admin/superuser privileges.

    As per the SQL standard, triggers are usually divided into two categories −

    • Row-level Trigger: Triggers that are only executed when each row is either inserted, updated or deleted in a database table. MySQL only supports these type of triggers.

    • Statement-level Trigger: Triggers like these are executed on the transaction level, once, no matter how many rows are modified in a table. MySQL does not support these trype of triggers.

    Types of Triggers in MySQL

    There are six types of row-level triggers in MySQL. They are:

    • Before Insert Trigger

    • After Insert Trigger

    • Before Update Trigger

    • After Update Trigger

    • Before Delete Trigger

    • After Delete Trigger

    Before Insert Trigger

    The Before Insert Trigger is performed before any value is inserted into the table. Whenever an INSERT statement is executed, the Before Insert trigger goes off, followed by the insertion transaction.

    After Insert Trigger

    The After Insert Trigger works opposite to the Before Insert Trigger. As implied by its name, it is performed after any value is inserted into the table. Whenever an INSERT statement is executed, the value is inserted into the table first followed by the execution of the trigger.

    Before Update Trigger

    The Before Update Trigger is performed before any value is updated or modified in the table. Whenever an UPDATE statement is executed, the Before Update trigger goes off, followed by the update transaction.

    After Update Trigger

    The After Update Trigger works opposite to the Before Update Trigger. As implied by its name, it is performed after any value is updated in the table. Whenever an UPDATE statement is executed, the value is updated in the table first followed by the execution of the trigger.

    Before Delete Trigger

    The Before Delete Trigger is performed before any value is deleted from the table. Whenever a DELETE statement is executed, the Before Delete trigger goes off, followed by the deletion transaction.

    After Delete Trigger

    The After Delete Trigger works opposite to the Before Delete Trigger. As implied by its name, it is performed after any value is deleted from the table. Whenever an DELETE statement is executed, the value is deleted from the table first followed by the execution of the trigger.

    Advantages of Triggers

    Triggers hold a lot of advantages in MySQL database. They are listed as follows −

    • Triggers help the database to maintain the integrity of the data stored.

    • Triggers are also a means to handle errors from the database layer itself.

    • As triggers are invoked automatically without being called explicitly, you don”t have to wait for the scheduled events to run.

    • Triggers can be useful to track the data changes made in the tables, by logging the events.

    • MySQL Triggers can also prevent invalid transactions from being executed.

    Disadvantages of Triggers

    However, there are disadvantages of using triggers in a MySQL database. Some of them are listed as follows −

    • Triggers cannot replace all validations, and only provide extended validations. For simple validations, you can use the NOT NULL, UNIQUE, CHECK and FOREIGN KEY constraints.

    • As triggers are invisible to the client application, it is impossible to understand what goes on in the database layer. Hence, making it difficult to troubleshoot.

    • Triggers are not beneficial for use with high-velocity data i.e. the data when a number of events per second are high.

    • Triggers may increase the overhead of the MySQL Server.

    Restrictions on Triggers

    Following are some of the restrictions that apply to MySQL triggers −

    • One trigger for each event − Each table can have only one trigger for each event combination, i.e. you can”t define two same triggers for the same table.

    • RETURN statement is not permitted − As triggers don”t return any values, the RETURN statement is not permitted.

    • Foreign key restriction − Triggers are not activated by foreign key actions.

    • Outdated metadata − Suppose, if a trigger is loaded into cache, it is not automatically reloaded when the table metadata changes. In this case, a trigger can operate using outdated metadata.

    • Cannot use ”CALL” statement − We cannot use the CALL statement in triggers.

    • Cannot create a TEMPORARY table or a view − We cannot create a view for a temporary table or a view.

    • Not activated by changes in INFORMATION_SCHEMA − Actually, triggers are not activated by changes made in INFORMATION_SCHEMA or performance_schema tables. It is because these tables are views and triggers are not permitted on views.


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

    MySQL – INT

    Table of content


    The MySQL INT Data Type

    The MySQL INT data type is used to store whole numbers without the decimal places (integers).

    However, MySQL provides various integer data types, such as TINYINT, SMALLINT, MEDIUMINT, and BIGINT to cater to different ranges of whole numbers.

    The following table illustrates the characteristics of different integer types in MySQL, including storage in bytes, minimum value, and maximum value for both signed and unsigned options −

    Type Storage (Bytes) Minimum value (Signed/Unsigned) Maximum value (Signed/Unsigned)
    TINYINT 1 -128/ 0 127/ 255
    SMALLINT 2 -32768/ 0 32767/ 65535
    MEDIUMINT 3 -8388608/ 0 8388607/ 16777215
    INT 4 -8388607/ 16777215 2147483647/ 4294967295
    BIGINT 8 – 9223372036854775808 / 0 9223372036854775807 / 18446744073709551615

    We have to choose the data types based on the kind (type) of data being stored. If possible, we need to use smaller data types to minimize the database size. TINYINT can be used for small numbers, while INT or BIGINT is used for large numbers like phone numbers in a country.

    Auto Increment with MySQL INT

    In MySQL, you can use the AUTO_INCREMENT attribute with an INT column to automatically generate unique values for that column. Here”s how it works −

    • Initial Value − When you create a table with an AUTO_INCREMENT INT column, the sequence starts with 1.

    • Inserting NULL or 0 − When you insert a record with a NULL or 0 value for the AUTO_INCREMENT column, MySQL sets the value to the next sequence value. This means it assigns the next available integer starting from 1.

    • Inserting Non-NULL Values − If you insert a non-NULL value into the AUTO_INCREMENT column, MySQL accepts that value and continues the sequence based on the new value inserted.

    Example

    First of all, we are creating a table named STUDENTS with an AUTO_INCREMENT INT column named “ID” −

    CREATE TABLE STUDENTS (
       ID int auto_increment,
       NAME varchar(20),
       primary key (ID)
    );
    

    When we insert records into this table without specifying values for the “ID” column, MySQL automatically generates unique values for “ID” starting from 1.

    Here, we are inserting three rows into the STUDENTS table using the below INSERT query −

    INSERT INTO STUDENTS (NAME) VALUES
    (''Tilak''), (''Akash''), (''Surya''), (''Deepak'');
    

    The STUDENTS table created is as follows −

    ID NAME
    1 Tilak
    2 Akash
    3 Surya
    4 Deepak

    Now, let us insert a row where we provide an explicit value for the “ID” column −

    INSERT INTO STUDENTS (ID, NAME) VALUES (15, ''Arjun'');
    

    Following is the output obtained −

    Query OK, 1 row affected (0.01 sec)
    

    Since we specified the “ID” as 15, MySQL resets the sequence to 16. If we insert a new row without specifying the “ID,” MySQL will use 16 as the next AUTO_INCREMENT value −

    INSERT INTO STUDENTS (NAME) VALUES (''Dev'');
    

    The output obtained is as follows −

    Query OK, 1 row affected (0.01 sec)
    

    Now, let us retrieve the records from the “STUDENTS” table −

    SELECT * FROM STUDENTS;
    

    The table produced is −

    ID NAME
    1 Tilak
    2 Akash
    3 Surya
    4 Deepak
    15 Arjun
    16 Dev
    From MySQL 5.1 version and onwards, the AUTO_INCREMENT column accepts only positive values and does not allow negative values.

    MySQL INT UNSIGNED

    In MySQL, when you define an UNSIGNED INT on a column, that column is restricted to storing only non-negative values (i.e., positive values). Negative values are not allowed in such columns.

    Example

    Let us create a table with the name EMPLOYEES using the following query −

    CREATE TABLE EMPLOYEES (
       ID int auto_increment,
       NAME varchar(30) not null,
       AGE int UNSIGNED,
       Primary key(ID)
    );
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.04 sec)
    

    Now, let us insert a row with a non-negative value into the “AGE” column −

    INSERT INTO EMPLOYEES (NAME, AGE) VALUES (''Varun'', 32);
    

    The above query will execute successfully since the value provided for the “AGE” column is non-negative.

    Query OK, 1 row affected (0.01 sec)
    

    However, if we attempt to insert a negative value into the “AGE” column, MySQL will generate an error −

    INSERT INTO EMPLOYEES (NAME, AGE) VALUES (''Sunil'', -10);
    

    MySQL will issue an error as shown below −

    ERROR 1264 (22003): Out of range value for column ''AGE'' at row 1
    

    MySQL INT with Display Width Attribute

    In MySQL, you can specify a display width for the INT data type by using parentheses after the INT keyword. For instance, using INT(5) sets the display width to five digits.

    It”s important to note that the display width attribute for INT in MySQL doesn”t affect the range of values that can be stored in the column. It formats integer values in applications, and is included as metadata in the result set.

    For example, if you insert the value 12345 into the id column of the EMPLOYEES table, it will be stored as is. When you retrieve it, some applications may choose to pad it with leading zeros to ensure it is displayed as five digits (e.g., 012345).

    MySQL INT with ZEROFILL Attribute

    In MySQL, the ZEROFILL attribute is a non-standard attribute that can be applied to numeric data types. It adds leading zeros to the displayed values, making sure the number is displayed with a fixed width, especially useful for numerical codes.

    Example

    Let us create a table with the name ZEROFILL_TABLE with ZEROFILL applied to INT columns using the query below −

    CREATE TABLE ZEROFILL_TABLE (
       col1 int(4) ZEROFILL,
       col2 int(6) ZEROFILL,
       col3 int(8) ZEROFILL
    );
    

    The output obtained is as follows −

    Query OK, 0 rows affected, 6 warnings (0.02 sec)
    

    Now, we are inserting a new row into the above-created table −

    INSERT INTO ZEROFILL_TABLE (col1, col2, col3)
    VALUES (1, 7, 3);
    

    Following is the output of the above code −

    Query OK, 1 row affected (0.00 sec)
    

    Now, let us display the records from the ZEROFILL_TABLE table −

    SELECT * FROM ZEROFILL_TABLE;
    

    We can see in the output below, the values are displayed with the specified width, and leading zeros are added to maintain that width, as determined by the ZEROFILL attribute −

    col1 col2 col3
    0001 000007 00000003

    INT Datatype Using a Client Program

    We can also create column of the INT datatype using the client program.

    Syntax

    To create a column of INT datatype through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −

    $sql = ''CREATE TABLE students (Id INT AUTO_INCREMENT primary key not null, reg_No INT )
    $mysqli->query($sql);
    

    To create a column of INT datatype through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −

    sql = "CREATE TABLE students (Id INT AUTO_INCREMENT primary key not null, reg_No INT )";
    con.query(sql);
    

    To create a column of INT datatype through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −

    String sql = "CREATE TABLE students(Id INT AUTO_INCREMENT primary key not null, reg_No INT)";
    statement.execute(sql);
    

    To create a column of INT datatype through a python program, we need to execute the “CREATE TABLE” statement using the execute() function of the MySQL Connector/Python as follows −

    sql = ''CREATE TABLE students (ID int auto_increment, NAME varchar(20), primary key (ID) )''
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $dbname = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if ($mysqli->connect_errno) {
       printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); //create table with boolean column $sql = ''CREATE TABLE students (Id INT AUTO_INCREMENT primary key not null, reg_No INT ) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } //insert data into created table $q = "INSERT INTO students (reg_No) VALUES (101), (102)"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT Id, reg_No FROM students"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Reg: %s", $row["Id"], $row["reg_No"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table Records:
    ID: 1, Reg: 101
    ID: 2, Reg: 102
    
    var mysql = require("mysql2");
    var con = mysql.createConnection({
       host: "localhost",
       user: "root",
       password: "password",
    }); //Connecting to MySQL
    
    con.connect(function (err) {
       if (err) throw err;
       //console.log("Connected successfully...!");
       //console.log("--------------------------");
       sql = "USE TUTORIALS";
       con.query(sql);
    
       //create a students table, that accepts one column of int type.
       sql = "CREATE TABLE students (Id INT AUTO_INCREMENT primary key not null, reg_No INT )";
       con.query(sql);
    
       //insert data into created table
       sql = "INSERT INTO students (reg_No) VALUES (101), (102)";
       con.query(sql);
    
       //select datatypes of salary
       sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''students'' AND COLUMN_NAME = ''reg_No''`;
       con.query(sql, function (err, result) {
          if (err) throw err;
          console.log(result);
       });
    });
    

    Output

    The output produced is as follows −

    [ { DATA_TYPE: ''int'' } ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class Int {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String username = "root";
          String password = "password";
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             Connection connection = DriverManager.getConnection(url, username, password);
             Statement statement = connection.createStatement();
             System.out.println("Connected successfully...!");
    
             //Int data types...!;
             String sql = "CREATE TABLE students(Id INT AUTO_INCREMENT primary key not null, reg_No INT)";
             statement.execute(sql);
             System.out.println("column of a INT type created successfully...!");
             ResultSet resultSet = statement.executeQuery("DESCRIBE students");
             while (resultSet.next()){
                System.out.println(resultSet.getString(1)+" "+resultSet.getString(2));
             }
             connection.close();
          } catch (Exception e) {
             System.out.println(e);
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    column of a INT type created successfully...!
    Id int
    reg_No int
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
       host=''localhost'',
       user=''root'',
       password=''password'',
       database=''tut''
    )
    # Creating a cursor object
    cursorObj = connection.cursor()
    # Create table with int column
    sql = ''''''CREATE TABLE students (
    ID int auto_increment,
    NAME varchar(20),
    primary key (ID)
    )''''''
    cursorObj.execute(sql)
    print("The table is created successfully!")
    # Data to be inserted
    data_to_insert = [
        (1, ''Tilak''),
        (2, ''Akash''),
        (3, ''Surya''),
        (4, ''Deepak''),
        (15, ''Arjun''),
        (16, ''Dev'')
    ]
    # Insert data into the created table
    insert_query = "INSERT INTO STUDENTS (ID, NAME) VALUES (%s, %s)"
    cursorObj.executemany(insert_query, data_to_insert)
    # Commit the changes after the insert operation
    connection.commit()
    print("Rows inserted successfully.")
    # Now display the table records
    select_query = "SELECT * FROM Students"
    cursorObj.execute(select_query)
    result = cursorObj.fetchall()
    print("Table Data:")
    for row in result:
        print(row)
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    The table is created successfully!
    Rows inserted successfully.
    Table Data:
    (1, ''Tilak'')
    (2, ''Akash'')
    (3, ''Surya'')
    (4, ''Deepak'')
    (15, ''Arjun'')
    (16, ''Dev'')
    

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

    MySQL – SHOW TRIGGERS

    Table of content


    Triggers in MySQL are stored programs similar to procedures. These can be created on a table, schema, view and database that are associated with an event and whenever an event occurs the respective trigger is invoked.

    MySQL provides a statement to list out all the existing triggers present in a database. Knowing the trigger information can be useful while creating new triggers, so that a user wouldn”t use the same name for multiple triggers.

    Show Triggers in MySQL

    The SHOW TRIGGERS Statement is used in MySQL to display information about all the triggers defined in the current database.

    Syntax

    Following is the syntax of the MySQL SHOW TRIGGERS Statement −

    SHOW TRIGGERS
    [{FROM | IN} db_name]
    [LIKE ''pattern'' | WHERE expr]
    

    Example

    In this example, we are creating a table named STUDENT using the query below −

    CREATE TABLE STUDENT(
       Name varchar(35),
       Age INT,
       Score INT
    );
    

    Following query creates a trigger sample_trigger which will set the score value to 0 if you enter a negative score value into the table.

    DELIMITER //
    CREATE TRIGGER sample_trigger
    BEFORE INSERT ON STUDENT
    FOR EACH ROW
    BEGIN
     IF NEW.score < 0 THEN SET NEW.score = 0;
    END IF;
    END //
    DELIMITER ;
    

    Assume we have created another trigger using the AFTER clause −

    DELIMITER //
    CREATE TRIGGER testTrigger
    AFTER UPDATE ON Student
    FOR EACH ROW
    BEGIN
     INSERT INTO Student
     SET action = ''update'',
     Name = OLD.Name,
     Age = OLD.age,
     Score = OLD.score;
    END;
    END //
    
    DELIMITER ;
    

    Following query shows the existing triggers in the current database −

    SHOW TRIGGERS G;
    

    Output

    The list of triggers will be displayed as follows −

    *************************** 1. row ***************************
    Trigger: sample_trigger
    Event: INSERT
    Table: student
    Statement: BEGIN
               IF NEW.score < 0 THEN SET NEW.score = 0;
               END IF;
               END
    Timing: BEFORE
    Created: 2021-05-12 19:08:04.50
    sql_mode: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
    Definer: root@localhost
    character_set_client: utf8mb4
    collation_connection: utf8mb4_0900_ai_ci
      Database Collation: utf8mb4_0900_ai_ci
    *************************** 2. row ***************************
    Trigger: testTrigger
    Event: UPDATE
    Table: student
    Statement: INSERT INTO Student
               SET Name = OLD.Name,
                   Age = OLD.age,
                   Score = OLD.score
    Timing: AFTER
    Created: 2021-05-12 19:10:44.49
    sql_mode: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
    Definer: root@localhost
    character_set_client: utf8mb4
    collation_connection: utf8mb4_0900_ai_ci
    Database Collation: utf8mb4_0900_ai_ci
    2 rows in set (0.00 sec)
    

    With FROM or IN Clause

    You can retrieve the information of triggers from a specific database using the FROM clause.

    Example

    Assume that the current database is named demo. Following query shows the triggers present in the database demo

    SHOW TRIGGERS FROM demoG
    

    You can also use the IN clause instead of FROM, to get the same output.

    SHOW TRIGGERS IN demoG
    

    Output

    The existing triggers present in the demo database −

    *************************** 1. row ***************************
                 Trigger: sample_trigger
                   Event: INSERT
                   Table: student
               Statement: BEGIN
     IF NEW.score < 0 THEN SET NEW.score = 0;
    END IF;
    END
                  Timing: BEFORE
                 Created: 2023-09-29 11:42:33.58
                sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
                 Definer: root@localhost
    character_set_client: cp850
    collation_connection: cp850_general_ci
      Database Collation: utf8mb4_0900_ai_ci
    *************************** 2. row ***************************
                 Trigger: testTrigger
                   Event: UPDATE
                   Table: student
               Statement: BEGIN
     INSERT INTO Student
     SET action = ''update'',
     Name = OLD.Name,
     Age = OLD.age,
     Score = OLD.score;
    END
                  Timing: AFTER
                 Created: 2023-09-29 11:43:10.27
                sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
                 Definer: root@localhost
    character_set_client: cp850
    collation_connection: cp850_general_ci
      Database Collation: utf8mb4_0900_ai_ci
    2 rows in set (0.00 sec)
    

    With WHERE Clause

    You can use the WHERE clause of the SHOW TRIGGERS statements to retrieve info about the triggers which match the specified condition.

    Example

    Following query retrieves the triggers in the current database whose event is update −

    SHOW TRIGGERS FROM demo WHERE Event = ''UPDATE'' G;
    

    Output

    The required list of triggers is displayed as follows −

    *************************** 1. row ***************************
                 Trigger: testTrigger
                   Event: UPDATE
                   Table: student
               Statement: BEGIN
     INSERT INTO Student
     SET action = ''update'',
     Name = OLD.Name,
     Age = OLD.age,
     Score = OLD.score;
    END
                  Timing: AFTER
                 Created: 2023-09-29 11:43:10.27
                sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
                 Definer: root@localhost
    character_set_client: cp850
    collation_connection: cp850_general_ci
      Database Collation: utf8mb4_0900_ai_ci
    1 row in set (0.00 sec)
    

    Showing Trigger Using Client Program

    We can also Show a trigger using a client program.

    Syntax

    To show a trigger through a PHP program, we need to execute the SHOW TRIGGERS statement using the mysqli function query() as follows −

    $sql = "Show TRIGGER";
    $mysqli->query($sql);
    

    To show a trigger through a JavaScript program, we need to execute the SHOW TRIGGERS statement using the query() function of mysql2 library as follows −

    sql = "Show TRIGGER";
    con.query(sql);
    

    To show a trigger through a Java program, we need to execute the SHOW TRIGGERS statement using the JDBC function executeQuery() as follows −

    String sql = "Show TRIGGER";
    statement.executeQuery(sql);
    

    To show a trigger through a python program, we need to execute the SHOW TRIGGERS statement using the execute() function of the MySQL Connector/Python as follows −

    Show_trigger_query = ''SHOW TRIGGER''
    cursorObj.execute(Show_trigger_query)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $db = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } printf(''Connected successfully.
    ''); // Create a trigger $sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score"; if ($mysqli->query($sql)) { printf("Trigger created successfully...!
    "); } else { printf("Trigger creation failed: %s
    ", $mysqli->error); } // Show created trigger details $sql = "SHOW TRIGGERS"; $res = $mysqli->query($sql); if ($res) { while ($row = $res->fetch_assoc()) { // Print trigger details foreach ($row as $key => $value) { printf("%s: %s
    ", $key, $value); } printf("
    "); } $res->free(); } else { printf("Failed to retrieve triggers: %s
    ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Connected successfully.
    Trigger created successfully...!
    Trigger: testTrigger
    Event: UPDATE
    Table: student
    Statement: INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score
    Timing: AFTER
    Created: 2023-09-08 12:16:27.54
    sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
    Definer: root@localhost
    character_set_client: utf8mb4
    collation_connection: utf8mb4_0900_ai_ci
    Database Collation: utf8mb4_0900_ai_ci
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"password"
    });
    
     //Connecting to MySQL
     con.connect(function(err) {
     if (err) throw err;
      //console.log("Connected successfully...!");
      //console.log("--------------------------");
     sql = "USE TUTORIALS";
     con.query(sql);
     sql = "SHOW TRIGGERS";
     con.query(sql);
     console.log("show trigger query executed successfully..!");
     console.log("Triggers: ");
     sql = "SHOW TRIGGERS";
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output produced is as follows −

    show trigger query executed successfully..!
    Triggers:
    [
      {
        Trigger: ''testTrigger'',
        Event: ''UPDATE'',
        Table: ''student'',
        Statement: "INSERT INTO Student SET action = ''update'', Name = OLD.Name, age = OLD.age, score = OLD.score",
        Timing: ''AFTER'',
        Created: 2023-08-01T05:21:18.540Z,
        sql_mode: ''IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION'',
        Definer: ''root@localhost'',
        character_set_client: ''utf8mb4'',
        collation_connection: ''utf8mb4_unicode_ci'',
        ''Database Collation'': ''utf8mb4_0900_ai_ci''
      }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class ShowTrigger {
       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 Trigger sample_trigger BEFORE INSERT ON student FOR EACH ROW BEGIN IF NEW.score < 0 THEN SET NEW.score = 0; END IF; END";
                st.execute(sql);
                System.out.println("Trigger created successfully...!");
                String sql1 = "SHOW TRIGGERS";
                rs = st.executeQuery(sql1);
                System.out.println("Triggers: ");
                while(rs.next())
                {
                   String triggers = rs.getNString(1);
                   System.out.println(triggers);
                }
    
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Trigger created successfully...!
    Triggers:
    sample_trigger
    testTrigger
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    table_name = ''Student''
    trigger_name = ''sample_trigger''
    # Creating a cursor object
    cursorObj = connection.cursor()
    # show trigger
    show_triggers_query = "SHOW TRIGGERS"
    cursorObj.execute(show_triggers_query)
    result = cursorObj.fetchall()
    print("Triggers in the database:")
    for row in result:
        print(row)
    # close the cursor and connection
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    Triggers in the database:
    (''sample_trigger'', ''INSERT'', ''student'', b''BEGINn    IF NEW.Score < 0 THENn        SET NEW.Score = 0;n    END IF;nEND'', ''BEFORE'', datetime.datetime(2023, 7, 31, 11, 38, 5, 880000), {''STRICT_TRANS_TABLES'', ''NO_ENGINE_SUBSTITUTION''}, ''root@localhost'', ''utf8mb4'', ''utf8mb4_0900_ai_ci'', ''utf8mb4_0900_ai_ci'')
    

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

    MySQL – TINYINT

    Table of content


    The MySQL TINYINT Data Type

    The MySQL TINYINT data type is used to store integer values within a very small range. It occupies just 1 byte (8 bits) of storage and can hold values from -128 to 127 for signed TINYINT or 0 to 255 for unsigned TINYINT.

    When you define a TINYINT column in MySQL, by default it is considered as SIGNED. This means it can hold both positive and negative numbers within a specific range. Additionally, you can use either “TINYINT” or “INT1” to define such a column because they work the same way.

    Syntax

    Following is the syntax of the MySQL TINYINT data type −

    TINYINT(M) [SIGNED | UNSIGNED | ZEROFILL]
    

    Example

    First, let us create a table with the name tinyint_table using the below query −

    CREATE TABLE tinyint_table (
       col1 TINYINT,
       col2 TINYINT UNSIGNED,
       col3 TINYINT ZEROFILL
    );
    

    Following is the output obtained −

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

    Now, let us try to insert some values (128, 128, 128) into these columns as shown below −

    INSERT INTO tinyint_table VALUES (128, 128, 128);
    

    An error is generated for the value in col1 because the value we inserted is out of range −

    ERROR 1264 (22003): Out of range value for column ''col1'' at row 1
    

    Next, if we try to insert a negative value into the TINYINT UNSIGNED column (“col2”), it will result in an error because UNSIGNED values cannot be negative −

    INSERT INTO tinyint_table VALUES (127, -120, 128);
    

    The error message displayed is as follows −

    ERROR 1264 (22003): Out of range value for column ''col2'' at row 1
    

    Similarly, if we insert -128 into the TINYINT ZEROFILL column (“col3”), an error will be generated −

    INSERT INTO tinyint_table VALUES (127, 128, -128);
    

    The output is as shown below −

    ERROR 1264 (22003): Out of range value for column ''col3'' at row 1
    

    However, if we insert values within the valid range, the insertion will succeed as shown below −

    INSERT INTO tinyint_table VALUES (127, 128, 128);
    

    Following is the output of the above code −

    Query OK, 1 row affected (0.01 sec)
    

    Finally, we can retrieve all the records present in the table using the following SELECT query −

    SELECT * FROM tinyint_table;
    

    This query will display the following result −

    col1 col2 col3
    127 128 128

    TINYINT Datatype Using a Client Program

    We can also create column of the TINYINT datatype using the client program.

    Syntax

    To create a column of TINYINT datatype through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −

    $sql = ''CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL )
    $mysqli->query($sql);
    

    To create a column of TINYINT datatype through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −

    sql = "CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL )";
    con.query(sql);
    

    To create a column of TINYINT datatype through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −

    String sql = "CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL )";
    statement.execute(sql);
    

    To create a column of TINYINT datatype through a python program, we need to execute the “CREATE TABLE” statement using the execute() function of the MySQL Connector/Python as follows −

    sql = ''CREATE TABLE tinyint_table (col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL)''
    cursorObj.execute(sql)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $dbname = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); $sql = ''CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL ) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } // insert data into created table $q = " INSERT INTO tinyint_table (col1, col2, col3) VALUES (100, 105, 110)"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM tinyint_table"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" Col_1: %s, Col_2: %s, Col_3: %s", $row["col1"], $row["col2"], $row["col3"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();

    Output

    The output obtained is as follows −

    Table created successfully...!
    Data inserted successfully...!
    Table Records:
     Col_1: 100, Col_2: 105, Col_3: 110
    
    var mysql = require("mysql2");
    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "password",
    }); //Connecting to MySQL
    
    con.connect(function (err) {
      if (err) throw err;
      //   console.log("Connected successfully...!");
      //   console.log("--------------------------");
      sql = "USE TUTORIALS";
      con.query(sql);
    
      //create a tinyint_table table, that accepts one column of tinyint type.
      sql = "CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL )";
      con.query(sql);
    
      //insert data into created table
      sql =
        "INSERT INTO tinyint_table (col1, col2, col3) VALUES (100, 105, 110)";
      con.query(sql);
    
      //select datatypes of salary
      sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''tinyint_table'' AND COLUMN_NAME = ''col2''`;
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log(result);
      });
    });
    

    Output

    The output produced is as follows −

    [ { DATA_TYPE: ''tinyint'' } ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class TinyInt {
       public static void main(String[] args) {
          String url = "jdbc:mysql://localhost:3306/TUTORIALS";
          String username = "root";
          String password = "password";
          try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             Connection connection = DriverManager.getConnection(url, username, password);
             Statement statement = connection.createStatement();
             System.out.println("Connected successfully...!");
    
             //TinyInt data types...!;
             String sql = "CREATE TABLE tinyint_table ( col1 TINYINT, col2 TINYINT UNSIGNED, col3 TINYINT ZEROFILL )";
             statement.execute(sql);
             System.out.println("column of a TINYINT type created successfully...!");
             ResultSet resultSet = statement.executeQuery("DESCRIBE tinyint_table");
             while (resultSet.next()){
                System.out.println(resultSet.getString(1)+" "+resultSet.getString(2));
             }
             connection.close();
          } catch (Exception e) {
             System.out.println(e);
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Connected successfully...!
    column of a TINYINT type created successfully...!
    col1 tinyint
    col2 tinyint unsigned
    col3 tinyint(3) unsigned zerofill
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    # Creating a cursor object
    cursorObj = connection.cursor()
    # Create table with Tinyint column
    sql = ''''''
    CREATE TABLE tinyint_table (
    col1 TINYINT,
    col2 TINYINT UNSIGNED,
    col3 TINYINT ZEROFILL
    )''''''
    cursorObj.execute(sql)
    print("The table is created successfully!")
    # Insert data into the created table
    insert_query = "INSERT INTO tinyint_table (col1, col2, col3) VALUES (127, 128, 128);"
    cursorObj.execute(insert_query)
    # Commit the changes after the insert operation
    connection.commit()
    print("Rows inserted successfully.")
    # Now display the table records
    select_query = "SELECT * FROM tinyint_table"
    cursorObj.execute(select_query)
    result = cursorObj.fetchall()
    print("Table Data:")
    for row in result:
        print(row)
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

    The table is created successfully!
    Rows inserted successfully.
    Table Data:
    (127, 128, 128)
    

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

    MySQL – DROP TRIGGER

    Table of content


    Triggers in MySQL are stored programs similar to procedures. These can be created on a table, schema, view and database that are associated with an event and whenever an event occurs the respective trigger is invoked.

    Triggers are, in fact, written to be executed in response to any of the following events −

    • A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
    • A database definition (DDL) statement (CREATE, ALTER, or DROP).
    • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

    You can delete a trigger using the DROP TRIGGER Statement.

    Dropping Trigger in MySQL

    The DROP TRIGGER statement in MySQL will drop a trigger from a database, and all its information.

    Syntax

    Following is the syntax of the MySQL DELETE TRIGGER Statement.

    DROP TRIGGER [IF EXISTS] trigger_name
    

    Where, trigger_name is the name of the trigger you need to delete.

    Example

    Assume we have created a table with name student as shown below −

    CREATE TABLE STUDENT(
       Name varchar(35),
       Age INT,
       Score INT
    );
    

    Following query creates a trigger named sample_trigger on this table. This trigger will set the score value 0 if you enter a value that is less than 0 as score.

    DELIMITER //
    CREATE TRIGGER sample_trigger
    BEFORE INSERT ON STUDENT
    FOR EACH ROW
    BEGIN
       IF NEW.score < 0 THEN SET NEW.score = 0;
    END IF;
    END //
    DELIMITER ;
    

    Now, let us use the following query to drop the trigger we created in the previous step −

    DROP TRIGGER sample_trigger;
    

    Verification

    To verify if the trigger has been dropped, let us display the trigger information using the following query −

    SHOW TRIGGERSG
    

    Since have deleted the trigger created, we get an empty set −

    Empty set (0.11 sec)
    

    With IF EXISTS clause

    If you try to drop a trigger that doesn”t exist an error will be generated as shown below −

    DROP TRIGGER demo;
    

    Following is the output −

    ERROR 1360 (HY000): Trigger does not exist
    

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

    DROP TRIGGER IF EXISTS demo;
    

    Dropping Trigger Using a Client Program

    In addition to create or show a trigger, we can also drop a trigger using a client program.

    Syntax

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

    $sql = "Drop TRIGGER testTrigger";
    $mysqli->query($sql);
    

    To drop a trigger through a JavaScript program, we need to execute the DROP TRIGGER statement using the query() function of mysql2 library as follows −

    sql = "DROP TRIGGER testTrigger";
    con.query(sql);
    

    To drop a trigger through a Java program, we need to execute the DROP TRIGGER statement using the JDBC function execute() as follows −

    String sql = "DROP TRIGGER sample_trigger";
    statement.execute(sql);
    

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

    drop_trigger_query = "DROP TRIGGER sample_trigger"
    cursorObj.execute(drop_trigger_query)
    

    Example

    Following are the programs −

    $dbhost = ''localhost
    $dbuser = ''root
    $dbpass = ''password
    $db = ''TUTORIALS
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    if($mysqli->connect_errno ) {
       printf("Connect failed: %s
    ", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
    ''); $sql = "DROP TRIGGER testTrigger"; if($mysqli->query($sql)){ printf("Trigger dropped successfully...!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as follows −

    Trigger dropped successfully...!
    
    var mysql = require(''mysql2'');
    var con = mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"password"
    });
    
     //Connecting to MySQL
     con.connect(function(err) {
     if (err) throw err;
      //console.log("Connected successfully...!");
      //console.log("--------------------------");
     sql = "USE TUTORIALS";
     con.query(sql);
     sql = "DROP TRIGGER testTrigger";
     con.query(sql);
     console.log("Drop trigger query executed successfully..!");
     console.log("Triggers: ");
     sql = "SHOW TRIGGERS";
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output produced is as follows −

    Drop trigger query executed successfully..!
    Triggers:
    []
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class DropTrigger {
       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 = "DROP TRIGGER sample_trigger";
                st.execute(sql);
                System.out.print("Triggerd dropped successfully...!");
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

       Triggerd dropped successfully...!
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    table_name = ''Student''
    trigger_name = ''sample_trigger''
    # Creating a cursor object
    cursorObj = connection.cursor()
    # drop trigger
    drop_trigger_query = "DROP TRIGGER sample_trigger"
    cursorObj.execute(drop_trigger_query)
    print("Trigger is dropped successfully")
    connection.commit()
    # close the cursor and connection
    cursorObj.close()
    connection.close()
    

    Output

    Following is the output of the above code −

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

    MySQL – After Insert Trigger



    A Trigger is simply defined as a response to an event. In MySQL, a trigger is a special stored procedure that resides in the system catalogue, that is executed whenever an event is performed. These events include SQL statements like INSERT, UPDATE and DELETE etc.

    It is called a special stored procedure as it does not require to be invoked explicitly like other stored procedures. The trigger acts automatically whenever the desired event is fired.

    MySQL After Insert Trigger

    The After Insert Trigger is a row-level trigger supported by the MySQL database. As its name suggests, the After Insert Trigger is executed right after a value is inserted into a database table.

    A row-level trigger is a type of trigger that goes off every time a row is modified. Simply, for every single transaction made in a table (like insertion, deletion, update), one trigger acts automatically.

    To elaborate, whenever an INSERT statement is executed in the database, the value is inserted into the table first followed by the trigger execution. Hence, one cannot update a newly inserted row using the AFTER INSERT trigger.

    Syntax

    Following is the syntax to create the AFTER INSERT trigger in MySQL −

    CREATE TRIGGER trigger_name
    AFTER INSERT ON table_name FOR EACH ROW
    BEGIN
       -- trigger body
    END;
    

    Example

    Let us see an example demonstrating the AFTER INSERT trigger. In here, we are creating a new table named USERS, which contains the details of users of an application, using the following query −

    CREATE TABLE USERS(
       ID INT AUTO_INCREMENT,
       NAME VARCHAR(100) NOT NULL,
       AGE INT NOT NULL,
       BIRTH_DATE VARCHAR(100),
       PRIMARY KEY(ID)
    );
    

    Now, let us create another table ”PUSH_NOTIFICATIONS” that is used to store messages to send as push notifications to the users on their birthdays −

    CREATE TABLE PUSH_NOTIFICATIONS(
       ID INT AUTO_INCREMENT,
       BIRTH_DATE VARCHAR(100),
       NOTIFICATIONS VARCHAR(255) NOT NULL,
       PRIMARY KEY(ID)
    );
    

    Using the following CREATE TRIGGER statement, create a new trigger after_trigger on the USERS table to insert values into the PUSH_NOTIFICATIONS table −

    DELIMITER //
    CREATE TRIGGER after_trigger AFTER INSERT ON USERS FOR EACH ROW
    BEGIN
       IF NEW.BIRTH_DATE IS NOT NULL THEN
       INSERT INTO PUSH_NOTIFICATIONS VALUES
       (new.ID, new.BIRTH_DATE, CONCAT(''Happy Birthday, '', NEW.NAME, ''!''));
    END IF;
    END //
    DELIMITER ;
    

    Insert values into the USERS table using the regular INSERT statement as shown below −

    INSERT INTO USERS (NAME, AGE, BIRTH_DATE) VALUES
    (''Sasha'', 23, ''24/06/1999'');
    (''Alex'', 21, ''12/01/2001'');
    

    Verification

    To verify if the trigger has been executed, display the PUSH_NOTIFICATIONS table using the SELECT statement −

    ID BIRTH_DATE NOTIFICATIONS
    1 24/06/1999 Happy Birthday, Sasha!
    2 12/01/2001 Happy Birthday, Alex!

    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