Category: mysql

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

    MySQL – Date and Time Functions



    In MySQL, we have a set of functions using which we can manipulate the date and time values. Following are the MySQL date time functions −

    Sr.No. Name & Description
    1

    This function adds two given dates

    2

    This function adds given time values

    3

    This function converts from one timezone to another

    4

    This function returns the current date

    5

    Synonyms for CURDATE()

    6

    Synonyms for CURTIME()

    7

    Synonyms for NOW()

    8

    This function returns the current time

    9

    Adds two dates

    10

    This function formats the given date as specified

    11

    This function subtracts two dates

    12

    This function extracts the date part of a date or datetime expression

    13

    This function subtracts two dates

    14

    This function retrieves the day of the month from the given date

    15

    This function returns the name of the weekday

    16

    This function returns the day of the month (1-31)

    17

    This function returns the weekday index of the argument

    18

    This function returns the day of the year (1-366)

    19

    This function extracts part of a date

    20

    This function converts a day number to a date

    21

    This function formats date as a UNIX timestamp

    22

    This function Extracts the hour

    23

    This function returns the last day of the month for the argument

    24

    Synonym for NOW()

    25

    Synonym for NOW()

    26

    This function creates a date from the year and day of year

    27

    This function creates a time value from the given hours, minutes, and seconds.

    28

    This function returns the microseconds from argument

    29

    This function returns the minute from the argument

    30

    This function returns the month from the date passed

    31

    This function returns the name of the month

    32

    This function returns the current date and time

    33

    This function adds a period to a year-month

    34

    This function returns the number of months between periods

    35

    This function returns the quarter from a date argument

    36

    This function converts seconds to ”HH:MM:SS” format

    37

    This function returns the second (0-59)

    38

    This function converts a string to a date

    39

    This function subtracts the specified interval to a date value

    40

    This function subtracts the specified time interval to a date time or, time value

    41

    This function returns the time at which the function executes

    42

    This function formats the given date in the specified format

    43

    This function returns the argument converted to seconds

    44

    This function extracts the time portion of the expression passed

    45

    This function subtracts two time values

    46

    With a single argument, this function returns the date or datetime expression. With two arguments, the sum of the arguments

    47

    This function adds an interval to a datetime expression

    48

    This function subtracts an interval from a datetime expression

    49

    This function returns the date argument converted to days

    50

    This function returns a UNIX timestamp

    51

    This function returns the current UTC date

    52

    This function returns the current UTC time

    53

    This function returns the current UTC date and time

    54

    This function returns the week number

    55

    This function returns the weekday index

    56

    This function returns the calendar week of the date (1-53)

    57

    This function returns the year

    58

    This function returns the year and week

    59

    This function converts the date or date-time values into seconds and returns the result.


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

    MySQL – UUID

    Table of content


    The MySQL UUID function

    The MySQL UUID() function is used to generate “Universal Unique Identifiers” (UUIDs) in accordance with RFC 4122. UUIDs are designed to be universally unique, even when generated on different servers. The UUID is generated using a combination of the current timestamp, the unique identifier of the server, and a random number.

    UUID Format

    The UUID value is represented as a UTF-8 string and is a 128-bit number. The format of the UUID value is in hexadecimal number, and it consists of five segments which are separated by hyphens.

    The general format of the UUID value is: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee, where each segment represents a hexadecimal value.

    Generating a UUID

    Following is the basic example to generate a UUID using the UUID() function in MySQL −

    SELECT UUID();
    

    Output

    It will display a universal unique identifier as shown below −

    UUID()
    55f7685d-e99c-11ed-adfc-88a4c2bbd1f9

    Generating Multiple UUIDs

    You can generate multiple UUIDs in a single query, and each UUID will be different as shown below −

    SELECT UUID() AS ID1, UUID() AS ID2;
    

    Output

    The output will show two different UUIDs, with differences generally in the first segment −

    ID1 ID2
    78c3fb43-e99c-11ed-adfc-88a4c2bbd1f9 78c3fb4f-e99c-11ed-adfc-88a4c2bbd1f9

    UUIDs in a Database Table

    You can use UUIDs as unique identifiers in a database table. Following is an example of how to create a table with a UUID column and insert data −

    Here, we are first creating a table with the name “ORDERS”, with an ORDER_ID column of type VARCHAR using the following query −

    CREATE TABLE ORDERS(
       ID int auto_increment primary key,
       NAME varchar(40),
       PRODUCT varchar(40),
       ORDER_ID varchar(100)
    );
    

    Now, we are inserting data into the ORDERS table, using the UUID() function to generate unique values for the ORDER_ID column −

    INSERT INTO ORDERS (NAME, PRODUCT, ORDER_ID) VALUES ("Varun", "Headphones", UUID());
    INSERT INTO ORDERS (NAME, PRODUCT, ORDER_ID) VALUES ("Priya", "Mouse", UUID());
    INSERT INTO ORDERS (NAME, PRODUCT, ORDER_ID) VALUES ("Nikhil", "Monitor", UUID());
    INSERT INTO ORDERS (NAME, PRODUCT, ORDER_ID) VALUES ("Sarah", "Keyboard", UUID());
    INSERT INTO ORDERS (NAME, PRODUCT, ORDER_ID) VALUES ("Vaidhya", "Printer", UUID());
    

    Following is the ORDERS table obtained −

    ID NAME PRODUCT ORDER_ID
    1 Varun Headphones a45a9632-e99d-11ed-adfc-88a4c2bbd1f9
    2 Priya Mouse a45b03a3-e99d-11ed-adfc-88a4c2bbd1f9
    3 Nikhil Monitor a45b49cc-e99d-11ed-adfc-88a4c2bbd1f9
    4 Sarah Keyboard a45b8d3f-e99d-11ed-adfc-88a4c2bbd1f9
    5 Vaidhya Printer a4b003d0-e99d-11ed-adfc-88a4c2bbd1f9

    Modifying UUIDs

    You can modify UUIDs without losing their uniqueness. For example, you can remove hyphens or convert them to base64 notation using functions like REPLACE() and TO_BASE64().

    Example

    Here, we are updating the UUID value for the record where ID = 1 using the following query −

    UPDATE ORDERS SET ORDER_ID = UUID() WHERE ID=1;
    

    Output

    Following is the output of the above code −

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

    Verification

    To verify the modified UUID values, we can use the following SELECT query −

    SELECT * FROM ORDERS;
    

    As we can see in the output below, every time we execute the UUID() function, we get a different UUID value −

    ID NAME PRODUCT ORDER_ID
    1 Varun Headphones 38f4d94a-e99d-11ed-adfc-88a4c2bbd1f9
    2 Priya Mouse a45b03a3-e99d-11ed-adfc-88a4c2bbd1f9
    3 Nikhil Monitor a45b49cc-e99d-11ed-adfc-88a4c2bbd1f9
    4 Sarah Keyboard a45b8d3f-e99d-11ed-adfc-88a4c2bbd1f9
    5 Vaidhya Printer a4b003d0-e99d-11ed-adfc-88a4c2bbd1f9

    Example

    Assume the previously created table and let us remove hyphens from the UUID of the row with ID = 2 using the REPLACE() function as shown below −

    UPDATE ORDERS
    SET ORDER_ID = REPLACE(UUID(), ''-'', '''')
    WHERE ID = 2;
    

    Output

    Output of the above code is as follows −

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

    Verification

    To verify the modified UUID value, we can use the following SELECT query −

    SELECT * FROM ORDERS;
    

    As we can see in the output below, the UUID of row = 2 is modified without disturbing the “unique” part of it −

    ID NAME PRODUCT ORDER_ID
    1 Varun Headphones a45a9632-e99d-11ed-adfc-88a4c2bbd1f9
    2 Priya Mouse 069b0ca-7e99e11ed-adfc-88a4c2bbd1f9
    3 Nikhil Monitor a45b49cc-e99d-11ed-adfc-88a4c2bbd1f9
    4 Sarah Keyboard a45b8d3f-e99d-11ed-adfc-88a4c2bbd1f9
    5 Vaidhya Printer a4b003d0-e99d-11ed-adfc-88a4c2bbd1f9

    Example

    In the following query, we are converting the UUID of ID = 4 to base64 notation using the TO_BASE64() function −

    UPDATE ORDERS
    SET ORDER_ID = TO_BASE64(UNHEX(REPLACE(UUID(),''-'','''')))
    WHERE ID=4;
    

    Output

    The result produced is as follows −

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

    Verification

    Let us verify the modified UUID value using the following SELECT query −

    SELECT * FROM ORDERS;
    

    The output produced is as given below −

    ID NAME PRODUCT ORDER_ID
    1 Varun Headphones a45a9632-e99d-11ed-adfc-88a4c2bbd1f9
    2 Priya Mouse 069b0ca7-e99e11ed-adfc-88a4c2bbd1f9
    3 Nikhil Monitor a45b49cc-e99d-11ed-adfc-88a4c2bbd1f9
    4 Sarah Keyboard ObRYA+mfEe2t/IikwrvR+Q==
    5 Vaidhya Printer a4b003d0-e99d-11ed-adfc-88a4c2bbd1f9

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

    MySQL – Aggregate Functions



    In general, aggregation is a consideration of a collection of objects that are bound together as a single entity. MySQL provides a set of aggregate functions that perform operations on all the entities of the column of a table considering them as a single unit. Following are the MySQL aggregate functions −

    Sr.No. Name & Description
    1

    This function is used to calculate the average value.

    2

    This function is used to calculate the bitwise AND value.

    3

    This function is used to calculate the bitwise OR value.

    4

    This function is used to calculate the bitwise XOR value.

    5

    This function is used to count the number of rows returned.

    6

    This function returns the concatenated string.

    7

    This function returns the given values as a single JSON array.

    8

    This function returns the given values as a single JSON object.

    9

    This function returns the maximum value.

    10

    This function returns the minimum value.

    11

    This function calculates and returns the population standard deviation.

    12

    This function calculates and returns the population standard deviation.

    13

    This function calculates and returns the population standard deviation.

    14

    This function calculates and returns the sample standard deviation.

    15

    This function is used to calculate the sum of the values.

    16

    This function calculates and returns the population standard variance.

    17

    This function calculates and returns the sample variance.

    18

    This function calculates and returns the population standard variance.


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

    MySQL – String Functions



    MySQL – String Functions

    MySQL string functions are used to manipulate the string values. The following table details the string functions that are available in the MySQL.

    Sr.No. Name & Description
    1

    This function returns numeric value of left-most character.

    2

    This function returns a string representation of the argument.

    3

    This function returns length of argument in bits.

    4

    This function returns the character for each integer passed.

    5

    This function returns number of characters in argument.

    6

    This function is a synonym for CHAR_LENGTH().

    7

    This function returns concatenated string.

    8

    This function returns concatenate with separator.

    9

    This function returns string at index number.

    10

    This function returns a string such that for every bit set in the value bits, you get an on string and for every unset bit, you get an off string.

    11

    This function returns the index (position) of the first argument in the subsequent arguments.

    12

    This function returns the index position of the first argument within the second argument.

    13

    This function decodes a base-64 encoded string as a binary string.

    14

    Inserts a substring at the specified position up to the specified number of characters.

    15

    This function returns the index of the first occurrence of substring.

    16

    Synonym for LOWER().

    17

    This function returns the leftmost number of characters as specified.

    18

    This function returns the length of a string in bytes.

    19

    This function is used to load the specified file.

    20

    This function returns the position of the first occurrence of substring.

    21

    This function returns the argument in lowercase.

    22

    This function returns the string argument, left-padded with the specified string.

    23

    This function is used to removes leading spaces from the given string.

    24

    This function returns a set of comma-separated strings that have the corresponding bit in bits set.

    25

    This function returns a substring starting from the specified position.

    26

    This function returns a string representation of the octal argument.

    27

    This function is a synonym for LENGTH().

    28

    If the leftmost character of the argument is a multi-byte character, returns the code for that character.

    29

    This function is a synonym for LOCATE().

    30

    This function escapes the argument for use in an SQL statement.

    31

    This function returns the starting index of the substring matching given regular expression.

    32

    This function replaces the matched sub string with the replacement string and returns the result.

    33

    This function is used to reverse the characters in a string

    34

    This function returns the specified rightmost number of characters.

    35

    This function is used to add padding to the right side of the string until it reaches the desired length.

    36

    This function is used to remove trailing spaces.

    37

    This function returns a soundex string.

    38

    This function returns a string of the specified number of spaces.

    39

    This function is used to compare two given strings.

    40

    This function returns the substring as specified.

    41

    This function returns the substring as specified.

    42

    This function returns a substring from a string before the specified number of occurrences of the delimiter.

    43

    This function encodes a string value to base-64 string.

    44

    This function is used to removes the leading and trailing spaces of the given string.

    45

    This function is a synonym for UPPER().

    46

    This function converts each pair of hexadecimal digits to a character.

    47

    This function is used to convert the characters in the given string to uppercase.

    48

    This function returns the weight string value of the given argument.

    49

    This operator is used to search for particular string in the specified list of columns.

    50

    This operator is similar to the REGEXP_LIKE() function it is used to match a particular pattern in the given string.

    51

    This operator is used to compare the soundex values of two strings.


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

    MySQL – Numeric Functions



    MySQL – Numeric Functions

    MySQL numeric functions are used primarily for numeric manipulation and/or mathematical calculations. The following table details the numeric functions that are available in the MySQL.

    Sr.No. Name & Description
    1

    Returns the absolute value of numeric expression.

    2

    Returns the arccosine of numeric expression. Returns NULL if the value is not in the range -1 to 1.

    3

    Returns the arcsine of numeric expression. Returns NULL if value is not in the range -1 to 1

    4

    Returns the arctangent of numeric expression.

    5

    Returns the arctangent of the two variables passed to it.

    6

    Returns the smallest integer value that is not less than passed numeric expression

    7

    Returns the smallest integer value that is not less than passed numeric expression

    8

    Converts numeric expression from one base to another.

    9

    Returns the cosine of passed numeric expression. The numeric expression should be expressed in radians.

    10

    Returns the cotangent of passed numeric expression.

    11

    Returns the Cyclic Redundancy Check (CRC) for the given value.

    12

    Returns numeric expression converted from radians to degrees.

    13

    Returns the base of the natural logarithm (e) raised to the power of passed numeric expression.

    14

    Returns the largest integer value that is not greater than passed numeric expression.

    15

    Returns a numeric expression rounded to a number of decimal places.

    16

    returns the hexadecimal representation of the given value.

    17

    Returns the natural logarithm of the passed numeric expression.

    18

    Returns the natural logarithm of the passed numeric expression.

    19

    Returns the base-10 logarithm of the passed numeric expression.

    20

    Returns the base-2 logarithm of the passed numeric expression.

    21

    Returns the remainder of one expression by diving by another expression.

    22

    Returns the value of pi

    23

    Returns the value of one expression raised to the power of another expression

    24

    Returns the value of one expression raised to the power of another expression

    25

    Returns the value of passed expression converted from degrees to radians.

    26

    Returns a random floating-point value with in the range 0 to 1.0.

    27

    Returns numeric expression rounded to an integer. Can be used to round an expression to a number of decimal points

    28

    Returns the sign of the given number.

    29

    Returns the sine of numeric expression given in radians.

    30

    Returns the non-negative square root of numeric expression.

    31

    Returns the tangent of numeric expression expressed in radians.

    32

    Returns numeric exp1 truncated to exp2 decimal places. If exp2 is 0, then the result will have no decimal point.


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

    MySQL – NULL Values

    Table of content


    The MySQL NULL Values

    MySQL uses the term “NULL” to represent a non-existent data value in the database. These values are different from an empty string or zero and do not occupy any storage space in the database. They are used to indicate the absence of a value or an unknown value in a data field.

    There are some common reasons why a value may be NULL −

    • The value may not be provided during data entry.

    • The value is not yet known.

    Since NULL values are non-existent, you cannot use standard comparison operators such as “=”, “<,” or “>” with them. Instead, you can use the “IS NULL,” “IS NOT NULL,” or “NOT NULL” operators to check if a value is NULL.

    Creating a Table without NULL Values

    To create a table without NULL values, you can use the “NOT NULL” keyword while defining the columns. If a column is specified as “NOT NULL,” an error will occur when attempting to insert NULL values into that specific column.

    Syntax

    The basic syntax for creating a table with “NOT NULL” columns is as follows −

    CREATE TABLE table_name (
       column1 datatype NOT NULL,
       column2 datatype NOT NULL,
       ...
       columnN datatype
    );
    

    Where, “NOT NULL” indicates that a column must always contain a specific value of the defined data type. Columns marked as “NOT NULL” cannot accept NULL values. On the other hand, you can insert NULL values into the columns without the “NOT NULL” constraint.

    Example

    Let us create a table named “CUSTOMERS” using the following query −

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

    Now, let us insert some records into the above-created table −

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

    The CUSTOMERS table obtained is as follows −

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

    Now, to retrieve records that are not NULL, you can use the “IS NOT NULL” operator as shown below−

    SELECT ID, NAME, AGE, ADDRESS, SALARY
    FROM CUSTOMERS
    WHERE SALARY IS NOT NULL;
    

    Following is the output of the above code −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00

    To retrieve records that are NULL, you can use the “IS NULL” operator as shown below −

    SELECT ID, NAME, AGE, ADDRESS, SALARY
    FROM CUSTOMERS
    WHERE SALARY IS NULL;
    

    The output produced is as follows −

    ID NAME AGE ADDRESS SALARY
    6 Komal 22 Hyderabad NULL
    7 Muffy 24 Indore NULL

    Updating NULL Values in a Table

    To update NULL values in a table, you can use the “UPDATE” statement with the “IS NULL” operator. This filter the rows containing NULL values and set new values using the “SET” keyword.

    Example

    Here, we are updating the NULL values in the SALARY column of the CUSTOMERS table as shown below −

    UPDATE CUSTOMERS SET SALARY = 9000 WHERE SALARY IS NULL;
    

    Output

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

    Query OK, 2 rows affected (0.01 sec)
    Rows matched: 2  Changed: 2  Warnings: 0
    

    Verification

    You can verify whether the records in the table are updated or not using the following query −

    SELECT * FROM CUSTOMERS;
    

    The output displayed is as follows −

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

    Deleting Records with NULL Values

    To delete records with NULL values from a table, you can use the “DELETE FROM” statement with the “IS NULL” operator in the “WHERE” clause.

    Example

    Now, we are deleting records with NULL values in the SALARY column as shown below −

    DELETE FROM CUSTOMERS WHERE SALARY IS NULL;
    

    Output

    Output of the above code is as shown below −

    Query OK, 2 rows affected (0.01 sec)
    

    Verification

    You can verify whether the records in the table is deleted or not using the SELECT statement as follows −

    SELECT * FROM CUSTOMERS;
    

    The table produced is as shown below −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00

    NULL Value Using a Client Program

    We can also execute NULL value using the client program.

    Syntax

    To check whether a column”s value is null through a PHP program, we need to execute the “SELECT” statement using the mysqli function query() as follows −

    $sql = "SELECT * from tcount_tbl WHERE tutorial_count IS NULL";
    $mysqli->query($sql);
    

    To check whether a column”s value is null through a JavaScript program, we need to execute the “SELECT” statement using the query() function of mysql2 library as follows −

    sql = "SELECT * from tcount_tbl WHERE tutorial_count IS NOT NULL";
    con.query(sql);
    

    To check whether a column”s value is null through a Java program, we need to execute the “SELECT” statement using the JDBC function executeQuery() as follows −

    String sql = "SELECT * FROM tcount_tbl WHERE tutorial_count IS NULL";
    statement.executeQuery(sql);
    

    To check whether a column”s value is null through a Python program, we need to execute the “SELECT” statement using the execute() function of the MySQL Connector/Python as follows: −

    null_values_query = "SELECT * FROM tcount_tbl WHERE tutorial_count IS NULL"
    cursorObj.execute(null_values_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 = "SELECT * from tcount_tbl WHERE tutorial_count IS NULL"; if($result = $mysqli->query($sql)){ printf("Table record: n"); while($row = mysqli_fetch_array($result)){ printf("Tutorial_author %s, Tutorial_count %d", $row[''tutorial_author''], $row[''tutorial_count'']); printf("n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as shown below −

    Table record:
    Tutorial_author mahnaz, Tutorial_count 0
    Tutorial_author Jen, Tutorial_count 0
    
    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 = "SELECT * from tcount_tbl WHERE tutorial_count IS NOT NULL";
     if(con.query(sql)){
        console.log("Select query executed successfully....!");
     }
     else{
        console.log("Error");
     }
     console.log("Table records: ");
     con.query(sql, function(err, result){
     if (err) throw err;
     console.log(result);
     });
    });
    

    Output

    The output obtained is as shown below −

    Select query executed successfully....!
    Table records:
    [
      { tutorial_author: ''mahran'', tutorial_count: 20 },
      { tutorial_author: ''Gill'', tutorial_count: 20 }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class NullValues {
       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 = " SELECT * FROM tcount_tbl WHERE tutorial_count = NULL";
                rs = st.executeQuery(sql);
                System.out.println("Table records(tutorial_count = null): ");
                while(rs.next()) {
                   String tutorial_author = rs.getString("tutorial_author");
                   String tutorial_count = rs.getString("tutorial_count");
                   System.out.println("Author: " + tutorial_author + ", Tutorial_count: " + tutorial_count);
                }
                String sql1 = "SELECT * FROM tcount_tbl WHERE tutorial_count IS NULL";
                rs = st.executeQuery(sql1);
                System.out.println("Table records(tutorial_count is null): ");
                while(rs.next()) {
                   String tutorial_author = rs.getString("tutorial_author");
                   String tutorial_count = rs.getString("tutorial_count");
                   System.out.println("Author: " + tutorial_author + ", Tutorial_count: " + tutorial_count);
                }
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    This will generate the following output -
    Table records(tutorial_count = null):
    Table records(tutorial_count is null):
    Author: mahnaz, Tutorial_count: null
    Author: Jen, Tutorial_count: null
    
    import mysql.connector
    #establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    cursorObj = connection.cursor()
    null_values_query = f"""
    SELECT * FROM tcount_tbl
    WHERE tutorial_count IS NULL
    """
    cursorObj.execute(null_values_query)
    # Fetching all the rows that meet the criteria
    filtered_rows = cursorObj.fetchall()
    for row in filtered_rows:
        print(row)
    cursorObj.close()
    connection.close()
    

    Output

    The output obtained is as shown below −

    (''mahnaz'', None)
    (''Jen'', 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 – Using Sequences nhận dự án làm có lương

    MySQL – Sequences

    Table of content


    A sequence is a series of integers, starting from 1 and incrementing by 1 with each successive value. These sequences are usually used in databases, as many applications require each row in a table to have a unique identifier, and sequences provide an easy way to generate such values.

    Sequences in MySQL

    MySQL does not have a built-in sequence feature but provides an alternative in the form of the AUTO_INCREMENT column, which serves a similar purpose.

    In MySQL, the AUTO_INCREMENT attribute is used to automatically generate unique integer values (sequences) for a column. By default, this sequence begins with an initial value of 1 and increments by 1 for each new row that is added.

    Syntax

    Following is the syntax of AUTO_INCREMENT attribute in MySQL −

    CREATE TABLE table_name (
       column1 datatype AUTO_INCREMENT,
       column2 datatype,
       column3 datatype,
       ...
       columnN datatype
    );
    

    Example

    In the following example, we are creating a table named “CUSTOMERS” and, in addition, defining the AUTO_INCREMENT attribute for the “ID” column of the table −

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

    Now, let us insert some records into the above-created table −

    INSERT INTO CUSTOMERS VALUES
    (NULL, ''Ramesh'', 32, ''Ahmedabad'', 2000.00),
    (NULL, ''Khilan'', 25, ''Delhi'', 1500.00),
    (NULL, ''Kaushik'', 23, ''Kota'', 2000.00),
    (NULL, ''Chaitali'', 25, ''Mumbai'', 6500.00),
    (NULL, ''Hardik'', 27, ''Bhopal'', 8500.00),
    (NULL, ''Komal'', 22, ''Hyderabad'', 4500.00),
    (NULL, ''Muffy'', 24, ''Indore'', 10000.00);
    

    Output

    We can see in the table displayed below that the values in the “ID” column are automatically incremented −

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

    Retrieving AUTO_INCREMENT Values

    To obtain AUTO_INCREMENT values in MySQL, you can use the LAST_INSERT_ID() SQL function. This function can be used in any client that can issue SQL statements. Alternatively, in PERL and PHP scripts, specific functions are available to retrieve the auto-incremented value of the last record.

    PERL Example

    You can access the AUTO_INCREMENT value generated by a query using the mysql_insertid attribute. This attribute can be accessed either through a database handle or a statement handle, depending on how you execute the query.

    The following example references it through the database handle −

    $dbh->do ("INSERT INTO insect (name,date,origin)
    VALUES(''moth'',''2001-09-14'',''windowsill'')");
    my $seq = $dbh->{mysql_insertid};
    

    PHP Example

    After executing a query that generates an AUTO_INCREMENT value, you can retrieve the value using the mysql_insert_id( ) command −

    mysql_query ("INSERT INTO insect (name,date,origin)
    VALUES(''moth'',''2001-09-14'',''windowsill'')", $conn_id);
    $seq = mysql_insert_id ($conn_id);
    

    Renumbering an Existing Sequence

    In some cases, you may need to re-sequence records in a table, especially if you have deleted many records. Be careful when resequencing if your table is related to other tables through joins.

    If you determine that the resequencing of an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the AUTO_INCREMENT column from the table, then add it again.

    Example

    The following example shows how to renumber the id values in the table using this technique.

    ALTER TABLE CUSTOMERS DROP id;
    ALTER TABLE CUSTOMERS
    ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
    ADD PRIMARY KEY (id);
    

    Output

    Following is the output obtained −

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

    Starting a Sequence at a Specific Value

    By default, MySQL starts sequences from 1, but you can specify a different initial value when creating the table.

    Example

    The following example demonstrates how to start the sequence from 100 during table creation −

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

    Output

    Output of the above code is as shown below −

    Query OK, 0 rows affected (0.04 sec)
    

    Alternatively, you can create the table first and then set the initial sequence value using the ALTER TABLE command as shown below −

    ALTER TABLE CUSTOMERS AUTO_INCREMENT = 100;
    

    Sequence Using a Client Program

    We can also create a sequence using the client program.

    Syntax

    To create a sequence on a column of a table through a PHP program, we need to specify auto_increment for a specific column while creating the table using the mysqli function query() as follows −

    $sql = "CREATE TABLE insect (id INT UNSIGNED NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL)";
    $mysqli->query($sql);
    

    To create a sequence on a column of a table through a JavaScript program, we need to specify auto_increment for a specific column while creating the table using the query() function of mysql2 library as follows −

    sql = "CREATE TABLE insect (id INT UNSIGNED NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL)";
    con.query(sql);
    

    To create a sequence on a column of a table through a Java program, we need to specify auto_increment for a specific column while creating the table using the JDBC function execute() as follows −

    String sql = "CREATE TABLE insect (id INT UNSIGNED NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL)";
    statement.execute(sql);
    

    To create a sequence on a column of a table through a Python program, we need to specify auto_increment for a specific column while creating the table using the execute() function of the MySQL Connector/Python as follows −

    create_table_query = "CREATE TABLE insect (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id), name VARCHAR(30) NOT NULL, date DATE NOT NULL, origin VARCHAR(30) NOT NULL)"
    cursorObj.execute(create_table_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 table with autoincrement sequene $sql = "CREATE TABLE insect (id INT UNSIGNED NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL)"; if($mysqli->query($sql)){ printf("Table created successfully....!n"); } //let''s insert some record $sql = "INSERT INTO insect (id,name,date,origin) VALUES(NULL,''housefly'',''2001-09-10'',''kitchen'')"; if($mysqli->query($sql)){ printf("First record inserted successfully...!n"); } $sql = "INSERT INTO insect (id,name,date,origin) VALUES(NULL,''millipede'',''2001-09-10'',''driveway'')"; if($mysqli->query($sql)){ printf("Second record inserted successfully...!n"); } $sql = "INSERT INTO insect (id,name,date,origin) VALUES(NULL,''grasshopper'',''2001-09-10'',''front yard'')"; if($mysqli->query($sql)){ printf("Third record inserted successfully...!n"); } printf("Table records: n"); $sql = "SELECT * FROM insect"; if($result = $mysqli->query($sql)){ printf("Table record: n"); while($row = mysqli_fetch_array($result)){ printf("Id: %d, Name: %s, Date: %s, Origin %s", $row[''id''], $row[''name''], $row[''date''], $row[''origin'']); printf("n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as shown below −

    Table created successfully....!
    First record inserted successfully...!
    Second record inserted successfully...!
    Third record inserted successfully...!
    Table records:
    Table record:
    Id: 1, Name: housefly, Date: 2001-09-10, Origin kitchen
    Id: 2, Name: millipede, Date: 2001-09-10, Origin driveway
    Id: 3, Name: grasshopper, Date: 2001-09-10, Origin front yard
    
    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 table
     sql = "CREATE TABLE insect (id INT UNSIGNED NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL)";
     con.query(sql, function(err, result){
        if (err) throw err;
        console.log("Table created successfully....!");
        });
    //now let''s insert some record
    sql = "INSERT INTO insect (id,name,date,origin) VALUES(NULL,''housefly'',''2001-09-10'',''kitchen'')";
    con.query(sql, function(err, result){
        if (err) throw err;
        console.log("First record inserted successfully...!");
        });
    sql = "INSERT INTO insect (id,name,date,origin) VALUES(NULL,''millipede'',''2001-09-10'',''driveway'')";
    con.query(sql, function(err, result){
        if (err) throw err;
        console.log("Second record inserted successfully...!");
        });
    sql = "INSERT INTO insect (id,name,date,origin) VALUES(NULL,''grasshopper'',''2001-09-10'',''front yard'')";
        con.query(sql, function(err, result){
        if (err) throw err;
        console.log("Third record inserted successfully...!");
        });
    sql = "SELECT * FROM INSECT";
    con.query(sql, function(err, result){
    console.log("Table records(with ID auto_increment sequence).");
        if (err) throw err;
        console.log(result);
        });
    });
    

    Output

    The output obtained is as shown below −

    Table created successfully....!
    First record inserted successfully...!
    Second record inserted successfully...!
    Third record inserted successfully...!
    Table records(with ID auto_increment sequence).
    [
      {
        id: 1,
        name: ''housefly'',
        date: 2001-09-09T18:30:00.000Z,
        origin: ''kitchen''
      },
      {
        id: 2,
        name: ''millipede'',
        date: 2001-09-09T18:30:00.000Z,
        origin: ''driveway''
      },
      {
        id: 3,
        name: ''grasshopper'',
        date: 2001-09-09T18:30:00.000Z,
        origin: ''front yard''
      }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class Sequence {
       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 table
                String sql = "CREATE TABLE insect (id INT UNSIGNED NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL)";
                st.execute(sql);
                System.out.println("Table ''insect'' created successfully...!");
                //lets insert some records into the table
                String sql1 = "INSERT INTO insect (id,name,date,origin) VALUES(NULL,''housefly'',''2001-09-10'',''kitchen''), (NULL,''millipede'',''2001-09-10'',''driveway''), (NULL,''grasshopper'',''2001-09-10'',''front yard'')";
                st.execute(sql1);
                System.out.println("Records inserted successfully...!");
                //lets print table records
                String sql2 = "SELECT * FROM INSECT";
                rs = st.executeQuery(sql2);
                System.out.println("Table records: ");
                while(rs.next()) {
                   String id = rs.getString("id");
                   String name = rs.getString("name");
                   String date = rs.getString("date");
                   String origin = rs.getString("origin");
                   System.out.println("Id: " + id + ", Name: " + name + ", Date: " + date + ", Origin: " + origin);
                }
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Table ''insect'' created successfully...!
    Records inserted successfully...!
    Table records:
    Id: 1, Name: housefly, Date: 2001-09-10, Origin: kitchen
    Id: 2, Name: millipede, Date: 2001-09-10, Origin: driveway
    Id: 3, Name: grasshopper, Date: 2001-09-10, Origin: front yard
    
    import mysql.connector
    # Connecting to MySQL
    con = mysql.connector.connect(
        host="localhost",
        user="root",
        password="password",
        database="tut"
    )
    # Creating a cursor object
    cursorObj = con.cursor()
    # Creating the table
    create_table_query = """
    CREATE TABLE insect (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (id),
    name VARCHAR(30) NOT NULL,
    date DATE NOT NULL,
    origin VARCHAR(30) NOT NULL
    )
    """
    cursorObj.execute(create_table_query)
    print("Table ''insect'' is created successfully!")
    # Inserting records
    sql = "INSERT INTO insect (name, date, origin) VALUES (%s, %s, %s)"
    values = [
        (''housefly'', ''2001-09-10'', ''kitchen''),
        (''millipede'', ''2001-09-10'', ''driveway''),
        (''grasshopper'', ''2001-09-10'', ''front yard'')
    ]
    cursorObj.executemany(sql, values)
    print("Data inserted into the ''insect'' table.")
    con.commit()
    # Retrieving records
    cursorObj.execute("SELECT * FROM insect")
    records = cursorObj.fetchall()
    # Printing the records
    print("Table records(with ID auto_increment sequence).")
    for record in records:
        print(record)
    # Closing the connection
    cursorObj.close()
    con.close()
    

    Output

    The output obtained is as shown below −

    Table ''insect'' is created successfully!
    Data inserted into the ''insect'' table.
    Table records(with ID auto_increment sequence).
    (1, ''housefly'', datetime.date(2001, 9, 10), ''kitchen'')
    (2, ''millipede'', datetime.date(2001, 9, 10), ''driveway'')
    (3, ''grasshopper'', datetime.date(2001, 9, 10), ''front yard'')
    

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

    MySQL – Transactions

    Table of content


    The MySQL Transactions

    The MySQL transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will never be complete unless each individual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail.

    Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction. This will ensure no data losses or failed executions of SQL queries.

    Properties of Transactions

    There are four standard properties of transactions, often referred to by the acronym ACID

    • Atomicity − This ensures that all operations within a transaction are treated as a single unit. Either all the operations within the transaction are completed successfully, or none of them are. If any part of the transaction fails, the entire transaction is rolled back, and the database is left in its original state.

    • Consistency − This ensures that the database properly changes states upon a successfully committed transaction.

    • Isolation − This enables transactions to operate independently and transparent to each other.

    • Durability − This ensures that once a transaction is committed, its effects on the database are permanent and will survive system failures (e.g., power outages, hardware failures).

    Transactional Statements in MySQL

    In MySQL, the transactions begin with either START TRANSACTION, BEGIN or BEGIN WORK statements, and end with either a COMMIT or a ROLLBACK statement. The MySQL commands executed between the beginning and ending statements forms the main body of the transaction.

    To enable or disable the auto-commit option in a transaction, you can use the SET AUTOCOMMIT command. To enable auto-commit, set the command to ”1” or ”ON,” and to disable it, set the command to ”0” or ”OFF.”

    The COMMIT Command

    The COMMIT command is a transaction control command in MySQL. When issued, it finalizes the changes made to a database table up to that point in a transaction, making those changes permanent. As a result, these changes become visible to other active sessions in MySQL.

    Syntax

    Following is the syntax to execute the COMMIT command in MySQL −

    COMMIT;
    

    Example

    Let us create a table names CUSTOMERS using the following query −

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

    We are inserting some records into the above-created table −

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

    The CUSTOMERS table displayed is as follows −

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

    Using the following query, start a transaction and delete the records from the CUSTOMERS table whose AGE is 25, then COMMIT the changes in the database −

    START TRANSACTION;
    DELETE FROM CUSTOMERS WHERE AGE = 25;
    COMMIT;
    

    Verification

    Two rows from the table would be deleted. To verify, display the modified CUSTOMERS table using the following SELECT statement −

    SELECT * FROM CUSTOMERS;
    

    Following is the output obtained −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    3 Kaushik 23 Kota 2000.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 MP 4500.00
    7 Muffy 24 Indore 10000.00

    The AUTOCOMMIT Command

    You can control the behaviour of a transaction by setting session variable called AUTOCOMMIT. If AUTOCOMMIT is set to 1 (the default), then each SQL statement (within a transaction or not) is considered a complete transaction and committed by default when it finishes.

    When AUTOCOMMIT is set to 0, by issuing the SET AUTOCOMMIT = 0 command, the subsequent series of statements acts like a transaction and no activities are committed until an explicit COMMIT statement is issued.

    The ROLLBACK Command

    The ROLLBACK command is a transactional command used to undo changes made in a transaction that have not been saved (committed) to the database. This command can only reverse the effects of transactions made since the last COMMIT or ROLLBACK statement was executed.

    Syntax

    Following is the syntax for ROLLBACK command in MySQL −

    ROLLBACK;
    

    Example

    Using the following query, delete the records from the CUSTOMERS table whose AGE is 25, then ROLLBACK the changes in the database −

    DELETE FROM CUSTOMERS WHERE AGE = 25;
    ROLLBACK;
    

    Verification

    The table will not be affected. To verify, display the modified CUSTOMERS table using the following SELECT statement −

    SELECT * FROM CUSTOMERS;
    

    Following is the table obtained −

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

    You must remember that ROLLBACK only works inside a transaction. If you try to execute it without starting a transaction, the changes would not be revoked.

    The SAVEPOINT Command

    A SAVEPOINT is a logical rollback point within a transaction in MySQL.

    When you execute the ROLLBACK command, it reverts the changes made in the transaction back to the last COMMIT or the beginning of the transaction if there haven”t been any COMMITs. However, by creating save points within the transaction, you can establish specific points to which you can partially roll back the transaction. You can create multiple save points within a transaction to have multiple rollback options between two commits.

    Syntax

    The syntax for creating a SAVEPOINT command among transactions is as shown below −

    SAVEPOINT SAVEPOINT_NAME;
    

    The syntax for rolling back to the SAVEPOINT created is as follows −

    ROLLBACK TO SAVEPOINT_NAME;
    

    Example

    In the following example, you plan to delete three different records from the CUSTOMERS table while creating SAVEPOINTs before each delete. This allows you to ROLLBACK to any SAVEPOINT at any time to restore the appropriate data to its original state −

    SAVEPOINT SP1;
    Query OK, 0 rows affected (0.00 sec)
    
    DELETE FROM CUSTOMERS WHERE ID=1;
    Query OK, 1 row affected (0.01 sec)
    
    SAVEPOINT SP2;
    Query OK, 0 rows affected (0.00 sec)
    
    DELETE FROM CUSTOMERS WHERE ID=2;
    Query OK, 0 rows affected (0.00 sec)
    
    SAVEPOINT SP3;
    Query OK, 0 rows affected (0.00 sec)
    
    DELETE FROM CUSTOMERS WHERE ID=3;
    Query OK, 1 row affected (0.01 sec)
    

    Now that the three deletions have taken place, let us assume that you have changed your mind and decided to ROLLBACK to the SAVEPOINT identified as SP2. Since SP2 was created after the first deletion, this action undoes the last two deletions −

    ROLLBACK TO SP2;
    

    Verification

    If you display the CUSTOMERS table using the following SELECT statement, you will notice that only the first deletion took place since you rolled back to SP2 −

    SELECT * FROM CUSTOMERS;
    

    The result obtained is as shown below −

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

    Transaction-Safe Table Types in MySQL

    In MySQL, not all table types natively support transactions. To use transactions effectively, you should create your tables in a specific way. Although various table types are available, the most commonly used transaction-safe table type is InnoDB.

    To enable InnoDB table support, you may need a specific compilation parameter during the MySQL source compilation. If your MySQL version doesn”t include InnoDB support, you can request your Internet Service Provider (ISP) to provide a MySQL version with InnoDB support, or you can download and install MySQL-Max Binary Distribution for Windows or Linux/UNIX to work with InnoDB tables in a development environment.

    If your MySQL installation supports InnoDB tables, you can create an InnoDB table as shown below −

    CREATE TABLE tcount_tbl (
       tutorial_author varchar(40) NOT NULL,
       tutorial_count  INT
    ) ENGINE = InnoDB;
    

    Following is the output obtained −

    Query OK, 0 rows affected (0.05 sec)
    

    You can also use other table types like GEMINI or BDB, but it depends on your installation, whether it supports these two table types or not.

    Transactions Using a Client Program

    We can also perform transactions using the client program.

    Syntax

    To perform the transactions through a PHP program, we need to execute three statements: “START TRANSACTION”, “COMMIT”, and “ROLLBACK” using the mysqli function query() as follows −

    $sql = "START TRANSACTION";
    $mysqli->query($sql);
    ...
    $sql = "COMMIT";
    $mysqli->query($sql);
    ...
    $sql = "ROLLBACK";
    $mysqli->query($sql);
    ...
    

    To perform the transactions through a JavaScript program, we need to execute three statements “START TRANSACTION”, “COMMIT”, and “ROLLBACK” using the query() function of mysql2 library as follows −

    sql = "START TRANSACTION";
    con.query(sql);
    ...
    sql = "COMMIT";
    con.query(sql);
    ...
    sql = "ROLLBACK";
    con.query(sql);
    ...
    

    To perform the transactions through a Java program, we need to execute three statements “START TRANSACTION”, “COMMIT”, and “ROLLBACK” using the JDBC function execute() as follows −

    String sql = "START TRANSACTION";
    statement.execute(sql);
    ...
    String sql = "COMMIT";
    statement.execute(sql);
    ...
    String sql = "ROLLBACK";
    statement.execute(sql);
    ...
    

    To perform the transactions through a Python program, we need to execute three statements “START TRANSACTION”, “COMMIT”, and “ROLLBACK” using the execute() function of the MySQL Connector/Python as follows: −

    connection.start_transaction()
    ...
    connection.commit()
    ...
    connection.rollback()
    ...
    

    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.
    ''); //start transaction $sql = "START TRANSACTION"; if($mysqli->query($sql)){ printf("Transaction started....!n"); } //print table record $sql = "SELECT * FROM CUSTOMERS"; if($result = $mysqli->query($sql)){ printf("Table records after transaction...!n"); while($row = mysqli_fetch_array($result)){ printf("ID %d, NAME %s, AGE %d, ADDRESS %s, SALARY %f", $row[''ID''], $row[''NAME''], $row[''AGE''], $row[''ADDRESS''], $row[''SALARY'']); printf("n"); } } //let''s delete some records $sql = "DELETE FROM CUSTOMERS WHERE AGE = 25"; if($mysqli->query($sql)){ printf("Records with age = 25 are deleted successfully....!n"); } //lets delete some more records.. $sql = "DELETE FROM CUSTOMERS WHERE SALARY = 2000"; if($mysqli->query($sql)){ printf("Records with salary = 2000 are deleted successfully....!n"); } printf("Table data after second delete (before rollback)...!n"); $sql = "SELECT * FROM CUSTOMERS"; if($result = $mysqli->query($sql)){ while($row = mysqli_fetch_array($result)){ printf("ID %d, NAME %s, AGE %d, ADDRESS %s, SALARY %f", $row[''ID''], $row[''NAME''], $row[''AGE''], $row[''ADDRESS''], $row[''SALARY'']); printf("n"); } } $sql = "ROLLBACK"; if($mysqli->query($sql)){ printf("Transaction rollbacked successfully..!n"); } printf("Table data after rollback: n"); $sql = "SELECT * FROM CUSTOMERS"; if($result = $mysqli->query($sql)){ while($row = mysqli_fetch_array($result)){ printf("ID %d, NAME %s, AGE %d, ADDRESS %s, SALARY %f", $row[''ID''], $row[''NAME''], $row[''AGE''], $row[''ADDRESS''], $row[''SALARY'']); printf("n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as shown below −

    Transaction started....!
    Table records after transaction...!
    ID 1, NAME Ramesh, AGE 32, ADDRESS Ahmedabad, SALARY 2000.000000
    ID 2, NAME Khilan, AGE 25, ADDRESS Delhi, SALARY 1500.000000
    ID 3, NAME kaushik, AGE 23, ADDRESS Kota, SALARY 2000.000000
    ID 4, NAME Chaitali, AGE 25, ADDRESS Mumbai, SALARY 6500.000000
    ID 5, NAME Hardik, AGE 27, ADDRESS Bhopal, SALARY 8500.000000
    ID 6, NAME Komal, AGE 22, ADDRESS MP, SALARY 4500.000000
    ID 7, NAME Muffy, AGE 24, ADDRESS Indore, SALARY 10000.000000
    Records with age = 25 are deleted successfully....!
    Records with salary = 2000 are deleted successfully....!
    Table data after second delete (before rollback)...!
    ID 5, NAME Hardik, AGE 27, ADDRESS Bhopal, SALARY 8500.000000
    ID 6, NAME Komal, AGE 22, ADDRESS MP, SALARY 4500.000000
    ID 7, NAME Muffy, AGE 24, ADDRESS Indore, SALARY 10000.000000
    Transaction rollbacked successfully..!
    Table data after rollback:
    ID 1, NAME Ramesh, AGE 32, ADDRESS Ahmedabad, SALARY 2000.000000
    ID 2, NAME Khilan, AGE 25, ADDRESS Delhi, SALARY 1500.000000
    ID 3, NAME kaushik, AGE 23, ADDRESS Kota, SALARY 2000.000000
    ID 4, NAME Chaitali, AGE 25, ADDRESS Mumbai, SALARY 6500.000000
    ID 5, NAME Hardik, AGE 27, ADDRESS Bhopal, SALARY 8500.000000
    ID 6, NAME Komal, AGE 22, ADDRESS MP, SALARY 4500.000000
    ID 7, NAME Muffy, AGE 24, ADDRESS Indore, SALARY 10000.000000
    
    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 = "START TRANSACTION";
    con.query(sql, function(err, result){
        if (err) throw err;
        console.log("Transaction started....!");
    });
     sql = "SELECT * FROM CUSTOMERS";
     con.query(sql, function(err, result){
        console.log("Table records after transaction...!");
        if (err) throw err;
        console.log(result);
        });
    //delete record
    sql = "DELETE FROM CUSTOMERS WHERE AGE  = 25";
    con.query(sql, function(err, result){
        if (err) throw err;
        console.log("Records with age = 25 are deleted successfully....!");
    });
    //now lets delete more records
    sql = "DELETE FROM CUSTOMERS WHERE SALARY  = 2000";
    con.query(sql, function(err, result){
        if (err) throw err;
        console.log("Records with salary = 2000 are deleted successfully....!");
    });
    //print table records before rollback;
    sql = "SELECT * FROM CUSTOMERS";
    con.query(sql, function(err, result){
       console.log("Table Data After Second Delete (Before Rollback)");
       if (err) throw err;
       console.log(result);
       });
    //rollback the transaction
    sql = "ROLLBACK";
    con.query(sql, function(err, result){
        if (err) throw err;
        console.log("Transaction rollbacked successfully..!");
    });
    //print table data after rollback;
    sql = "SELECT * FROM CUSTOMERS";
     con.query(sql, function(err, result){
        console.log("Table records after rollback...!");
        if (err) throw err;
        console.log(result);
        });
    });
    

    Output

    The output obtained is as shown below −

    Transaction started....!
    Table records after transaction...!
    [
      {
        ID: 1,
        NAME: ''Ramesh'',
        AGE: 32,
        ADDRESS: ''Ahmedabad'',
        SALARY: ''2000.00''
      },
      {
        ID: 2,
        NAME: ''Khilan'',
        AGE: 25,
        ADDRESS: ''Delhi'',
        SALARY: ''1500.00''
      },
      {
        ID: 3,
        NAME: ''kaushik'',
        AGE: 23,
        ADDRESS: ''Kota'',
        SALARY: ''2000.00''
      },
      {
        ID: 4,
        NAME: ''Chaitali'',
        AGE: 25,
        ADDRESS: ''Mumbai'',
        SALARY: ''6500.00''
      },
      {
        ID: 5,
        NAME: ''Hardik'',
        AGE: 27,
        ADDRESS: ''Bhopal'',
        SALARY: ''8500.00''
      },
      { ID: 6, NAME: ''Komal'', AGE: 22, ADDRESS: ''MP'', SALARY: ''4500.00'' },
      {
        ID: 7,
        NAME: ''Muffy'',
        AGE: 24,
        ADDRESS: ''Indore'',
        SALARY: ''10000.00''
      }
    ]
    Records with age = 25 are deleted successfully....!
    Records with salary = 2000 are deleted successfully....!
    Table Data After Second Delete (Before Rollback)
    [
      {
        ID: 5,
        NAME: ''Hardik'',
        AGE: 27,
        ADDRESS: ''Bhopal'',
        SALARY: ''8500.00''
      },
      { ID: 6, NAME: ''Komal'', AGE: 22, ADDRESS: ''MP'', SALARY: ''4500.00'' },
      {
        ID: 7,
        NAME: ''Muffy'',
        AGE: 24,
        ADDRESS: ''Indore'',
        SALARY: ''10000.00''
      }
    ]
    Transaction rollbacked successfully..!
    Table records after rollback...!
    [
      {
        ID: 1,
        NAME: ''Ramesh'',
        AGE: 32,
        ADDRESS: ''Ahmedabad'',
        SALARY: ''2000.00''
      },
      {
        ID: 2,
        NAME: ''Khilan'',
        AGE: 25,
        ADDRESS: ''Delhi'',
        SALARY: ''1500.00''
      },
      {
        ID: 3,
        NAME: ''kaushik'',
        AGE: 23,
        ADDRESS: ''Kota'',
        SALARY: ''2000.00''
      },
      {
        ID: 4,
        NAME: ''Chaitali'',
        AGE: 25,
        ADDRESS: ''Mumbai'',
        SALARY: ''6500.00''
      },
      {
        ID: 5,
        NAME: ''Hardik'',
        AGE: 27,
        ADDRESS: ''Bhopal'',
        SALARY: ''8500.00''
      },
      { ID: 6, NAME: ''Komal'', AGE: 22, ADDRESS: ''MP'', SALARY: ''4500.00'' },
      {
        ID: 7,
        NAME: ''Muffy'',
        AGE: 24,
        ADDRESS: ''Indore'',
        SALARY: ''10000.00''
      }
    ]
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class Transaction {
       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...!");
                //start transaction
                String sql = "START TRANSACTION";
                st.execute(sql);
                System.out.println("Transaction started....!");
                //print customers record after starting transaction
                String sql1 = "SELECT * FROM CUSTOMERS";
                rs = st.executeQuery(sql1);
                System.out.println("Table records after starting transaction: ");
                while(rs.next()) {
                   String id = rs.getString("id");
                   String name = rs.getString("name");
                   String age = rs.getString("age");
                   String address = rs.getString("address");
                   String salary = rs.getString("salary");
                   System.out.println("Id: " + id + ", Name: " + name +   ", Age: " + age +   ", Address: " + address +  ", Salary: " + salary);
                }
                //lets delete some records
                String sql2 = "DELETE FROM CUSTOMERS WHERE AGE = 25";
                st.execute(sql2);
                System.out.println("Customer with age 25 deleted successfully...!");
                String sql4 = "DELETE FROM CUSTOMERS WHERE SALARY  = 2000";
                st.execute(sql4);
                System.out.println("Customer with age 2000 deleted successfully...!");
                String sql5 = "SELECT * FROM CUSTOMERS";
                rs = st.executeQuery(sql5);
                System.out.println("Table records before rollback: ");
                while(rs.next()) {
                   String id = rs.getString("id");
                   String name = rs.getString("name");
                   String age = rs.getString("age");
                   String address = rs.getString("address");
                   String salary = rs.getString("salary");
                   System.out.println("Id: " + id + ", Name: " + name +   ", Age: " + age +   ", Address: " + address +  ", Salary: " + salary);
                }
                //lets roll-back the transaction
                String r = "ROLLBACK";
                st.execute(r);
                System.out.println("Transaction rollbacked successfully...!");
                String sql6 = "SELECT * FROM CUSTOMERS";
                rs = st.executeQuery(sql6);
                System.out.println("Table records after rollback: ");
                while(rs.next()) {
                   String id = rs.getString("id");
                   String name = rs.getString("name");
                   String age = rs.getString("age");
                   String address = rs.getString("address");
                   String salary = rs.getString("salary");
                   System.out.println("Id: " + id + ", Name: " + name +   ", Age: " + age +   ", Address: " + address +  ", Salary: " + salary);
                }
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Transaction started....!
    Table records after starting transaction:
    Id: 1, Name: Ramesh, Age: 32, Address: Ahmedabad, Salary: 2000.00
    Id: 2, Name: Khilan, Age: 25, Address: Delhi, Salary: 1500.00
    Id: 3, Name: kaushik, Age: 23, Address: Kota, Salary: 2000.00
    Id: 4, Name: Chaitali, Age: 25, Address: Mumbai, Salary: 6500.00
    Id: 5, Name: Hardik, Age: 27, Address: Bhopal, Salary: 8500.00
    Id: 6, Name: Komal, Age: 22, Address: MP, Salary: 4500.00
    Id: 7, Name: Muffy, Age: 24, Address: Indore, Salary: 10000.00
    Customer with age 25 deleted successfully...!
    Customer with age 2000 deleted successfully...!
    Table records before rollback:
    Id: 5, Name: Hardik, Age: 27, Address: Bhopal, Salary: 8500.00
    Id: 6, Name: Komal, Age: 22, Address: MP, Salary: 4500.00
    Id: 7, Name: Muffy, Age: 24, Address: Indore, Salary: 10000.00
    Transaction rollbacked successfully...!
    Table records after rollback:
    Id: 1, Name: Ramesh, Age: 32, Address: Ahmedabad, Salary: 2000.00
    Id: 2, Name: Khilan, Age: 25, Address: Delhi, Salary: 1500.00
    Id: 3, Name: kaushik, Age: 23, Address: Kota, Salary: 2000.00
    Id: 4, Name: Chaitali, Age: 25, Address: Mumbai, Salary: 6500.00
    Id: 5, Name: Hardik, Age: 27, Address: Bhopal, Salary: 8500.00
    Id: 6, Name: Komal, Age: 22, Address: MP, Salary: 4500.00
    Id: 7, Name: Muffy, Age: 24, Address: Indore, Salary: 10000.00
    
    import mysql.connector
    # Establishing the connection
    connection = mysql.connector.connect(
        host=''localhost'',
        user=''root'',
        password=''password'',
        database=''tut''
    )
    # Creating a cursor object
    cursorObj = connection.cursor()
    # Start the transaction
    connection.start_transaction()
    # Displaying the table before deleting
    select_query = "SELECT * FROM customers"
    cursorObj.execute(select_query)
    print("Table Data after starting Transaction:")
    for row in cursorObj.fetchall():
        print(row)
    # Execute the DELETE statement
    delete_query = "DELETE FROM customers WHERE AGE = 25"
    cursorObj.execute(delete_query)
    print("Rows with AGE = 25 are deleted.")
    # Commit the transaction
    connection.commit()
    print("Transaction committed successfully.")
    # Displaying the table after deleting (changes are permanent)
    cursorObj.execute(select_query)
    print("Table Data After Transaction:")
    for row in cursorObj.fetchall():
        print(row)
    # Now, let us delete more records
    delete_query1 = "DELETE FROM customers WHERE SALARY = 2000"
    cursorObj.execute(delete_query1)
    print("Rows with SALARY = 2000 are deleted.")
    # Display the table after the second delete operation (changes are not committed yet)
    cursorObj.execute(select_query)
    print("Table Data After Second Delete (Before Rollback):")
    for row in cursorObj.fetchall():
        print(row)
    # Rollback the transaction
    connection.rollback()
    print("Transaction rollbacked successfully.")
    # Displaying the table after rollback (changes are reverted)
    cursorObj.execute(select_query)
    print("Table Data After Rollback:")
    for row in cursorObj.fetchall():
        print(row)
    # Closing the cursor and connection
    cursorObj.close()
    connection.close()
    

    Output

    The output obtained is as shown below −

    Table Data after starting Transaction:
    (1, ''Ramesh'', 32, ''Ahmedabad'', Decimal(''2000.00''))
    (2, ''Khilan'', 25, ''Delhi'', Decimal(''1500.00''))
    (3, ''kaushik'', 23, ''Kota'', Decimal(''2000.00''))
    (4, ''Chaitali'', 25, ''Mumbai'', Decimal(''6500.00''))
    (5, ''Hardik'', 27, ''Bhopal'', Decimal(''8500.00''))
    (6, ''Komal'', 22, ''MP'', Decimal(''4500.00''))
    (7, ''Muffy'', 24, ''Indore'', Decimal(''10000.00''))
    Rows with AGE = 25 are deleted.
    Transaction committed successfully.
    Table Data After Transaction:
    (1, ''Ramesh'', 32, ''Ahmedabad'', Decimal(''2000.00''))
    (3, ''kaushik'', 23, ''Kota'', Decimal(''2000.00''))
    (5, ''Hardik'', 27, ''Bhopal'', Decimal(''8500.00''))
    (6, ''Komal'', 22, ''MP'', Decimal(''4500.00''))
    (7, ''Muffy'', 24, ''Indore'', Decimal(''10000.00''))
    Rows with SALARY = 2000 are deleted.
    Table Data After Second Delete (Before Rollback):
    (5, ''Hardik'', 27, ''Bhopal'', Decimal(''8500.00''))
    (6, ''Komal'', 22, ''MP'', Decimal(''4500.00''))
    (7, ''Muffy'', 24, ''Indore'', Decimal(''10000.00''))
    Transaction rollbacked successfully.
    Table Data After Rollback:
    (1, ''Ramesh'', 32, ''Ahmedabad'', Decimal(''2000.00''))
    (3, ''kaushik'', 23, ''Kota'', Decimal(''2000.00''))
    (5, ''Hardik'', 27, ''Bhopal'', Decimal(''8500.00''))
    (6, ''Komal'', 22, ''MP'', Decimal(''4500.00''))
    (7, ''Muffy'', 24, ''Indore'', Decimal(''10000.00''))
    

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

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

    MySQL – Handling Duplicates

    Table of content


    Tables or result sets in a database usually contain duplicate records. While duplicates are generally allowed, there are situations where it is necessary to prevent them. In such cases, it becomes essential to identify and remove duplicate records from a database table.

    Importance of Handling MySQL Duplicates

    There are various reasons why handling duplicates in a database becomes necessary. One of the main reasons is that the existence of duplicates in an organizational database will lead to logical errors. In addition to it, we need to handle redundant data to prevent the following consequences −

    • Duplicate data occupies storage space, reducing the efficiency of database usage and increasing storage costs.
    • Dealing with duplicate records consumes additional resources, driving up the overall cost of maintaining the database.
    • Duplicates in a database can lead to logical errors in data, affecting the integrity and reliability of the information stored.

    Preventing Duplicate Entries

    You can use a PRIMARY KEY or a UNIQUE Index on a table with the appropriate fields to prevent duplicate record entries into a table.

    Example

    The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name.

    CREATE TABLE CUSTOMERS (
       first_name CHAR(20),
       last_name CHAR(20),
       sex CHAR(10)
    );
    

    To prevent multiple records with the same first and last name values from being created in this table, add a PRIMARY KEY to its definition. When you do this, it is also necessary to declare the indexed columns to be NOT NULL, because a PRIMARY KEY does not allow NULL values −

    CREATE TABLE CUSTOMERS (
       first_name CHAR(20) NOT NULL,
       last_name CHAR(20) NOT NULL,
       sex CHAR(10),
       PRIMARY KEY (last_name, first_name)
    );
    

    Using INSERT IGNORE Query −

    The existence of a unique index in a table normally causes an error when attempting to insert a record that duplicates an existing record in the indexed column(s).

    To handle this situation without generating an error, you can use the “INSERT IGNORE” command. When a record is not a duplicate, MySQL inserts it as usual. However, if the record is duplicate, the “IGNORE” keyword instructs MySQL to discard it without producing an error.

    The provided example does not result in an error, and it also ensures that duplicate records are not inserted −

    INSERT IGNORE INTO CUSTOMERS (LAST_NAME, FIRST_NAME)
    VALUES (''Jay'', ''Thomas''), (''Jay'', ''Thomas'');
    

    We get the following output −

    Query OK, 1 row affected, 1 warning (0.01 sec)
    Records: 2  Duplicates: 1  Warnings: 1
    

    Using REPLACE Query −

    Instead of using the INSERT command, consider using the REPLACE command. When dealing with a new record, it is inserted just as with INSERT. However, if it is a duplicate, the new record replaces the old one.

    REPLACE INTO CUSTOMERS (LAST_NAME, FIRST_NAME)
    VALUES ( ''Ajay'', ''Kumar''), ( ''Ajay'', ''Kumar'');
    

    Following is the output of the above code −

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

    Your choice between the INSERT IGNORE and REPLACE commands should depend on the specific duplicate-handling behaviour you wish to achieve. The INSERT IGNORE command retains the first set of duplicated records and discards the remaining. On the other hand, the REPLACE command keeps the last set of duplicates and removes any earlier instances.

    Using UNIQUE Constraint −

    Another way to enforce uniqueness is to add a UNIQUE index rather than a PRIMARY KEY to a table −

    CREATE TABLE CUSTOMERS (
       first_name CHAR(20) NOT NULL,
       last_name CHAR(20) NOT NULL,
       sex CHAR(10),
       UNIQUE (last_name, first_name)
    );
    

    Counting and Identifying Duplicates

    You can use the COUNT function and GROUP BY clause to count and identify duplicate records based on specific columns.

    Example

    Following is the query to count duplicate records with first_name and last_name in a table −

    SELECT COUNT(*) as repetitions, last_name, first_name
    FROM CUSTOMERS
    GROUP BY last_name, first_name
    HAVING repetitions > 1;
    

    This query will return a list of all the duplicate records in the CUSTOMERS table. In general, to identify sets of values that are duplicated, follow the steps given below.

    • Determine which columns may contain duplicated values.

    • Include those columns in the column selection list, along with COUNT(*).

    • List the columns in the GROUP BY clause as well.

    • Apply a HAVING clause to filter unique values by requiring the group counts to be greater than one.

    Eliminating Duplicates from a Query Result

    You can use the DISTINCT command along with the SELECT statement to find out unique records available in a table.

    SELECT DISTINCT last_name, first_name
    FROM CUSTOMERS
    ORDER BY last_name;
    

    An alternative to the DISTINCT command is to add a GROUP BY clause that specifies the columns you are selecting. This approach eliminates duplicates and retrieves only the unique combinations of values from the specified columns.

    SELECT last_name, first_name
    FROM CUSTOMERS
    GROUP BY (last_name, first_name);
    

    Removing Duplicates Using Table Replacement

    If you have duplicate records in a table and you want to remove all the duplicate records from that table, then follow the procedure given below −

    CREATE TABLE tmp AS
    SELECT DISTINCT last_name, first_name, sex
    FROM CUSTOMERS;
    
    DROP TABLE CUSTOMERS;
    ALTER TABLE tmp RENAME TO CUSTOMERS;
    

    Handling Duplicates Using a Client Program

    We can also handle duplicate using the client program.

    Syntax

    To handle duplicates value through a PHP program, we need to execute the “INSERT IGNORE” statement using the mysqli function query() as follows −

    $sql = "INSERT IGNORE INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')";
    $mysqli->query($sql);
    

    To handle duplicates value through a JavaScript program, we need to execute the “INSERT IGNORE” statement using the query() function of mysql2 library as follows −

    sql = "INSERT IGNORE INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')";
    con.query(sql);
    

    To handle duplicates value through a Java program, we need to execute the “INSERT IGNORE” statement using the JDBC function execute() as follows −

    String sql = "INSERT IGNORE INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')";
    statement.execute(sql);
    

    To handle duplicates value through a Python program, we need to execute the “INSERT IGNORE” statement using the execute() function of the MySQL Connector/Python as follows −

    sql = "INSERT IGNORE INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')"
    cursorObj.execute(sql)
    

    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 TABLE person_tbl (first_name CHAR(20) NOT NULL, last_name CHAR(20) NOT NULL, sex CHAR(10), PRIMARY KEY (last_name, first_name))"; if($mysqli->query($sql)){ printf("Table created successfully...!n"); } //let''s insert some records $sql = "INSERT INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')"; if($mysqli->query($sql)){ printf("First record inserted successfully...!n"); } $sql = "INSERT INTO person_tbl (last_name, first_name) VALUES( ''John'', ''Smith'')"; if($mysqli->query($sql)){ printf("Second record inserted successfully...!n"); } //now lets insert duplicate record with IGNORE keyword $sql = "INSERT IGNORE INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')"; if($mysqli->query($sql)){ printf("Duplicate record inserted successfully using IGNORE keyword...!n"); } $sql = "SELECT * from person_tbl"; if($result = $mysqli->query($sql)){ printf("Table records: n"); while($row = mysqli_fetch_array($result)){ printf("First Name: %s, Last name: %s, Sex: %s", $row[''first_name''], $row[''last_name''], $row[''sex'']); printf("n"); } } //lets insert a duplicate record $sql = "INSERT INTO person_tbl (last_name, first_name) VALUES( ''John'', ''Smith'')"; if(!$mysqli->query($sql)){ printf("You can''t insert any duplicate records...!n"); } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();

    Output

    The output obtained is as shown below −

    Table created successfully...!
    First record inserted successfully...!
    Second record inserted successfully...!
    Duplicate record inserted successfully using IGNORE keyword...!
    Table records:
    First Name: Thomas, Last name: Jay, Sex:
    First Name: Smith, Last name: John, Sex:
    PHP Fatal error:  Uncaught mysqli_sql_exception: Duplicate entry ''John-Smith'' for key ''person_tbl.PRIMARY'' in D:testhandlingduplicates.php:48
    
    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 table
     sql = "CREATE TABLE person_tbl (first_name CHAR(20) NOT NULL, last_name CHAR(20) NOT NULL, sex CHAR(10), PRIMARY KEY (last_name, first_name))";
     con.query(sql, function(err, result){
        if (err) throw err;
        console.log("Table created successfully....!");
        });
    //now let''s insert some records
    sql = "INSERT INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')";
    con.query(sql, function(err, result){
        if (err) throw err;
        console.log("First record inserted successfully...!");
        });
    sql = "INSERT INTO person_tbl (last_name, first_name) VALUES( ''John'', ''Smith'')";
    con.query(sql, function(err, result){
        if (err) throw err;
        console.log("Second record inserted successfully...!");
        });
    //now lets insert duplicate record with IGNORE keyword
    sql = "INSERT IGNORE INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')";
        con.query(sql, function(err, result){
            console.log("Insert duplicate record with IGNORE keyword")
        if (err) throw err;
        console.log("Duplicate record inserted successfully with the help of IGNORE keyword");
        });
    //lets insert a duplicate record
    sql = "INSERT INTO person_tbl (last_name, first_name) VALUES( ''John'', ''Smith'')";
        con.query(sql, function(err, result){
            console.log("Insert duplicate record");
        if (err) throw err;
        console.log("You can''t insert the duplicate record because columns are primary key");
        });
    sql = "SELECT * FROM person_tbl";
    con.query(sql, function(err, result){
        console.log("Table records(with ID auto_increment sequence).");
        if (err) throw err;
        console.log(result);
        });
    });
    

    Output

    The output obtained is as shown below −

    Table created successfully....!
    First record inserted successfully...!
    Second record inserted successfully...!
    Insert duplicate record with IGNORE keyword
    Duplicate record inserted successfully with the help of IGNORE keyword
    Insert duplicate record
    Insert duplicate record
    D:test1duplicate.js:43
        if (err) throw err;              ^
    
    Error: Duplicate entry ''John-Smith'' for key ''person_tbl.PRIMARY''
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class HandleDuplicates {
       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 table
                String sql = "CREATE TABLE person_tbl ( first_name CHAR(20) NOT NULL, last_name CHAR(20) NOT NULL, sex CHAR(10), PRIMARY KEY (last_name, first_name))";
                st.execute(sql);
                System.out.println("Table created successfully....!");
                //let''s insert some records
                String sql1 = "INSERT IGNORE INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')";
                st.execute(sql1);
                System.out.println("Record inserted successfully...!");
                String sql2 = "INSERT IGNORE INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')";
                st.execute(sql2);
                System.out.println("Duplicate record inserted successfully...!");
                //lets print the table records
                String sql3 = "SELECT * FROM PERSON_TBL";
                rs = st.executeQuery(sql3);
                System.out.println("Table records: ");
                while(rs.next()) {
                   String fname = rs.getString("first_name");
                   String lname = rs.getString("last_name");
                   System.out.println("First name: " + fname + ", Last name: " + lname);
                }
          }catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    

    Output

    The output obtained is as shown below −

    Table created successfully....!
    Record inserted successfully...!
    Duplicate record inserted successfully...!
    Table records:
    First name: Thomas, Last name: Jay
    
    import mysql.connector
    # Connecting to MySQL
    con = mysql.connector.connect(
        host="localhost",
        user="root",
        password="password",
        database="tut"
    )
    # Creating a cursor object
    cursorObj = con.cursor()
    # Creating the table
    create_table_query = """
    CREATE TABLE person_tbl (
        first_name CHAR(20) NOT NULL,
        last_name CHAR(20) NOT NULL,
        sex CHAR(10),
        PRIMARY KEY (last_name, first_name)
    )
    """
    cursorObj.execute(create_table_query)
    print("Table ''person_tbl'' is created successfully!")
    # Inserting some records
    first_record = "INSERT INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')"
    print("First record inserted successfully!")
    cursorObj.execute(first_record)
    
    second_record = "INSERT INTO person_tbl (last_name, first_name) VALUES( ''John'', ''Smith'')"
    print("Second record inserted successfully!")
    cursorObj.execute(second_record)
    # Insert duplicate record with IGNORE keyword
    sql = "INSERT IGNORE INTO person_tbl (last_name, first_name) VALUES( ''Jay'', ''Thomas'')"
    print("Duplicate record inserted successfully with the help of IGNORE keyword")
    cursorObj.execute(sql)
    # Insert a duplicate record (this will throw an error)
    try:
        cursorObj.execute("INSERT INTO person_tbl (last_name, first_name) VALUES( ''John'', ''Smith'')")
        print("Insert duplicate record")
    except mysql.connector.Error as err:
        print("Insert duplicate record error:", err)
    con.commit()
    # Retrieving records
    cursorObj.execute("SELECT * FROM person_tbl")
    records = cursorObj.fetchall()
    # Printing the records
    print("Table records.")
    for record in records:
        print(record)
    # Closing the connection
    cursorObj.close()
    con.close()
    

    Output

    The output obtained is as shown below −

    First record inserted successfully!
    Second record inserted successfully!
    Duplicate record inserted successfully with the help of IGNORE keyword
    Insert duplicate record error: 1062 (23000): Duplicate entry ''John-Smith'' for key ''person_tbl.PRIMARY''
    Table records.
    (''Thomas'', ''Jay'', None)
    (''Smith'', ''John'', 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 – SQL Injection nhận dự án làm có lương

    MySQL – SQL Injection

    Table of content


    The SQL Injection in MySQL is a harmful approach where an attacker inserts or “injects” harmful SQL code into a database query. This can be done through user inputs such as forms, URL parameters, or cookies. The attacker takes advantage of weaknesses in the software to steal information from the database.

    How SQL Injection Works

    Imagine you have a web application with a login page. When a user enters their username and password, the application checks these credentials against a MySQL database. The SQL query might look like as given below −

    SELECT * FROM users
    WHERE username = ''user'' AND password = ''password
    

    In a secure application, the ”user” and ”password” would be the actual values entered by the user. However, in an SQL Injection attack, an attacker can manipulate the input fields to inject malicious SQL code.

    For example, they might enter the following as the username −

    '' OR ''1'' = ''1
    

    Now, the SQL query becomes −

    SELECT * FROM users
    WHERE username = '''' OR ''1'' = ''1'' AND password = ''password
    

    Because ”1” always equals ”1”, this condition is always true, and the attacker gains unauthorized access to the application. In this way, they trick the application into granting access without a valid password.

    Preventing SQL Injection

    To prevent SQL injection, it is important to handle escape characters properly when using scripting languages like PERL and PHP. When working with PHP and MySQL, you can use the mysql_real_escape_string() function to escape input characters that have special meaning in MySQL. Following is an example of how to do this −

    if (get_magic_quotes_gpc()) {
       $name = stripslashes($name);
    }
    // escape input characters
    $name = mysql_real_escape_string($name);
    
    // Perform the MySQL query with the escaped ''name''
    mysqli_query("SELECT * FROM CUSTOMERS WHERE name=''{$name}''");
    

    The LIKE Quandary

    Now, let us address the issue with the LIKE clause. When dealing with user-provided data that may include ”%” and ”_” characters, it is important to create a custom escaping mechanism to treat them as literals. You can achieve this by combining “mysql_real_escape_string()” function with “addcslashes()” function, which allows you to specify a character range to escape. Following is an example of how you can do it −

    // Escape and convert ''%'' and ''_'' in the user-provided string
    $sub = addcslashes(mysql_real_escape_string("%str"), "%_");
    
    // $sub will be equal to %str_
    
    // Use the escaped string in the LIKE query
    mysqli_query("SELECT * FROM messages
       WHERE subject LIKE ''{$sub}%''");
    

    In this way, you ensure that the ”%” and ”_” characters in the user input are treated as literal characters in the SQL query, preventing SQL injection and maintaining the integrity of your database operations.


    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