Your cart is currently empty!
Author: alien
-
Khóa học miễn phí MySQL – BOOLEAN nhận dự án làm có lương
MySQL – Boolean Datatype
Table of content
A Boolean data type is used to represent truth values of logic and Boolean algebra. It has two possible values: either true or false.
For example, if a customer wants to see all the bikes that are black in colour, we can filter them using BOOLEAN operator, as given in the following table −
Here, ”IS_BLACK” is the BOOLEAN column that returns either true or false values based on the colours of the bikes.
Boolean in MySQL
In MySQL, there is no built-in Boolean or Bool data type. Instead MySQL provides us with the TINYINT datatype to store the Boolean values.
MySQL considers the value 0 as FALSE and 1 as TRUE. We can also store NULL values using the TINYINT datatype.
The Boolean values (such as TRUE and FALSE) are not case-sensitive.
Syntax
Following is the syntax of the BOOLEAN operator in MySQL −
CREATE TABLE table_name ( Column_name BOOLEAN );
Example
In MySQL, 0 is defined as FALSE and any non-zero values are defined as TRUE −
SELECT TRUE, FALSE;
Output
As we can see in the output below, TRUE and FALSE are represented as 1 and 0 −
TRUE FALSE 1 0 Example
In MySQL, the Boolean values (TRUE and FALSE) are case-insensitive −
SELECT true, false, TRUE, FALSE, True, False;
Output
The output produced is as given below −
true false TRUE FALSE True False 1 0 1 0 1 0 Example
Now, let”s create a table with the name CUSTOMERS using the following query. Here, the AVAILABILITY column specifies whether the customer is available or not. If the bit value is 0 (FALSE), the customer is not available. If it is 1(TRUE), the customer is available −
CREATE TABLE CUSTOMERS ( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(40), AVAILABILITY BOOLEAN );
Following is the output produced −
Query OK, 0 rows affected (0.02 sec)
To get the information about the CUSTOMERS table, use the following query −
DESCRIBE CUSTOMERS;
If we look at the AVAILABILITY column, which has been set to BOOLEAN while creating the table, it now shows type of TINYINT −
Field Type Null Key Default Extra ID int NO PRI NULL auto_increment NAME varchar(40) YES NULL AVAILABILITY tinyint(1) YES NULL Now, let us insert some records into the CUSTOMERS table using the following INSERT query −
INSERT INTO CUSTOMERS VALUES (1, ''Ramesh'', FALSE), (2, ''Khilan'', TRUE), (4, ''Kaushik'', NULL);
Using the below query, we can display all the values in the table −
SELECT * FROM CUSTOMERS;
We can see the values in the AVAILABILITY column are set to 0 and 1 respectively. −
ID NAME AVAILABILITY 1 Ramesh 0 2 Khilan 1 4 Kaushik NULL Replacing BOOLEAN 0,1 with TRUE and FALSE
As we can see in the above CUSTOMERS table, the BOOLEAN data type shows 0 and 1 values instead of TRUE and FALSE. In MySQL, we can convert BOOLEAN data type to TRUE and FALSE values using the CASE statement.
The MySQL CASE statement is a conditional statement that goes through conditions and return a values when the first condition is met. Therefore, once a condition is true, it will stop reading the next piece of code and return the result.
If no conditions are true, it will return the value in the ELSE clause. If no ELSE clause is present and no conditions are true, it returns NULL.
Syntax
Following is the syntax of CASE statement in MySQL −
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... WHEN conditionN THEN resultN ELSE result END;
Example
To get a better understanding, let us consider the BIKES table created using the query below −
CREATE TABLE BIKES ( S_NO INT AUTO_INCREMENT PRIMARY KEY, COMPANY VARCHAR(40) NOT NULL, PRICE INT NOT NULL, COLOUR VARCHAR(40) NOT NULL, IS_BLACK BOOLEAN );
Example
Output of the above code is as follows −
Query OK, 0 rows affected (0.03 sec)
Now, let us insert values into the BIKES table using the INSERT statement as shown below −
INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK) VALUES (''Royal Enfield'', 300000, ''Black'', 1); INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK) VALUES (''BMW'', 900000, ''Blue'', 0); INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK) VALUES (''Jawa'', 150000, ''Black'', 1); INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK) VALUES (''Triumph'', 1200000, ''Red'', 0);
The BIKES table obtained is as follows −
S_NO COMPANY PRICE COLOUR IS_BLACK 1 Royal Enfield 300000 Black 1 2 BMW 900000 Blue 0 3 Jawa 150000 Black 1 4 Triumph 1200000 Red 0 Now, let us display all the records from the BIKES table, where the colour BLACK is represented by either TRUE or FALSE −
SELECT *, CASE IS_BLACK WHEN 1 THEN ''TRUE'' WHEN 0 THEN ''FALSE'' END AS IS_BOOLEAN FROM BIKES;
Output
The output is displayed as follows −
S_NO COMPANY PRICE COLOUR IS_BLACK IS_BOOLEAN 1 Royal Enfield 300000 Black 1 TRUE 2 BMW 900000 Blue 0 FALSE 3 Jawa 150000 Black 1 TRUE 4 Triumph 1200000 Red 0 FALSE Example
In the following query, we are filtering the records from the BIKES table where colour black is TRUE −
SELECT * FROM BIKES WHERE IS_BLACK IS TRUE;
Output
As we can see the output below, Royal Enfield and Jawa are black in color (true) −
S_NO COMPANY PRICE COLOUR IS_BLACK 1 Royal Enfield 300000 Black 1 3 Jawa 150000 Black 1 Example
In here, we are filtering the records from the BIKES table where color black is FALSE −
SELECT * FROM BIKES WHERE IS_BLACK IS FALSE;
Output
The output says that BMW and Triumph are not black in colour(false) −
S_NO COMPANY PRICE COLOUR IS_BLACK 2 BMW 900000 Blue 0 4 Triumph 1200000 Red 0 Boolean Operator Using a Client Program
In addition to perform the Boolean Operator in MySQL table using MySQL query, we can also perform the another operation on a table using a client program.
MySQL provides various Connectors and APIs using which you can write programs (in the respective programming languages) to communicate with the MySQL database. The connectors provided are in programming languages such as, Java, PHP, Python, JavaScript, C++ etc. This section provides programs to execute Boolean Operator in MySQL Table.
Syntax
Following are the syntaxes of the MySQL Boolean Operator in various programming languages −
The MySQL PHP connector mysqli provides a function named query() to execute an SQL query in the MySQL database. Depending on the type of query, it retrieves data or performs modifications within the database.
This function accepts two parameters namely −
- $sql: This is a string value representing the query.
- $resultmode: This is an optional parameter which is used to specify the desired format of the result. Which can be MYSQLI_STORE_RESULT (buffered result set object) or, MYSQLI_USE_RESULT (unbuffered result set object) or, MYSQLI_ASYNC.
To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −
$sql = "CREATE TABLE table_name ( Column_name BOOLEAN )"; $mysqli->query($sql);
The MySQL NodeJS connector mysql2 provides a function named query() to execute an SQL query in the MySQL database. This function accepts a string value as a parameter representing the query to be executed.
To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −
sql= "CREATE TABLE table_name ( Column_name BOOLEAN )"; con.query(sql);
We can use the JDBC type 4 driver to communicate to MySQL using Java. It provides a function named execute() to execute an SQL query in the MySQL database. This function accepts a String value as a parameter representing the query to be executed.
To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −
String sql = "CREATE TABLE table_name ( Column_name BOOLEAN )"; statement.execute(sql);
The MySQL Connector/Python provides a function named execute() to execute an SQL query in the MySQL database. This function accepts a string value as a parameter representing the query to be executed.
To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −
query = "CREATE TABLE table_name (Column_name BOOLEAN)" cursorObj.execute(query);
Example
Following are the implementations of this operation in various programming languages −
$dbhost = ''localhost $dbuser = ''root $dbpass = ''password $dbname = ''TUTORIALS $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqli->connect_errno ) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
''); //create table with boolean column $sql = ''CREATE TABLE CUSTOMERS ( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(40), AVAILABILITY BOOLEAN); $result = $mysqli->query($sql); if($result){ printf("Table created successfully...!n"); } //insert data into created table $q = "INSERT INTO CUSTOMERS(ID, NAME, AVAILABILITY) VALUES (1, ''Ramesh'', TRUE)"; If($res = $mysqli->query($q)){ printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM CUSTOMERS"; If($r = $mysqli->query($s)){ printf("Select query executed successfully...!n"); printf("Table records: n"); while($row = $r->fetch_assoc()) { printf("Id %d, Name: %s, AVAILABILITY: %s", $row["ID"], $row["NAME"], $row["AVAILABILITY"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();Output
The output obtained is as follows −
Table created successfully...! Data inserted successfully...! Select query executed successfully...! Table records: Id 1, Name: Ramesh, AVAILABILITY: 1
var mysql = require("mysql2"); var con = mysql.createConnection({ host: "localhost", user: "root", password: "Nr5a0204@123", }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; console.log("Connected!"); console.log("--------------------------"); //Select database sql = "CREATE DATABASE TUTORIALS"; con.query(sql); //Select database sql = "USE TUTORIALS"; con.query(sql); //Creating CUSTOMERS table sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(40), AVAILABILITY BOOLEAN);" con.query(sql , function(err){ if (err) throw err; console.log("Table created Successfully..."); }); //Inserting Records sql = "INSERT INTO CUSTOMERS(ID, NAME, AVAILABILITY) VALUES (1, ''Ramesh'', 0), (2, ''Khilan'', 1), (4, ''Kaushik'', NULL);" con.query(sql); //Displaying all the records of the CUSTOMERS table sql = "SELECT * FROM CUSTOMERS;" con.query(sql, function (err, result) { if (err) throw err; console.log(result); }); });
Output
The output produced is as follows −
Connected! -------------------------- Table created Successfully... [ { ID: 1, NAME: ''Ramesh'', AVAILABILITY: 0 }, { ID: 2, NAME: ''Khilan'', AVAILABILITY: 1 }, { ID: 4, NAME: ''Kaushik'', AVAILABILITY: null } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class BooleanOperator { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String user = "root"; String password = "password"; ResultSet rs; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, password); Statement st = con.createStatement(); //System.out.println("Database connected successfully...!"); //create a table(having boolean field/column) String sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,NAME VARCHAR(40),AVAILABILITY BOOLEAN)"; st.execute(sql); System.out.println("Table created successfully...!"); //now lets insert some records String sql1 = "INSERT INTO CUSTOMERS(ID, NAME, AVAILABILITY) VALUES (1, ''Ramesh'', 0), (2, ''Khilan'', 1), (4, ''Kaushik'', NULL)"; st.executeUpdate(sql1); System.out.println("Records inserted successfully...!"); //lets display the records.... String sql2 = "SELECT * FROM CUSTOMERS"; rs = st.executeQuery(sql2); System.out.println("Table records are: "); while(rs.next()) { String id = rs.getString("Id"); String name = rs.getString("Name"); String is_available = rs.getString("AVAILABILITY"); System.out.println("Id: " + id + ", Name: " + name + ", Is_available: " + is_available); } }catch(Exception e) { e.printStackTrace(); } } }
Output
The output obtained is as shown below −
Table created successfully...! Records inserted successfully...! Table records are: Id: 1, Name: Ramesh, Is_available: 0 Id: 2, Name: Khilan, Is_available: 1 Id: 4, Name: Kaushik, Is_available: null
import mysql.connector # Establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) table_name = ''customer'' # Creating a cursor object cursorObj = connection.cursor() # Create table with boolean column sql = '''''' CREATE TABLE CUSTOMER( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(40), AVAILABILITY BOOLEAN)'''''' cursorObj.execute(sql) print("The table is created successfully!") # Insert data into the created table insert_query = ''INSERT INTO CUSTOMER(ID, NAME, AVAILABILITY) VALUES (1, "Ramesh", TRUE);'' cursorObj.execute(insert_query) print("Row inserted successfully.") # Now display the table records select_query = "SELECT * FROM CUSTOMER" cursorObj.execute(select_query) result = cursorObj.fetchall() print("Tutorial Table Data:") for row in result: print(row) cursorObj.close() connection.close()
Output
Following is the output of the above code −
The table is created successfully! Row inserted successfully. Tutorial Table Data: (1, ''Ramesh'', 1)
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc
Khóa học miễn phí MySQL – DECIMAL nhận dự án làm có lương
MySQL – DECIMAL
The MySQL Decimal Data Type
The MySQL DECIMAL data type is used to store numeric values with decimal points. It allows for precise calculations and can be configured to store a specified number of digits before and after the decimal point.
We often use this datatype for the columns that require exact precision such as salaries of employees, employee PF balances, etc.
Internally, MySQL stores DECIMAL values using a binary format that allocates storage for the integer and fractional parts of the number separately. This binary format efficiently packs 9 digits into 4 bytes of storage.
Syntax
Following is the syntax to define a column whose data type is DECIMAL −
column_name DECIMAL(P,D);
Where,
-
P is called precision which specifies the total number of significant digits that can be stored in the column, both to the left and right of the decimal point. The range of P is 1 to 65.
-
D is a scale that specifies the maximum number of digits that can be stored after the decimal point. The range of D should be between 0 and 30 and D is less than or equal to (<=) P.
For instance, if we define a column as DECIMAL(10,2), it can store numbers with up to 10 digits, and up to 2 digits to the right of the decimal point.
In MySQL, instead of the DECIMAL keyword, we can also use the “DEC”, “FIXED” and “NUMERIC” keywords because they are synonyms for DECIMAL.
Attributes
The DECIMAL keyword has two attributes: UNSIGNED and ZEROFILL.
-
UNSIGNED − When used, it indicates that the column does not accept negative values.
-
ZEROFILL − If used, it pads the number with zeros to the specified width.
Precision and Scale
In the following query, we define a SALARY column with the DECIMAL data type, specifying a precision of 5 and a scale of 3 −
SALARY decimal(5,3)
This definition means that the SALARY column can store values with up to 5 digits in total, including 3 digits to the right of the decimal point. The range for this column would be from 99.999 to -99.999.
No Decimal Places
In here, the SALARY column contains no fractional part or decimal point. The following two queries are same −
SALARY DECIMAL(5); SALARY DECIMAL(5,0);
Both declarations indicate that the SALARY column can store values as whole numbers without decimal places.
Default Precision
If you omit the precision value, the default precision P will be 10 −
SALARY DECIMAL;
MySQL DECIMAL Storage
MySQL stores values of the “DECIMAL” data type using a binary format that optimizes storage. Specifically, MySQL packs 9 digits into 4 bytes. Storage is allocated separately for the integer and fractional parts, with 4 bytes used for each set of 9 digits. Any remaining digits require additional storage.
The storage required for remaining (leftover) digits is demonstrated in the following table:
Leftover Digits | Bytes |
---|---|
0 | 0 |
1-2 | 1 |
3-4 | 2 |
5-6 | 3 |
7-9 | 4 |
Consider a DECIMAL(30,9) column, which has 9 digits for the fractional part and 30 – 9 = 21 digits for the integer part. In this case, the fractional part takes 4 bytes. The integer part takes 8 bytes for the first 18 digits, and for the leftover 3 digits, it requires an additional 2 bytes. Therefore, the DECIMAL(30,9) column requires a total of 14 bytes.
Example
To further understand this, let us create a table named EMPLOYEES using the following query −
CREATE TABLE EMPLOYEES ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, SALARY decimal(14,4) NOT NULL, PRIMARY KEY (ID) );
Using the following query, we are inserting some records into the above created table −
INSERT INTO EMPLOYEES (NAME, SALARY) VALUES ("Krishna", 150050.34), ("Kalyan", 100000.65);
The EMPLOYEES table obtained is as follows −
ID | NAME | SALARY |
---|---|---|
1 | Krishna | 150050.3400 |
2 | Kalyan | 100000.6500 |
Using the following query, we are including the ZEROFILL attribute in the “SALARY” column −
ALTER TABLE EMPLOYEES MODIFY SALARY decimal(14, 4) zerofill;
Following is the output of the above query −
Query OK, 2 rows affected, 1 warning (0.03 sec) Records: 2 Duplicates: 0 Warnings: 1
Here, we are trying to fetch all the records from the EMPLOYEES tables after including the ZEROFILL attribute on SALARY column −
SELECT * FROM EMPLOYEES;
The records will display zeros padded based on the range specified in the “SALARY” column −
ID | NAME | SALARY |
---|---|---|
1 | Krishna | 0000150050.3400 |
2 | Kalyan | 0000100000.6500 |
Decimal Datatype Using a Client Program
We can also create column of the decimal datatype using the client program.
Syntax
To create a column of decimal datatype through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −
$sql = ''CREATE TABLE EMPLOYEES ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, SALARY decimal(14,4) NOT NULL, PRIMARY KEY (ID) ) $mysqli->query($sql);
To create a column of decimal datatype through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −
sql = "CREATE TABLE EMPLOYEES ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, SALARY decimal(14,4) NOT NULL, PRIMARY KEY (ID) )"; con.query(sql);
To create a column of decimal datatype through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −
String sql = "CREATE TABLE STUDENTS (ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, BRANCH ENUM ("CSE", "ECE", "MECH"), FEES int NOT NULL, PRIMARY KEY (ID))"; statement.execute(sql);
To create a column of decimal datatype through a python program, we need to execute the “CREATE TABLE” statement using the execute() function of the MySQL Connector/Python as follows −
sql = ''CREATE TABLE EMPLOYEES (ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, SALARY decimal(14,4) NOT NULL, PRIMARY KEY (ID))'' cursorObj.execute(sql)
Example
Following are the programs −
$dbhost = ''localhost $dbuser = ''root $dbpass = ''password $dbname = ''TUTORIALS $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($mysqli->connect_errno) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
''); //create table with boolean column $sql = ''CREATE TABLE EMPLOYEES ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, SALARY decimal(14,4) NOT NULL, PRIMARY KEY (ID) ) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } //insert data into created table $q = "INSERT INTO EMPLOYEES (NAME, SALARY) VALUES (''Krishna'', 150050.34), (''Kalyan'', 100000.65)"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT ID, Salary FROM EMPLOYEES"; if ($r = $mysqli->query($s)) { printf("Table Records: Where Salary is decimal type! n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Salary: %s", $row["ID"], $row["Salary"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();
Output
The output obtained is as follows −
Table created successfully...! Data inserted successfully...! Table Records: Where Salary is decimal type! ID: 1, Salary: 150050.3400 ID: 2, Salary: 100000.6500
var mysql = require("mysql2"); var con = mysql.createConnection({ host: "localhost", user: "root", password: "password", }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; // console.log("Connected successfully...!"); // console.log("--------------------------"); sql = "USE TUTORIALS"; con.query(sql); //create a employees table, that accepts one column of decimal type. sql = "CREATE TABLE EMPLOYEES ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, SALARY decimal(14,4) NOT NULL, PRIMARY KEY (ID) )"; con.query(sql); //insert data into created table sql = "INSERT INTO EMPLOYEES (NAME, SALARY) VALUES (''Krishna'', 150050.34), (''Kalyan'', 100000.65)"; con.query(sql); //select datatypes of salary sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''EMPLOYEES'' AND COLUMN_NAME = ''SALARY''`; con.query(sql, function (err, result) { if (err) throw err; console.log(result); }); });
Output
The output produced is as follows −
[ { DATA_TYPE: ''decimal'' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Decimal { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String username = "root"; String password = "password"; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); System.out.println("Connected successfully...!"); //Decimal data types...!; String sql = "CREATE TABLE EMPLOYEES ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, SALARY decimal(14,4) NOT NULL, PRIMARY KEY (ID))"; statement.execute(sql); System.out.println("column of a Decimal type created successfully...!"); ResultSet resultSet = statement.executeQuery("DESCRIBE EMPLOYEES"); while (resultSet.next()){ System.out.println(resultSet.getString(1)+" "+resultSet.getString(2)); } connection.close(); } catch (Exception e) { System.out.println(e); } } }
Output
The output obtained is as shown below −
Connected successfully...! column of a Decimal type created successfully...! ID int NAME varchar(30) SALARY decimal(14,4)
import mysql.connector # Establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) # Creating a cursor object cursorObj = connection.cursor() # Create table with decimal column sql = '''''' CREATE TABLE EMPLOYEES ( ID int NOT NULL AUTO_INCREMENT, NAME varchar(30) NOT NULL, SALARY decimal(14,4) NOT NULL, PRIMARY KEY (ID) )'''''' cursorObj.execute(sql) print("The table is created successfully!") # Data to be inserted data_to_insert = [ (''Krishna'', 150050.34), (''Kalyan'', 100000.65) ] # Insert data into the created table insert_query = "INSERT INTO EMPLOYEES (NAME, SALARY) VALUES (%s, %s)" cursorObj.executemany(insert_query, data_to_insert) # Commit the changes after the insert operation connection.commit() print("Rows inserted successfully.") # Now display the table records select_query = "SELECT * FROM EMPLOYEES" cursorObj.execute(select_query) result = cursorObj.fetchall() print("Table Data:") for row in result: print(row) cursorObj.close() connection.close()
Output
Following is the output of the above code −
The table is created successfully! Rows inserted successfully. Table Data: (1, ''Krishna'', Decimal(''150050.3400'')) (2, ''Kalyan'', Decimal(''100000.6500''))
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