Your cart is currently empty!
Author: alien
-
Khóa học miễn phí MySQL – Repair Tables nhận dự án làm có lương
MySQL – Repair Tables
Table of content
MySQL Repair Table Statement
There can be scenarios where tables in databases can become corrupted due to various reasons such as hardware failures, software bugs, or unexpected server crashes. When this situation happens, we cannot be able to access or manipulate the data in those tables because of data inconsistencies or errors.
In such situations, to repair those currupted tables, we use the MySQL REPAIR TABLE statement. This statement works for only certain engines such as MyISAM, etc.
Syntax
Following is the syntax of MySQL REPAIR TABLE Statement −
REPAIR [NO_WRITE_TO_BINLOG | LOCAL] TABLE tbl_name [, tbl_name] ... [QUICK] [EXTENDED] [USE_FRM]
Example
Let us start by creating a table named CUSTOMERS using the following query −
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) );
Here, we are inserting 7 records into the above created table using the below INSERT statement −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 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 );
Assume the above created table is corrupted and we are using the REPAIR TABLE statement to repair it.
REPAIR TABLE CUSTOMERS;
The above query displays an error as: “The storage engine for the table doesn”t support repair” because the REPAIR TABLE statement won”t work with the default InnoDB engine.
Table Op Msg_type Msg_text tutorials.customers repair note The storage engine for the table doesn”t support repair To repair the table, We need to change the table”s engine to MyISAM because it supports the REPAIR TABLE statement.
ALTER TABLE CUSTOMERS ENGINE = MyISAM;
Now, to repair the CUSTOMERS table, execute the following query −
REPAIR TABLE CUSTOMERS;
Output
We can see in the output below, it says OK which indicates that the table CUSTOMERS is in good condition, and there are no issues or corruption.
Table Op Msg_type Msg_text tutorials.customers repair status OK Repairing multiple tables
In MySQL, we can also repair multiple tables and get the results using the REPAIR TABLE Statement. To do this, we just need to list the names of the tables we want to repair, separating them with commas.
Example
Let us create three different tables with the names Test1, Test2, and Test3 using the following CREATE TABLE statements −
CREATE TABLE Test1(ID INT, Name VARCHAR(255)); CREATE TABLE Test2(ID INT, Name VARCHAR(255)); CREATE TABLE Test3(ID INT, Name VARCHAR(255));
Assume the above three tables are corrupted. Change the engine of these tables to MyISAM to repair them with REPAIR TABLE statement −
ALTER TABLE Test1 ENGINE = MyISAM; ALTER TABLE Test2 ENGINE = MyISAM; ALTER TABLE Test3 ENGINE = MyISAM;
Now, to repair these tables, execute the following query −
REPAIR TABLE Test1, Test2, Test3;
As we can see in the output below, all three tables are in good condition, and there are no issues or corruption.
Table Op Msg_type Msg_text tutorials.test1 repair status OK tutorials.test2 repair status OK tutorials.test3 repair status OK Repair Table Options
We have various optional clauses to use with REPAIR TABLE such as QUICK, EXTENDED, and, USE_FRM clause. Let us discuss them one by one with suitable examples.
QUICK Clause
The QUICK clause is the is the default and it is most commonly used with REPAIR TABLE. If you specify the QUICK clause, MySQL will repair the table without re-creating it. −
ExampleIn the following example, we are using the QUICK clause with the REPAIR TABLE statement to repair the CUSTOMERS table.
REPAIR TABLE CUSTOMERS QUICK;
OutputExecuting the query above will produce the following output −
Table Op Msg_type Msg_text tutorials.customers repair status OK EXTENDED Clause
If we specify the EXTENDED clause, MySQL not only repairs the table but also rebuilds the index and optimizes the table structure.
Note: The EXTENDED clause is a more time-consuming compared to QUICK clause.
ExampleIn the following example, we are using the EXTENDED clause with the REPAIR TABLE statement to repair the CUSTOMERS table.
REPAIR TABLE CUSTOMERS EXTENDED;
OutputExecuting the query above will produce the following output −
Table Op Msg_type Msg_text tutorials.customers repair status OK USE_FRM clause
We can use the USE_FRM clause, in case the MYI index file is missing. If you provide this clause the .NYI file will be recreated using information from the data dictionary −
ExampleHere, we are using the USE_FRM clause with the REPAIR TABLE statement to repair the CUSTOMERS table.
REPAIR TABLE CUSTOMERS USE_FRM;
OutputExecuting the query above will produce the following output −
Table Op Msg_type Msg_text tutorials.CUSTOMERS repair warning Number of rows changed from 0 to 7 tutorials.customers repair status OK Repairing table Using a Client Program
Besides repairing a table in a MySQL database with a MySQL query, we can also use a client program to perform the REPAIR TABLE operation.
Syntax
Following are the syntaxes to repair a table in various programming languages −
To repair a table in a MySQL Database through a PHP program, we need to execute the Repair Table statement using the mysqli function query() as −
$sql="Repair TABLE table_names"; $mysqli->query($sql);
To repair a table in a MySQL Database through a Node.js program, we need to execute the Repair Table statement using the query() function of the mysql2 library as −
sql=" REPAIR [NO_WRITE_TO_BINLOG | LOCAL] TABLE tbl_name [, tbl_name] ... [QUICK] [EXTENDED] [USE_FRM]"; con.query(sql);
To repair a table in a MySQL database through a Java program, we need to execute the Repair Table statement using the JDBC function executeUpdate() as −
String sql="Repair TABLE table_names"; statement.executeUpdate(sql);
To repair a table in a MySQL database through a Python program we need to execute the Repair Table statement using the execute() function of the MySQL Connector/Python as −
sql="REPAIR TABLE table_name"; 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 = " REPAIR TABLE SalesSummary "; if ($mysqli->query($sql)) { printf(" Table repair successfully.
"); } if ($mysqli->errno) { printf("table could not be repaired .
", $mysqli->error); } $mysqli->close();Output
The output obtained is as follows −
Table repair successfully.
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("--------------------------"); sql = "Create Database TUTORIALS" con.query(sql); sql = "USE TUTORIALS" con.query(sql); sql = "CREATE TABLE sales(ID INT, ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255));" con.query(sql); sql = "insert into sales values(1, ''Key-Board'', ''Raja'', DATE(''2019-09-01''), TIME(''11:00:00''), 7000, ''Hyderabad''),(2, ''Earphones'', ''Roja'', DATE(''2019-05-01''), TIME(''11:00:00''), 2000, ''Vishakhapatnam''),(3, ''Mouse'', ''Puja'', DATE(''2019-03-01''), TIME(''10:59:59''), 3000, ''Vijayawada''),(4, ''Mobile'', ''Vanaja'', DATE(''2019-03-01''), TIME(''10:10:52''), 9000, ''Chennai''),(5, ''Headset'', ''Jalaja'', DATE(''2019-04-06''), TIME(''11:08:59''), 6000, ''Goa'');" con.query(sql); sql = "ALTER TABLE Sales ENGINE = MyISAM;" con.query(sql); sql = "REPAIR TABLE Sales;" con.query(sql, function(err, result){ if (err) throw err console.log(result); }); });
Output
The output produced is as follows −
Connected! -------------------------- [ { Table: ''tutorials.sales'', Op: ''repair'', Msg_type: ''status'', Msg_text: ''OK'' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class RepairTable{ 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...!"); //Repair tables...! String sql = "REPAIR TABLE customers"; statement.executeUpdate(sql); System.out.println("Table repaired successfully...!"); connection.close(); } catch(Exception e){ System.out.println(e); } } }
Output
The output obtained is as shown below −
Connected successfully...! Table repaired successfully...!
import mysql.connector #establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) table_name = ''tutorials_tbl_temp'' #Creating a cursor object cursorObj = connection.cursor() repair_table_query = f"REPAIR TABLE {table_name}" cursorObj.execute(repair_table_query) print(f"Table ''{table_name}'' is repaired successfully.") # Fetch and consume any remaining results from the cursor # ensuring that there are no unread results before closing the cursor. for _ in cursorObj: pass cursorObj.close() connection.close()
Output
Following is the output of the above code −
Table ''tutorials_tbl_temp'' is repaired successfully.
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc
Khóa học miễn phí MySQL – Temporary Tables nhận dự án làm có lương
MySQL – Temporary Tables
What are Temporary Tables?
The Temporary Tables are the tables that are created in a database to store data temporarily. These tables will be automatically deleted once the current client session is terminated or ends. In addition to that, these tables can be deleted explicitly if the users decide to drop them manually. You can perform various SQL operations on temporary tables, just like you would with permanent tables, including CREATE, UPDATE, DELETE, INSERT, JOIN, etc.
Temporary tables were introduced in MySQL version 3.23. If you”re using an older version of MySQL that”s older than 3.23, you won”t be able to use temporary tables, instead you can use the Heap Tables.
As stated earlier, temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQL database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table.
Creating Temporary Tables in MySQL
Creating a temporary table in MySQL is very similar to creating a regular database table. But, instead of using CREATE TABLE, we use CREATE TEMPORARY TABLE statement.
Syntax
Following is the syntax to create a temporary table in MySQL −
CREATE TEMPORARY TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) );
Example
First of all, let us create a temporary table named CUSTOMERS using the below query −
CREATE TEMPORARY 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) );
Similar to normal tables, we can insert records into a temporary table using the INSERT statement. Here, we are inserting three records into the above created temporary table −
INSERT INTO CUSTOMERS VALUES (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ), (2, ''Khilan'', 25, ''Delhi'', 1500.00 ), (3, ''kaushik'', 23, ''Kota'', 2000.00 );
Execute the following query to display all the records of the temporary table CUSTOMERS.
SELECT * FROM CUSTOMERS;
Following are the records of CUSTOMERS table −
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
2 | Khilan | 25 | Delhi | 1500.00 |
3 | Kaushik | 23 | Kota | 2000.00 |
When we issue a SHOW TABLES command, our temporary table won”t be displayed in the list of tables. To verify if the temporary table exists, we need to use the SELECT statement to retrieve its data. Temporary tables will be deleted when we ends our session, so if we log out of MySQL and then try to issue the SELECT command, we won”t find the temporary table in the database.
Dropping Temporary Tables in MySQL
Though MySQL automatically removes temporary tables when your database connection ends, we can still delete them ourselves by using the DROP TEMPORARY TABLE command if we want to.
Syntax
Following is the syntax for dropping a temporary table in MySQL −
DROP TEMPORARY TABLE table_name;
Example
In the following query, we are dropping the temporary table CUSTOMERS that was created in the previous example −
DROP TEMPORARY TABLE CUSTOMERS;
Output
Executing the query above will produce the following output −
Query OK, 0 rows affected (0.00 sec)
Verification
Now, let us verify the temporary table CUSTOMERS by retrieving it”s records using the following query −
SELECT * FROM CUSTOMERS;
Since we removed the the temporary table CUSTOMERS, it will generate an error saying the table does not exist.
ERROR 1146: Table ''TUTORIALS.CUSTOMERS'' doesn''t exist
Creating Temporary table Using a Client Program
In addition to create a temporary table in MySQL Database using the MySQL query, we can also perform the “TEMPORARY TABLE” operation on a table using a client program.
Syntax
Following are the syntaxes to create a temporary table into MySQL Database in various programming languages −
To create a temporary table into MySQL database through a PHP program, we need to execute the Create Temporary Table statement using the mysqli function query() as −
$sql="CREATE temporary Table table_name(column_name, column_type, ...)"; $mysqli->query($sql);
To create a temporary table into MySQL database through a Node.js program, we need to execute the Create Temporary Table statement using the query() function of the mysql2 library as −
sql="CREATE temporary Table table_name(column_name, column_type, ...)"; con.query(sql);
To create a temporary table into MySQL database through a Java program, we need to execute the Create Temporary Table statement using the JDBC function executeUpdate() as −
String sql="CREATE temporary Table table_name(column_name, column_type, ...)"; statement.executeQuery(sql);
To create a temporary table into MySQL database through a Python program, we need to execute the Create Temporary Table statement using the execute() function of the MySQL Connector/Python as −
sql="CREATE temporary Table table_name(column_name, column_type, ...)"; 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 TEMPORARY TABLE SalesSummary (" . " product_name VARCHAR(50) NOT NULL, " . " total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00, " . " avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00, " . " total_units_sold INT UNSIGNED NOT NULL DEFAULT 0 )"; if ($mysqli->query($sql)) { printf("temporary table created successfully.
"); } if ($mysqli->errno) { printf("temporary table could not be created: %s
", $mysqli->error); } $mysqli->close();
Output
The output obtained is as follows −
temporary table created successfully.
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("--------------------------"); //Creating a Database sql = "CREATE DATABASE testdb" con.query(sql); //Selecting a Database sql = "USE testdb" con.query(sql); //Creating table sql = "CREATE TEMPORARY TABLE SalesSummary (product_name VARCHAR(50) NOT NULL, total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00, avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00, total_units_sold INT UNSIGNED NOT NULL DEFAULT 0);" con.query(sql); sql = "INSERT INTO SalesSummary(product_name, total_sales, avg_unit_price, total_units_sold)VALUES(''cucumber'', 100.25, 90, 2);" con.query(sql); sql = "SELECT * FROM SalesSummary;" con.query(sql, function(err, result){ if (err) throw err console.log("**SalesSummary Table:**") console.log(result); }); });
Output
The output produced is as follows −
Connected! -------------------------- **SalesSummary Table:** [ { product_name: ''cucumber'', total_sales: ''100.25'', avg_unit_price: ''90.00'', total_units_sold: 2 } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class TemporaryTable { 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...!"); //Create temporary table...! String sql = "CREATE TEMPORARY TABLE SalesSummary (product_name VARCHAR(50) NOT NULL, total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00, avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00, total_units_sold INT UNSIGNED NOT NULL DEFAULT 0 )"; statement.executeUpdate(sql); System.out.println("Temporary table created successfully...!"); ResultSet resultSet = statement.executeQuery("DESCRIBE SalesSummary"); while(resultSet.next()) { System.out.print(resultSet.getNString(1)); System.out.println(); } connection.close(); } catch(Exception e){ System.out.println(e); } } }
Output
The output obtained is as shown below −
Connected successfully...! Temporary table created successfully...! product_name total_sales avg_unit_price total_units_sold
import mysql.connector #establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) table_name = ''tutorials_tbl_temp'' #Creating a cursor object cursorObj = connection.cursor() create_table_query = f"CREATE TEMPORARY TABLE {table_name} (NAME VARCHAR(50), ID INT)" cursorObj.execute(create_table_query) print(f"Temporary table ''{table_name}'' is created successfully.") cursorObj.close() connection.close()
Output
Following is the output of the above code −
Temporary table ''tutorials_tbl_temp'' is created successfully.
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc