Your cart is currently empty!
Category: mysql
-
Khóa học miễn phí MySQL – Show Columns nhận dự án làm có lương
MySQL – Show Columns
Table of content
MySQL Show Columns Statement
To retrieve entire information of a table, we use DESCRIBE, DESC or SHOW COLUMNS statements.
All of these statements of MySQL can be used to retrieve/display the description of all the columns of a table, as they all retrieve the same result-sets.
Obtaining column information can be useful in several situations like inserting values into a table (based on the column datatype), updating or dropping a column, or to just simply know a table”s structure.
In this chapter, let us understand how to use SHOW COLUMNS statement in detail.
Syntax
Following is the syntax of the MySQL SHOW COLUMNS Statement −
SHOW [EXTENDED] [FULL] {COLUMNS | FIELDS} {FROM | IN} tbl_name [{FROM | IN} db_name] [LIKE ''pattern'' | WHERE expr]
Example
Let us start with creating a database named TUTORIALS using the below query −
CREATE DATABASE TUTORIALS;
Execute the following statement to change into TUTORIALS database −
USE TUTORIALS;
In the following query, we are creating a table named CUSTOMERS using the following CREATE TABLE statement −
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, we are using the SHOW COLUMNS statement to retrieve the information about columns of the CUSTOMERS table −
SHOW COLUMNS FROM CUSTOMERS;
Output
Following is the information of columns in CUSTOMERS table −
Field Type Null Key Default Extra ID int NO PRI NULL auto_increment NAME varchar(20) NO NULL AGE int NO NULL ADDRESS char(25) YES NULL SALARY decimal(18,2) YES NULL Example
We can also use the IN clause instead of FROM as shown in the query below −
SHOW COLUMNS IN CUSTOMERS;
Output
As we can obeserve the output, it is exactly the same as the previous output.
Field Type Null Key Default Extra ID int NO PRI NULL auto_increment NAME varchar(20) NO NULL AGE int NO NULL ADDRESS char(25) YES NULL SALARY decimal(18,2) YES NULL Example
We can specify the name of the database along with the table name as shown in the query below −
SHOW COLUMNS IN CUSTOMERS FROM TUTORIALS;
Output
Following is the information of columns in CUSTOMERS table that is present in TUTORIALS database.
Field Type Null Key Default Extra ID int NO PRI NULL auto_increment NAME varchar(20) NO NULL AGE int NO NULL ADDRESS char(25) YES NULL SALARY decimal(18,2) YES NULL Example
We can replace the COLUMNS clause with FIELDS and get the same results −
SHOW FIELDS IN CUSTOMERS;
Output
As we see the output, we got the same results as COLUMNS clause.
Field Type Null Key Default Extra ID int NO PRI NULL auto_increment NAME varchar(20) NO NULL AGE int NO NULL ADDRESS char(25) YES NULL SALARY decimal(18,2) YES NULL The LIKE clause
In MySQL, using the LIKE clause, you can specify a pattern to retrieve info about specific columns.
Example
Following query retrieves the column names starting with the letter “P” from CUSTOMERS table.
SHOW COLUMNS FROM CUSTOMERS LIKE ''N%
Output
Executing the query above will produce the following output −
Field Type Null Key Default Extra NAME varchar(20) NO NULL The WHERE clause
We can use the MySQL WHERE clause of the SHOW COLUMNS statements to retrieve information about the columns which match the specified condition.
Example
In the following example, we are using the WHERE clause to retrieve the columns where there type is int.
SHOW COLUMNS FROM CUSTOMERS WHERE Type= ''int
Output
Executing the query above will produce the following output −
Field Type Null Key Default Extra ID int NO PRI NULL auto_increment AGE int NO NULL The FULL clause
Usually, the information provided by the SHOW COLUMNS statements contains field type, can be null or not, key, default values and some extra details. If you use the full clause details like collation, privileges and comments will be added.
Example
In the following example, we are using the FULL clause with SHOW COLUMNS to retrieve extra details of the CUSTOMERS table −
SHOW FULL COLUMNS IN CUSTOMERS FROM tutorials;
Executing the query above will produce the following output −
Field Type Collation Null Key Default ID int NULL NO PRI NULL NAME varchar(20) utf8mb4 0900 ai ci NO NULL AGE int NULL NO NULL ADDRESS char(25) utf8mb4 0900 ai ci YES NULL SALARY decimal(18,2) NULL YES NULL Showing Columns of a table Using a Client Program
Besides showing the columns of a table in a MySQL database with a MySQL query, we can also use a client program to perform the SHOW COLUMNS operation.
Syntax
Following are the syntaxes to show columns of a MySQL table in various programming languages −
To show columns of a MySQL table through a PHP program, we need to execute the Show Columns statement using the mysqli function query() as −
$sql="Show Table_name"; $mysqli->query($sql);
To show columns of a MySQL table through a Node.js program, we need to execute the Show statement using the query() function of the mysql2 library as −
sql="SHOW COLUMNS FROM table_name"; con.query(sql);
To show columns of a MySQL table through a Java program, we need to execute the Show statement using the JDBC function executeUpdate() as −
String sql="SHOW COLUMNS FROM table_name FROM database"; statement.executeQuery(sql);
To show columns of a MySQL table through a Python program, we need to execute the Show statement using the execute() function of the MySQL Connector/Python as −
sql="SHOW COLUMNS FROM table_name FROM database"; 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.
''); //column can be shown by the following queries // $sql = "SHOW COLUMNS FROM tut_tbl"; $sql = "SHOW COLUMNS FROM sales FROM tutorials"; if ($show_clmn = $mysqli->query($sql)) { printf("show column executed successfully!.
"); while ($col = mysqli_fetch_array($show_clmn)) { echo "n{$col[''Field'']}"; } } if ($mysqli->errno) { printf("Columns could be shown by the above query!.
", $mysqli->error); } $mysqli->close();Output
The output obtained is as follows −
show column executed successfully!. ID ProductName CustomerName DispatchDate DeliveryTime Price Location
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 demo" con.query(sql); sql = "USE demo" 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); //Displaying all the columns from the Sales table sql = "SHOW COLUMNS FROM sales;" con.query(sql, function(err, result){ if (err) throw err console.log(result); }); });
Output
The output produced is as follows −
Connected! -------------------------- [ { Field: ''ID'', Type: ''int'', Null: ''YES'', Key: '''', Default: null, Extra: '''' }, { Field: ''ProductName'', Type: ''varchar(255)'', Null: ''YES'', Key: '''', Default: null, Extra: '''' }, { Field: ''CustomerName'', Type: ''varchar(255)'', Null: ''YES'', Key: '''', Default: null, Extra: '''' }, { Field: ''DispatchDate'', Type: ''date'', Null: ''YES'', Key: '''', Default: null, Extra: '''' }, { Field: ''DeliveryTime'', Type: ''time'', Null: ''YES'', Key: '''', Default: null, Extra: '''' }, { Field: ''Price'', Type: ''int'', Null: ''YES'', Key: '''', Default: null, Extra: '''' }, { Field: ''Location'', Type: ''varchar(255)'', Null: ''YES'', Key: '''', Default: null, Extra: '''' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ShowColumn { 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...!"); //show column String sql = "SHOW COLUMNS FROM tutorials_tbl FROM TUTORIALS"; ResultSet resultSet = statement.executeQuery(sql); System.out.println("Column has been shown successfully...!"); while (resultSet.next()) { System.out.print(resultSet.getString(1)); System.out.println(); } connection.close(); } catch (Exception e) { System.out.println(e); } } }
Output
The output obtained is as shown below −
Connected successfully...! Column has been shown successfully...! ID tutorial_title tutorial_author
import mysql.connector #establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) table_name = ''NOVELS'' #Creating a cursor object cursorObj = connection.cursor() show_columns_query = f"SHOW COLUMNS FROM {table_name}" cursorObj.execute(show_columns_query) columns_info = cursorObj.fetchall() print(f"Columns of table ''{table_name}'':") for column in columns_info: print(f"Column Name: {column[0]}, Type: {column[1]}, Null: {column[2]}, Key: {column[3]}, Default: {column[4]}") cursorObj.close() connection.close()
Output
Following is the output of the above code −
Columns of table ''tutorials_tbl'': Column Name: tutorial_id, Type: b''int'', Null: NO, Key: PRI, Default: None Column Name: tutorial_title, Type: b''varchar(100)'', Null: NO, Key: , Default: None Column Name: tutorial_author, Type: b''varchar(40)'', Null: NO, Key: , Default: None Column Name: submission_date, Type: b''date'', Null: YES, Key:, Default: None Column Name: tutorial_name, Type: b''varchar(20)'', Null: YES, Key: , Default: 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 – Lock User Account nhận dự án làm có lương
MySQL – Lock User Account
Account Locking in MySQL is introduced to increase security of the database by preventing unauthorized transactions or suspicious activities.
In many cases, the MySQL user accounts require to be locked for various reasons. For instance, to wait while completing the authorization of an account, or if the account has been inactive for a very long time, etc. In such cases, locking accounts will improve the efficiency of the MySQL server.
MySQL Lock User Account
To check whether an account is locked or not, MySQL provides the ”account_locked” attribute in the ”mysql.user” table that will hold either ”Y” or ”N” values respectively. A value of ”Y” indicates that the account is locked, while ”N” indicates that it is not locked.
Locking New Accounts
MySQL provides ACCOUNT LOCK clause to lock the accounts. Using this clause with CREATE USER and ALTER USER statements will either create a new already locked user or lock the existing user respectively.
Syntax
Following is the syntax of CREATE USER… ACCOUNT LOCK statement −
CREATE USER username@hostname IDENTIFIED BY ''new_password'' ACCOUNT LOCK;
Example
In the following query, we are creating a new already-locked user account in MySQL using the CREATE USER statement −
CREATE USER test@localhost IDENTIFIED BY ''asdfgh'' ACCOUNT LOCK;
Output
Following is the output of the above code −
Query OK, 0 rows affected (0.02 sec)
Verification
We can verify whether the account of the ”test” user is locked or not using the following SELECT statement −
SELECT User, Host, account_locked FROM mysql.user WHERE User = ''test
Output of the above code is as shown below −
User | Host | account_locked |
---|---|---|
test | localhost | Y |
Since the account is locked, you cannot access it unless it is unlocked again. Look at the example below −
C:WindowsSystem32> mysql -u test -p Enter password: ******
The result produced is as follows −
ERROR 3118 (HY000): Access denied for user ''test''@''localhost''. Account is locked.
Locking Existing Accounts
We can use the ALTER USER… ACCOUNT LOCK statement to lock existing accounts in MySQL. But you must make sure that the user is in the unlock state before executing the query.
Syntax
Following is the syntax of ALTER USER… ACCOUNT LOCK statement −
ALTER USER username@hostname ACCOUNT LOCK;
Example
In here, we are locking an existing user account in MySQL using the ALTER USER statement −
ALTER USER sample@localhost ACCOUNT LOCK;
Output
Output of the above code is as follows −
Query OK, 0 rows affected (0.00 sec)
Verification
We can verify whether the account of the ”sample” user is locked or not using the following SELECT statement −
SELECT User, Host, account_locked FROM mysql.user WHERE User = ''sample
The result obtained is as shown below −
User | Host | account_locked |
---|---|---|
sample | localhost | Y |
To verify that the account is locked, let us access it as shown in the query below −
C:WindowsSystem32> mysql -u sample -p Enter password: ******
We get the output as follows −
ERROR 3118 (HY000): Access denied for user ''sample''@''localhost''. Account is locked.
Locking User Account Using a Client Program
Now, in this section let us discuss how to lock a MySQL user using various client programs.
Syntax
Following are the syntaxes −
Following is the syntax to lock the MySQL user account using PHP −
$sql = "CREATE USER user_name IDENTIFIED BY ''password'' ACCOUNT LOCK"; Or, $sql = "ALTER USER user_name@localhost IDENTIFIED BY ''password'' ACCOUNT LOCK"; $mysqli->query($sql);
Following is the syntax to lock the MySQL user account using JavaScript −
sql= "CREATE USER username@hostname IDENTIFIED BY ''new_password'' ACCOUNT LOCK"; con.query(sql, function (err, result) { if (err) throw err; console.log(result); });
Following is the syntax to lock the MySQL user account using Java −
String sql = "ALTER USER USER_NAME@LOCALHOST IDENTIFIED BY ''password'' ACCOUNT LOCK"; Or, String sql = "CREATE USER USER_NAME IDENTIFIED BY ''password'' ACCOUNT LOCK"; statement.execute(sql);
Following is the syntax to lock the MySQL user account using Python −
sql = f"ALTER USER ''{username_to_lock}''@''localhost'' ACCOUNT LOCK"; cursorObj.execute(sql);
Example
Following are the programs to lock users in various programming languages −
$dbhost = ''localhost $dbuser = ''root $dbpass = ''password $mysqli = new mysqli($dbhost, $dbuser, $dbpass); if($mysqli->connect_errno ) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
''); $sql = "CREATE USER Sarika IDENTIFIED BY ''password'' ACCOUNT LOCK;"; if($mysqli->query($sql)){ printf("User has been locked successfully..!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();
Output
The output obtained is as follows −
User has been locked 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 USER test@localhost IDENTIFIED BY ''asdfgh'' ACCOUNT LOCK;" con.query(sql); sql = "SELECT User, Host, account_locked FROM mysql.user WHERE User = ''test"; con.query(sql, function(err, result){ if (err) throw err; console.log(result); }); });
Output
The output produced is as follows −
Connected! -------------------------- [ { User: ''test'', Host: ''localhost'', account_locked: ''Y'' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class LockUserAccount { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String user = "root"; String password = "password"; 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 = "ALTER USER Vivek@localhost IDENTIFIED BY ''password'' ACCOUNT LOCK"; st.execute(sql); System.out.println("User ''Vivek'' account locked successfully...!"); }catch(Exception e) { e.printStackTrace(); } } }
Output
The output obtained is as shown below −
User ''Vivek'' account locked successfully...!
import mysql.connector # creating the connection object connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'' ) username_to_lock = ''newUser'' # Create a cursor object for the connection cursorObj = connection.cursor() cursorObj.execute(f"ALTER USER ''{username_to_lock}''@''localhost'' ACCOUNT LOCK") print(f"User ''{username_to_lock}'' account is locked successfully.") cursorObj.close() connection.close()
Output
Following is the output of the above code −
User ''newUser'' account is locked 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