Your cart is currently empty!
Category: mysql
-
Khóa học miễn phí MySQL – BLOB nhận dự án làm có lương
MySQL – BLOB
Table of content
Many user applications require the storage of different types of data, including text, images, files, and more. Using BLOBs in a MySQL database allows you to store all these types of data within the same database, eliminating the need for a separate file system.
The MySQL BLOB Data Type
The MySQL BLOB (Binary Large Object) data type is used to store binary data, such as images, audio, video, or any other type of binary file. BLOB columns can store variable-length binary data, making it suitable for handling files of various sizes.
Consider an application that collects user information through forms. This information may include personal details, such as name and address, along with image proofs like PAN cards or AADHAR cards. Instead of managing these files separately in a file system, you can store them as BLOBs in a MySQL database.
Syntax
Following is the basic syntax to assign BLOB data type on a table field −
CREATE TABLE table_name (column_name BLOB,...)
Example
Let us consider a basic example to show how to assign BLOB datatype to a table field. Here, we are creating a table named ”demo_table” with two fields “ID” and “DEMO_FILE” −
CREATE TABLE demo_table ( ID INT NOT NULL, DEMO_FILE BLOB );
Following is the output obtained −
Query OK, 0 rows affected (0.01 sec)
You can see the table structure with the following command −
DESC demo_table;
The table obtained is as follows −
Field Type Null Key Default Extra ID int NO NULL DEMO_FILE blob YES NULL Inserting Data into BLOB Fields
You can insert some values into a database table, by loading a file to the BLOB field using the LOAD_FILE() function. However, before doing so, ensure that the following conditions are met −
-
File Existence −The file you want to insert must exist on the MySQL server host location. To determine the required location, you can use the secure_file_priv variable with the following command. If the result of this command is not empty, the file to be loaded must be located in that specific directory.
SHOW VARIABLES LIKE secure_file_priv;
Specify Full File Path − When using the LOAD_FILE() function, you must pass the full path of the file as an argument, like ”/users/tutorialspoint/file_name.txt”. For Windows users, remember to use double backslashes as escape characters in the path (”//users//tutorialspoint//file_name.txt”).
Check ”max_allowed_packet” Value − MySQL Server has a max_allowed_packet variable that determines the maximum allowed file size for loading. To check the value of this variable, you can use the following command −
SHOW VARIABLES LIKE max_allowed_packet;
Ensure that the file size does not exceed the value specified in this variable.
Grant FILE Privileges − Make sure the MySQL user account has FILE privileges granted. To grant file privileges to a user, you can use the following command (usually performed by a user with administrative privileges, such as ”root”) −
GRANT FILE ON *.* TO ''username''@''hostname FLUSH PRIVILEGES;
File Readability − Lastly, make sure that the file is readable by the MySQL server.
Example
To insert values into a previously created table ”demo_table”, you can use the following INSERT query −
INSERT INTO demo_table VALUES(1, LOAD_FILE("C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\sample.txt"));
To verify the insertion, you can retrieve the data from the ”demo_table” using the following query −
SELECT * FROM demo_table;
We can see in the output below, the table contains the hex string of content present in the ”sample.txt” file. You can load any type of files into MySQL, like images, multimedia files, PDF documents etc. −
ID DEMO_FILE 1 0x5468697320697320612073616D706C652066696C65 Types of BLOB Datatype
MySQL provides four types of BLOB datatypes, each with varying maximum storage capacities. While they all serve the same purpose of storing binary data, such as images or files, they differ in the maximum size of objects they can accommodate. Here are the four BLOB datatypes −
-
TINYBLOB − It can store a maximum of 255 bytes, or 255 characters.
-
BLOB − It can store up to 65,535 (216 – 1) bytes, which is equivalent to 64KB of data.
-
MEDIUMBLOB − It can store up to 16,777,215 (224 – 1) bytes, or 4GB.
-
LONGBLOB − It is the largest among these datatypes and can store objects up to 4,294,967,295 bytes (232 – 1), or 4GB.
Let us try to create tables with all types of BLOB datatypes mentioned above.
Creating a Table with TINYBLOB Datatype
In this example, we are creating a table named ”demo_tinyblob” with TINYBLOB datatype on a field −
CREATE TABLE demo_tinyblob (ID INT, DEMO_FIELD TINYBLOB);
Output
Following is the output obtained −
Query OK, 0 rows affected (0.02 sec)
Verification
You can see the table structure with the following command −
DESC demo_tinyblob;
The table obtained is as follows −
Field Type Null Key Default Extra ID int YES NULL DEMO_FIELD tinyblob YES NULL Creating a Table with MEDIUMBLOB Datatype
Here, we are creating a table named ”demo_mediumblob” with a field of type MEDIUMBLOB using the following query −
CREATE TABLE demo_mediumblob (ID INT, DEMO_FIELD MEDIUMBLOB);
Output
Output of the above code is as follows −
Query OK, 0 rows affected (0.02 sec)
Verification
You can see the table structure with the following command −
DESC demo_mediumblob;
Following is the table obtained −
Field Type Null Key Default Extra ID int YES NULL DEMO_FIELD mediumblob YES NULL Creating a Table with LONGBLOB Datatype
In this case, we are creating a table named ”demo_longblob” with a field of type LONGBLOB −
CREATE TABLE demo_longblob (ID INT, DEMO_FIELD LONGBLOB);
Output
Following is the result produced −
Query OK, 0 rows affected (0.02 sec)
Verification
You can see the table structure with the command given below −
DESC demo_longblob;
The table produced is as shown below −
Field Type Null Key Default Extra ID int YES NULL DEMO_FIELD longblob YES NULL
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 – SET nhận dự án làm có lương
MySQL – SET
The MySQL SET data type
The MySQL SET data type is used to store a set of values chosen from a predefined list of values. Each column of the SET datatype can have zero or more values chosen from its list of values. These values are specified as a comma-separated list when inserting or updating data.
It is important to note that the list of values that can be stored in a SET column is defined at the time the table is created, and any values outside this list are not allowed.
For example, if we define a SET column like this −
test_col SET(''one'', ''two'') NOT NULL
The possible values for this column are −
- An empty string (””)
- ”one”
- ”two”
- ”one,two”
Storage of SET Data Type
A MySQL SET column can hold a maximum of 64 distinct members, which means that duplicate values are not allowed. If duplicates exist, MySQL will generate an error or a warning when strict SQL mode is enabled. Additionally, MySQL automatically removes trailing spaces from SET values when creating a table.
In MySQL, when you store a number in a SET column, the bits set in the binary representation of that number determine which set members are included in the column value. Consider the following query for a better understanding −
Create table test_table ( ID int auto_increment primary key , COL1 set(''Goa'', ''Assam'', ''Delhi'', ''Kerala'') );
In the above query, each set member is assigned a single bit with corresponding decimal and binary values −
Set Member | Decimal Value | Binary Value |
---|---|---|
Goa | 1 | 0001 |
Assam | 2 | -0010 |
Delhi | 4 | 0100 |
Kerala | 8 | 1000 |
So, if a value of 3 is assigned to the column (binary: 0011), it selects the first two SET members, resulting in ”Goa,Assam”.
Example
First of all, let us create a table with the name test_table using the following query −
Create table test_table ( ID int auto_increment primary key , COL1 set(''Goa'', ''Assam'', ''Delhi'', ''Kerala'') );
Following is the output obtained −
Query OK, 0 rows affected (0.02 sec)
When inserting values into a SET column, there is no specific order required for listing the elements. Even if a particular element is listed multiple times, when retrieved later, each element will appear only once, following the order specified during table creation.
Here, we are inserting the values into the set −
INSERT INTO test_table (COL1) VALUES (''Goa,Assam''), (''Assam,Goa''), (''Goa,Assam,Goa''), (''Goa,Assam,Assam''), (''Assam,Goa,Assam'');
Output
The output produced is as shown below −
Query OK, 5 rows affected (0.00 sec) Records: 5 Duplicates: 0 Warnings: 0
Verification
Let us display all the records of the ”test_table” using the SELECT statement as follows −
SELECT * FROM test_table;
As we can see the output below, all the values in ”COL1” will appear as ”Goa,Assam” −
ID | COL1 |
---|---|
1 | Goa,Assam |
2 | Goa,Assam |
3 | Goa,Assam |
4 | Goa,Assam |
5 | Goa,Assam |
Example
In the following query, we are searching for the SET values in the table using the MySQL LIKE operator. It finds rows where ”COL1” contains ”GOA” anywhere, even as a substring −
SELECT * FROM test_table WHERE COL1 LIKE ''%Goa%
Output
On executing the given query, the output is displayed as follows −
ID | COL1 |
---|---|
1 | Goa,Assam |
2 | Goa,Assam |
3 | Goa,Assam |
4 | Goa,Assam |
5 | Goa,Assam |
Example
In here, we are fetching the rows where the values are exactly ”Goa,Assam” and in the same order as listed in the ”COL1” definition −
SELECT * FROM test_table WHERE COL1 = ''Goa,Assam
Output
The output for the above query is as given below −
ID | COL1 |
---|---|
1 | Goa,Assam |
2 | Goa,Assam |
3 | Goa,Assam |
4 | Goa,Assam |
5 | Goa,Assam |
Updating the SET Values
In MySQL, you can update SET elements in various ways: by replacing elements, adding elements, or removing elements from the SET data. Here are examples of each method −
Replacing SET Data
In the following query, we replace the value in the 5th row with the number 11, which corresponds to Goa + Assam + Kerala (8 + 2 + 1) −
UPDATE test_table SET COL1 = 11 WHERE Id = 5;
Output
The query executes successfully and produces the following output −
Query OK, 1 row affected (0.01 sec) Rows matched: 1 Changed: 1 Warnings: 0
Verification
To verify the changes done in the test_table, use the following SELECT query −
SELECT * FROM test_table;
Following is the output produced −
ID | COL1 |
---|---|
1 | Goa,Assam |
2 | Goa,Assam |
3 | Goa,Assam |
4 | Goa,Assam |
5 | Goa,Assam,Kerala |
Adding Data to SET
You can add elements to an existing SET column using the CONCAT() function. In this example, we add “Kerala” to the value in the 3rd row −
UPDATE test_table SET COL1 = CONCAT(COL1, ",Kerala") WHERE Id = 3;
Output
The output for this query is as follows −
Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0
Verification
To verify the changes done in the test_table, use the following SELECT query −
SELECT * FROM test_table;
The result shows the updated value −
ID | COL1 |
---|---|
1 | Goa,Assam |
2 | Goa,Assam |
3 | Goa,Assam,Kerala |
4 | Goa,Assam |
5 | Goa,Assam,Kerala |
Removing Data from SET
To remove a specific SET element, you can use the & ~ bitwise operation. In this example, we remove the “Assam” element from the value in the 4th row −
UPDATE test_table SET COL1 = COL1 & ~2 WHERE ID = 4;
Output
The output for this query is as follows −
Query OK, 1 row affected (0.01 sec) Rows matched: 1 Changed: 1 Warnings: 0
Verification
Let us verify the test_table using the below query −
SELECT * FROM test_table;
Following is the table obtained −
ID | COL1 |
---|---|
1 | Goa,Assam |
2 | Goa,Assam |
3 | Goa,Assam,Kerala |
4 | Goa |
5 | Goa,Assam,Kerala |
SET Datatype Using a Client Program
We can also create column of the SET datatype using the client program.
Syntax
To create a column of SET datatype through a PHP program, we need to execute the “CREATE TABLE” statement using the mysqli function query() as follows −
$sql = "CREATE TABLE test_table (ID INT auto_increment primary key, COL1 set(''Goa'', ''Assam'', ''Delhi'', ''Kerala'') )"; $mysqli->query($sql);
To create a column of SET 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 test_table (ID INT auto_increment primary key, COL1 set(''Goa'', ''Assam'', ''Delhi'', ''Kerala'') )"; con.query(sql);
To create a column of SET datatype through a Java program, we need to execute the “CREATE TABLE” statement using the JDBC function execute() as follows −
String sql = "CREATE TABLE test_table (ID INT auto_increment primary key, COL1 set("Goa", "Assam", "Delhi", "Kerala"))"; statement.execute(sql);
To create a column of SET 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 test_table (ID INT AUTO_INCREMENT PRIMARY KEY, COL1 SET(''Goa'', ''Assam'', ''Delhi'', ''Kerala''))'' cursorObj.execute(sql)
Example
Following are the programs −
$dbhost = ''localhost $dbuser = ''root $dbpass = ''password $dbname = ''TUTORIALS $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($mysqli->connect_errno) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
''); $sql = ''Create table test_table (ID INT auto_increment primary key, COL1 set("Goa", "Assam", "Delhi", "Kerala") ) $result = $mysqli->query($sql); if ($result) { printf("Table created successfully...!n"); } // insert data into created table $q ="INSERT INTO test_table (COL1) VALUES (''Goa,Assam''), (''Assam,Goa''), (''Goa,Assam,Goa''), (''Goa,Assam,Assam''), (''Assam,Goa,Assam'')"; if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!n"); } //now display the table records $s = "SELECT * FROM test_table"; if ($r = $mysqli->query($s)) { printf("Table Records: n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Col_1: %s", $row["ID"], $row["COL1"]); printf("n"); } } else { printf(''Failed''); } $mysqli->close();
Output
The output obtained is as follows −
Table created successfully...! Data inserted successfully...! Table Records: ID: 1, Col_1: Goa,Assam ID: 2, Col_1: Goa,Assam ID: 3, Col_1: Goa,Assam ID: 4, Col_1: Goa,Assam ID: 5, Col_1: Goa,Assam
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 test_table table, that accepts one column of set type. sql = "Create table test_table (ID INT auto_increment primary key, COL1 set(''Goa'', ''Assam'', ''Delhi'', ''Kerala'') )"; con.query(sql); //insert data into created table sql = "INSERT INTO test_table (COL1) VALUES (''Goa,Assam''), (''Assam,Goa''), (''Goa,Assam,Goa''), (''Goa,Assam,Assam''), (''Assam,Goa,Assam'')"; con.query(sql); //select datatypes of salary sql = `SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ''test_table'' AND COLUMN_NAME = ''col1''`; con.query(sql, function (err, result) { if (err) throw err; console.log(result); }); });
Output
The output produced is as follows −
[ { DATA_TYPE: ''set'' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Set { 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...!"); //Set data types...!; String sql = "Create table test_table (ID INT auto_increment primary key, COL1 set("Goa", "Assam", "Delhi", "Kerala"))"; statement.execute(sql); System.out.println("column of a SET type created successfully...!"); ResultSet resultSet = statement.executeQuery("DESCRIBE test_table"); while (resultSet.next()){ System.out.println(resultSet.getString(1)+" "+resultSet.getString(2)); } connection.close(); } catch (Exception e) { System.out.println(e); } } }
Output
The output obtained is as shown below −
Connected successfully...! column of a SET type created successfully...! ID int COL1 set(''Goa'',''Assam'',''Delhi'',''Kerala'')
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 Set column sql = '''''' CREATE TABLE test_table ( ID INT AUTO_INCREMENT PRIMARY KEY, COL1 SET(''Goa'', ''Assam'', ''Delhi'', ''Kerala'') ) '''''' cursorObj.execute(sql) print("The table is created successfully!") # Data to be inserted data_to_insert = [ (''Goa,Assam'',), (''Assam,Goa'',), (''Goa,Assam,Goa'',), (''Goa,Assam,Assam'',), (''Assam,Goa,Assam'',) ] # Insert data into the created table insert_query = "INSERT INTO test_table (COL1) VALUES (%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 test_table" cursorObj.execute(select_query) result = cursorObj.fetchall() print("Test 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. Test Table Data: (1, {''Assam'', ''Goa''}) (2, {''Assam'', ''Goa''}) (3, {''Assam'', ''Goa''}) (4, {''Assam'', ''Goa''}) (5, {''Assam'', ''Goa''})
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