Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MySQL metadata


May 15, 2021 MySQL


Table of contents


MySQL metadata

You may want to know three things about MySQL:

  • Query result information: Select, UPDATE, or DELETE statements affect the number of records.
  • Information about databases and data tables: Contains structural information about databases and data tables.
  • MySQL server information: Contains the current state of the database server, version number, etc.

In mySQL's command prompts, we can easily obtain the above server information. B ut if you use scripting languages such as Perl or PHP, you need to call a specific interface function to get it. W e'll cover it in more detail next.


Gets the number of records affected by the query statement

PERL instance

In a DBI script, the number of records affected by the statement is returned through the function do () or execute ():

# 方法 1
# 使用do( ) 执行  $query 
my $count = $dbh->do ($query);
# 如果发生错误会输出 0
printf "%d rows were affected\n", (defined ($count) ? $count : 0);

# 方法 2
# 使用prepare( ) 及 execute( ) 执行  $query 
my $sth = $dbh->prepare ($query);
my $count = $sth->execute ( );
printf "%d rows were affected\n", (defined ($count) ? $count : 0);

PhP instance

In PHP, you can use the mysql_affected_rows ( ) function to get the number of records affected by query statements.

$result_id = mysql_query ($query, $conn_id);
# 如果查询失败返回 
$count = ($result_id ? mysql_affected_rows ($conn_id) : 0);
print ("$count rows were affected\n");

A list of databases and data tables

You can easily get a list of databases and data tables in the MySQL server. If you do not have sufficient permissions, the result will return null.

You can also use SHOW TABLES or SHOW DATABASES statements to get a list of databases and data tables.

PERL instance

# 获取当前数据库中所有可用的表。
my @tables = $dbh->tables ( );
foreach $table (@tables ){
   print "Table Name $table\n";
}

PhP instance

<?php
$con = mysql_connect("localhost", "userid", "password");
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

$db_list = mysql_list_dbs($con);

while ($db = mysql_fetch_object($db_list))
{
  echo $db->Database . "<br />";
}
mysql_close($con);
?>

Gets server metadata

The following command statements can be used in MySQL command prompts or in scripts, such as PHP scripts.

Command Describe
SELECT VERSION( ) Server version information
SELECT DATABASE( ) Current database name (or return empty)
SELECT USER( ) The current user name
SHOW STATUS The state of the server
SHOW VARIABLES The server configuration variable