Your cart is currently empty!
Category: mysql
-
Khóa học miễn phí MySQL – BOOLEAN nhận dự án làm có lương
MySQL – Boolean Datatype
Table of content
A Boolean data type is used to represent truth values of logic and Boolean algebra. It has two possible values: either true or false.
For example, if a customer wants to see all the bikes that are black in colour, we can filter them using BOOLEAN operator, as given in the following table −
Here, ”IS_BLACK” is the BOOLEAN column that returns either true or false values based on the colours of the bikes.
Boolean in MySQL
In MySQL, there is no built-in Boolean or Bool data type. Instead MySQL provides us with the TINYINT datatype to store the Boolean values.
MySQL considers the value 0 as FALSE and 1 as TRUE. We can also store NULL values using the TINYINT datatype.
The Boolean values (such as TRUE and FALSE) are not case-sensitive.
Syntax
Following is the syntax of the BOOLEAN operator in MySQL −
CREATE TABLE table_name ( Column_name BOOLEAN );
Example
In MySQL, 0 is defined as FALSE and any non-zero values are defined as TRUE −
SELECT TRUE, FALSE;
Output
As we can see in the output below, TRUE and FALSE are represented as 1 and 0 −
TRUE FALSE 1 0 Example
In MySQL, the Boolean values (TRUE and FALSE) are case-insensitive −
SELECT true, false, TRUE, FALSE, True, False;
Output
The output produced is as given below −
true false TRUE FALSE True False 1 0 1 0 1 0 Example
Now, let”s create a table with the name CUSTOMERS using the following query. Here, the AVAILABILITY column specifies whether the customer is available or not. If the bit value is 0 (FALSE), the customer is not available. If it is 1(TRUE), the customer is available −
CREATE TABLE CUSTOMERS ( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(40), AVAILABILITY BOOLEAN );
Following is the output produced −
Query OK, 0 rows affected (0.02 sec)
To get the information about the CUSTOMERS table, use the following query −
DESCRIBE CUSTOMERS;
If we look at the AVAILABILITY column, which has been set to BOOLEAN while creating the table, it now shows type of TINYINT −
Field Type Null Key Default Extra ID int NO PRI NULL auto_increment NAME varchar(40) YES NULL AVAILABILITY tinyint(1) YES NULL Now, let us insert some records into the CUSTOMERS table using the following INSERT query −
INSERT INTO CUSTOMERS VALUES (1, ''Ramesh'', FALSE), (2, ''Khilan'', TRUE), (4, ''Kaushik'', NULL);
Using the below query, we can display all the values in the table −
SELECT * FROM CUSTOMERS;
We can see the values in the AVAILABILITY column are set to 0 and 1 respectively. −
ID NAME AVAILABILITY 1 Ramesh 0 2 Khilan 1 4 Kaushik NULL Replacing BOOLEAN 0,1 with TRUE and FALSE
As we can see in the above CUSTOMERS table, the BOOLEAN data type shows 0 and 1 values instead of TRUE and FALSE. In MySQL, we can convert BOOLEAN data type to TRUE and FALSE values using the CASE statement.
The MySQL CASE statement is a conditional statement that goes through conditions and return a values when the first condition is met. Therefore, once a condition is true, it will stop reading the next piece of code and return the result.
If no conditions are true, it will return the value in the ELSE clause. If no ELSE clause is present and no conditions are true, it returns NULL.
Syntax
Following is the syntax of CASE statement in MySQL −
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... WHEN conditionN THEN resultN ELSE result END;
Example
To get a better understanding, let us consider the BIKES table created using the query below −
CREATE TABLE BIKES ( S_NO INT AUTO_INCREMENT PRIMARY KEY, COMPANY VARCHAR(40) NOT NULL, PRICE INT NOT NULL, COLOUR VARCHAR(40) NOT NULL, IS_BLACK BOOLEAN );
Example
Output of the above code is as follows −
Query OK, 0 rows affected (0.03 sec)
Now, let us insert values into the BIKES table using the INSERT statement as shown below −
INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK) VALUES (''Royal Enfield'', 300000, ''Black'', 1); INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK) VALUES (''BMW'', 900000, ''Blue'', 0); INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK) VALUES (''Jawa'', 150000, ''Black'', 1); INSERT INTO BIKES (COMPANY, PRICE, COLOUR, IS_BLACK) VALUES (''Triumph'', 1200000, ''Red'', 0);
The BIKES table obtained is as follows −
S_NO COMPANY PRICE COLOUR IS_BLACK 1 Royal Enfield 300000 Black 1 2 BMW 900000 Blue 0 3 Jawa 150000 Black 1 4 Triumph 1200000 Red 0 Now, let us display all the records from the BIKES table, where the colour BLACK is represented by either TRUE or FALSE −
SELECT *, CASE IS_BLACK WHEN 1 THEN ''TRUE'' WHEN 0 THEN ''FALSE'' END AS IS_BOOLEAN FROM BIKES;
Output
The output is displayed as follows −
S_NO COMPANY PRICE COLOUR IS_BLACK IS_BOOLEAN 1 Royal Enfield 300000 Black 1 TRUE 2 BMW 900000 Blue 0 FALSE 3 Jawa 150000 Black 1 TRUE 4 Triumph 1200000 Red 0 FALSE Example
In the following query, we are filtering the records from the BIKES table where colour black is TRUE −
SELECT * FROM BIKES WHERE IS_BLACK IS TRUE;
Output
As we can see the output below, Royal Enfield and Jawa are black in color (true) −
S_NO COMPANY PRICE COLOUR IS_BLACK 1 Royal Enfield 300000 Black 1 3 Jawa 150000 Black 1 Example
In here, we are filtering the records from the BIKES table where color black is FALSE −
SELECT * FROM BIKES WHERE IS_BLACK IS FALSE;
Output
The output says that BMW and Triumph are not black in colour(false) −
S_NO COMPANY PRICE COLOUR IS_BLACK 2 BMW 900000 Blue 0 4 Triumph 1200000 Red 0 Boolean Operator Using a Client Program
In addition to perform the Boolean Operator in MySQL table using MySQL query, we can also perform the another operation on a table using a client program.
MySQL provides various Connectors and APIs using which you can write programs (in the respective programming languages) to communicate with the MySQL database. The connectors provided are in programming languages such as, Java, PHP, Python, JavaScript, C++ etc. This section provides programs to execute Boolean Operator in MySQL Table.
Syntax
Following are the syntaxes of the MySQL Boolean Operator in various programming languages −
The MySQL PHP connector mysqli provides a function named query() to execute an SQL query in the MySQL database. Depending on the type of query, it retrieves data or performs modifications within the database.
This function accepts two parameters namely −
- $sql: This is a string value representing the query.
- $resultmode: This is an optional parameter which is used to specify the desired format of the result. Which can be MYSQLI_STORE_RESULT (buffered result set object) or, MYSQLI_USE_RESULT (unbuffered result set object) or, MYSQLI_ASYNC.
To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −
$sql = "CREATE TABLE table_name ( Column_name BOOLEAN )"; $mysqli->query($sql);
The MySQL NodeJS connector mysql2 provides a function named query() to execute an SQL query in the MySQL database. This function accepts a string value as a parameter representing the query to be executed.
To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −
sql= "CREATE TABLE table_name ( Column_name BOOLEAN )"; con.query(sql);
We can use the JDBC type 4 driver to communicate to MySQL using Java. It provides a function named execute() to execute an SQL query in the MySQL database. This function accepts a String value as a parameter representing the query to be executed.
To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −
String sql = "CREATE TABLE table_name ( Column_name BOOLEAN )"; statement.execute(sql);
The MySQL Connector/Python provides a function named execute() to execute an SQL query in the MySQL database. This function accepts a string value as a parameter representing the query to be executed.
To perform the Boolean operation in MySQL table, we need to execute the CREATE TABLE statement using this function as −
query = "CREATE TABLE table_name (Column_name BOOLEAN)" cursorObj.execute(query);
Example
Following are the implementations of this operation in various programming languages −
$dbhost = ''localhost $dbuser = ''root $dbpass = ''password $dbname = ''TUTORIALS $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqli->connect_errno ) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
''); //create table with boolean column $sql = ''CREATE TABLE CUSTOMERS ( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(40), AVAILABILITY BOOLEAN); $result = $mysqli->query($sql); if($result){ printf("Table created successfully...!n"); } //insert data into created table $q = "INSERT INTO CUSTOMERS(ID, NAME, AVAILABILITY) VALUES (1, ''Ramesh'', TRUE)"; If($res = $mysqli->query($q)){ printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM CUSTOMERS"; If($r = $mysqli->query($s)){ printf("Select query executed successfully...!n"); printf("Table records: n"); while($row = $r->fetch_assoc()) { printf("Id %d, Name: %s, AVAILABILITY: %s", $row["ID"], $row["NAME"], $row["AVAILABILITY"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();Output
The output obtained is as follows −
Table created successfully...! Data inserted successfully...! Select query executed successfully...! Table records: Id 1, Name: Ramesh, AVAILABILITY: 1
var mysql = require("mysql2"); var con = mysql.createConnection({ host: "localhost", user: "root", password: "Nr5a0204@123", }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; console.log("Connected!"); console.log("--------------------------"); //Select database sql = "CREATE DATABASE TUTORIALS"; con.query(sql); //Select database sql = "USE TUTORIALS"; con.query(sql); //Creating CUSTOMERS table sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(40), AVAILABILITY BOOLEAN);" con.query(sql , function(err){ if (err) throw err; console.log("Table created Successfully..."); }); //Inserting Records sql = "INSERT INTO CUSTOMERS(ID, NAME, AVAILABILITY) VALUES (1, ''Ramesh'', 0), (2, ''Khilan'', 1), (4, ''Kaushik'', NULL);" con.query(sql); //Displaying all the records of the CUSTOMERS table sql = "SELECT * FROM CUSTOMERS;" con.query(sql, function (err, result) { if (err) throw err; console.log(result); }); });
Output
The output produced is as follows −
Connected! -------------------------- Table created Successfully... [ { ID: 1, NAME: ''Ramesh'', AVAILABILITY: 0 }, { ID: 2, NAME: ''Khilan'', AVAILABILITY: 1 }, { ID: 4, NAME: ''Kaushik'', AVAILABILITY: null } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class BooleanOperator { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String user = "root"; String password = "password"; ResultSet rs; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, password); Statement st = con.createStatement(); //System.out.println("Database connected successfully...!"); //create a table(having boolean field/column) String sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,NAME VARCHAR(40),AVAILABILITY BOOLEAN)"; st.execute(sql); System.out.println("Table created successfully...!"); //now lets insert some records String sql1 = "INSERT INTO CUSTOMERS(ID, NAME, AVAILABILITY) VALUES (1, ''Ramesh'', 0), (2, ''Khilan'', 1), (4, ''Kaushik'', NULL)"; st.executeUpdate(sql1); System.out.println("Records inserted successfully...!"); //lets display the records.... String sql2 = "SELECT * FROM CUSTOMERS"; rs = st.executeQuery(sql2); System.out.println("Table records are: "); while(rs.next()) { String id = rs.getString("Id"); String name = rs.getString("Name"); String is_available = rs.getString("AVAILABILITY"); System.out.println("Id: " + id + ", Name: " + name + ", Is_available: " + is_available); } }catch(Exception e) { e.printStackTrace(); } } }
Output
The output obtained is as shown below −
Table created successfully...! Records inserted successfully...! Table records are: Id: 1, Name: Ramesh, Is_available: 0 Id: 2, Name: Khilan, Is_available: 1 Id: 4, Name: Kaushik, Is_available: null
import mysql.connector # Establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) table_name = ''customer'' # Creating a cursor object cursorObj = connection.cursor() # Create table with boolean column sql = '''''' CREATE TABLE CUSTOMER( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(40), AVAILABILITY BOOLEAN)'''''' cursorObj.execute(sql) print("The table is created successfully!") # Insert data into the created table insert_query = ''INSERT INTO CUSTOMER(ID, NAME, AVAILABILITY) VALUES (1, "Ramesh", TRUE);'' cursorObj.execute(insert_query) print("Row inserted successfully.") # Now display the table records select_query = "SELECT * FROM CUSTOMER" cursorObj.execute(select_query) result = cursorObj.fetchall() print("Tutorial Table Data:") for row in result: print(row) cursorObj.close() connection.close()
Output
Following is the output of the above code −
The table is created successfully! Row inserted successfully. Tutorial Table Data: (1, ''Ramesh'', 1)
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc
Khóa học miễn phí MySQL – FLOAT nhận dự án làm có lương
MySQL – FLOAT
The FLOAT data type is a part of the numeric data type. Numeric data types are used to store numbers, and they can be categorized into various subtypes based on their characteristics, such as storage size and precision.
The MySQL FLOAT Data Type
The MySQL FLOAT datatype is a floating-point number type that stores approximate numeric values. It stores approximate numeric values in 4 bytes and represents single-precision values.
FLOAT is suitable for a wide range of numeric values but stores them in an approximate manner due to the IEEE 754 standard limitations.
FLOAT data type can represent both signed and unsigned attributes of a data value in versions prior to MySQL 8.0.17, but the unsigned FLOAT is deprecated in MySQL 8.0.17 and later versions.
Syntax
Following is the basic syntax to set the datatype of a field as FLOAT −
CREATE TABLE (column_name FLOAT, ...);
Example
In this example, let us create a new database table named ”datatype_demo” using CREATE TABLE statement with columns representing FLOAT values −
CREATE TABLE datatype_demo( ID INT, NAME VARCHAR(50), HEIGHT FLOAT, WEIGHT FLOAT );
Following is the output obtained −
Query OK, 0 rows affected (0.03 sec)
Verification
Once the table is created, we can verify the data types of the ”HEIGHT” and ”WEIGHT” fields by retrieving the table”s definition as shown below −
DESC datatype_demo;
The result of the DESC command will show that the ”HEIGHT” and ”WEIGHT” fields have the FLOAT data type −
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
ID | int | YES | NULL | ||
NAME | varchar(50) | YES | NULL | ||
HEIGHT | float | YES | NULL | ||
WEIGHT | float | YES | NULL |
To verify further, let us insert some values into the table using the following INSERT statement −
INSERT INTO datatype_demo VALUES (1, ''John'', 171.3, 65.7), (2, ''Rob'', 45, 75), (3, ''Salman'', 12.74839, 54.262), (4, ''Arush'', NULL, NULL), (5, ''James'', ''h'', ''w'');
Following is the output obtained −
ERROR 1265 (01000): Data truncated for column ''HEIGHT'' at row 1
As expected, the FLOAT fields accept single precision floating-point numbers without any issues. However, when attempting to insert non-numeric values into these fields, such as ”h” and ”w,” MySQL raises an error, indicating data truncation.
Finally, to view the data that has been inserted into the table, we can use the SELECT statement as shown below −
SELECT * FROM datatype_demo;
The resultant table is as follows −
ID | NAME | HEIGHT | WEIGHT |
---|---|---|---|
1 | John | 171.3 | 65.7 |
2 | Rob | 45 | 75 |
3 | Salman | 12.7484 | 54.262 |
4 | Arush | NULL | NULL |
Other Representations of MySQL FLOAT
MySQL has a provision to specify the range of precision (not the exponent) for the FLOAT datatype in the form of bits. These bits are specified within the parenthesis following the keyword FLOAT, i.e. FLOAT(p).
However, this precision value is only used to determine the storage size and only holds up to 7 decimal places, with the range from 0 to 23 bits. If the precision bit exceeds 23, the data type becomes DOUBLE.
Example
First, we will drop the existing ”datatype_demo” table −
DROP TABLE datatype_demo;
The output obtained is as follows −
Query OK, 0 rows affected (0.01 sec)
Then, we will create a new table ”datatype_demo” specifying a precision of 20 bits for the ”HEIGHT” column −
CREATE TABLE datatype_demo( ID INT, NAME VARCHAR(50), HEIGHT FLOAT(20) );
Following is the output of the above code −
Query OK, 0 rows affected (0.02 sec)
Verification
Even though we specified a precision of 20 bits, the ”HEIGHT” column will still store float values within the single-precision range, holding up to 7 decimal places. To verify the table”s definition, we can use the DESC command as shown below −
DESC datatype_demo;
The table produced is as follows −
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
ID | int | YES | NULL | ||
NAME | varchar(50) | YES | NULL | ||
HEIGHT | float | YES | NULL |
If the precision bit exceeds 23, the datatype becomes DOUBLE. Look at the query below −
CREATE TABLE datatype_demo1( ID INT, NAME VARCHAR(50), HEIGHT FLOAT(30) );
we get the following output −
Query OK, 0 rows affected (0.02 sec)
Again, we can verify the table”s definition using the DESC command −
DESC datatype_demo1;
Following is the table obtained −
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
ID | int | YES | NULL | ||
NAME | varchar(50) | YES | NULL | ||
HEIGHT | double | YES | NULL |
Float Datatype Using a Client Program
We can also create column of the Float datatype using the client program.
Syntax
To create a column of Float datatype through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −
$sql = ''CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id)) $mysqli->query($sql);
To create a column of Float datatype through a JavaScript program, we need to execute the “CREATE TABLE” statement using the query() function of mysql2 library as follows −
sql = "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))"; con.query(sql);
To create a column of Float datatype through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −
String sql = "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))"; statement.execute(sql);
To create a column of Float datatype through a python program, we need to execute the “CREATE TABLE” statement using the execute() function of the MySQL Connector/Python as follows −
sql = ''CREATE TABLE datatype_demo(ID INT, NAME VARCHAR(50), HEIGHT FLOAT, WEIGHT FLOAT)'''' cursorObj.execute(sql)
Example
Following are the programs −
$dbhost = ''localhost $dbuser = ''root $dbpass = ''password $dbname = ''TUTORIALS $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($mysqli->connect_errno) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
''); //creating a table temp where we are inserting the celsius and Fahrenheit values in float $sql = ''CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id)) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } // insert data into created table $q = " INSERT INTO temp(Celsius, Fahrenheit) VALUES ( 36.2, 97.16), ( 35.8, 96.44), ( 37.32, 99.17), ( 35.89, 96.602);"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM temp"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Celsius: %f, Fahrenheit: %f", $row["Id"], $row["Celsius"], $row["Fahrenheit"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();
Output
The output obtained is as follows −
Table created successfully...! Data inserted successfully...! Table Records: ID: 1, Celsius: 36.200000, Fahrenheit: 97.160000 ID: 2, Celsius: 35.800000, Fahrenheit: 96.440000 ID: 3, Celsius: 37.320000, Fahrenheit: 99.170000 ID: 4, Celsius: 35.890000, Fahrenheit: 96.602000
var mysql = require("mysql2"); var con = mysql.createConnection({ host: "localhost", user: "root", password: "password", }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; // console.log("Connected successfully...!"); // console.log("--------------------------"); sql = "USE TUTORIALS"; con.query(sql); //create a student table, that accepts one column of float type. sql = "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))"; con.query(sql); //insert data into created table sql = "INSERT INTO temp(Celsius, Fahrenheit) VALUES ( 36.2, 97.16), ( 35.8, 96.44), ( 37.32, 99.17), ( 35.89, 96.602)"; con.query(sql); //select datatypes of salary sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''temp'' AND COLUMN_NAME = ''Celsius''`; con.query(sql, function (err, result) { if (err) throw err; console.log(result); }); });
Output
The output produced is as follows −
[ { DATA_TYPE: ''float'' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Float { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String username = "root"; String password = "password"; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); System.out.println("Connected successfully...!"); //Float data types...!; String sql = "CREATE TABLE temp(Id INT AUTO_INCREMENT, Celsius FLOAT, Fahrenheit FLOAT, PRIMARY KEY(Id))"; statement.execute(sql); System.out.println("column of a Float type created successfully...!"); ResultSet resultSet = statement.executeQuery("DESCRIBE temp"); while (resultSet.next()){ System.out.println(resultSet.getString(1)+" "+resultSet.getString(2)); } connection.close(); } catch (Exception e) { System.out.println(e); } } }
Output
The output obtained is as shown below −
Connected successfully...! column of a Float type created successfully...! Id int Celsius float Fahrenheit float
import mysql.connector # Establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) # Creating a cursor object cursorObj = connection.cursor() # Create table with float column sql = '''''' CREATE TABLE datatype_demo(ID INT, NAME VARCHAR(50), HEIGHT FLOAT, WEIGHT FLOAT ) '''''' cursorObj.execute(sql) print("The table is created successfully!") # Data to be inserted data_to_insert = [ (1, ''John'', 171.3, 65.7), (2, ''Rob'', 45, 75), (3, ''Salman'', 12.74839, 54.262), (4, ''Arush'', None, None), ] # Insert data into the created table insert_query = "INSERT INTO datatype_demo (ID, NAME, HEIGHT, WEIGHT) VALUES (%s, %s, %s, %s)" cursorObj.executemany(insert_query, data_to_insert) # Commit the changes after the insert operation connection.commit() print("Rows inserted successfully.") # Now display the table records select_query = "SELECT * FROM datatype_demo" cursorObj.execute(select_query) result = cursorObj.fetchall() print("Table Data:") for row in result: print(row) cursorObj.close() connection.close()
Output
Following is the output of the above code −
The table is created successfully! Rows inserted successfully. Table Data: (1, ''John'', 171.3, 65.7) (2, ''Rob'', 45.0, 75.0) (3, ''Salman'', 12.7484, 54.262) (4, ''Arush'', None, None)
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc