MySQL Metadata View and Instance Code

  • 2021-06-29 12:15:32
  • OfStack

You may want to know three kinds of information about MySQL:

Query Result Information: Number of records affected by SELECT, UPDATE, or DELETE statements. Information about databases and tables: Contains structural information about databases and tables. MySQL Server Information: Contains the current status of the database server, version number, etc.

From the command prompt of MySQL, we can easily get the above server information.However, if you use scripting languages such as Perl or PHP, you need to call specific interface functions to get them.Next we'll go into more detail.

Get the number of records affected by a query statement

PERL instance

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


#  Method  1
#  Use do( )  implement  $query 
my $count = $dbh->do ($query);
#  Output if an error occurs  0
printf "%d rows were affected\n", (defined ($count) ? $count : 0);

#  Method  2
#  Use prepare( )  and  execute( )  implement  $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 mysql_affected_The rows() function gets the number of records affected by a query statement.


 
$result_id = mysql_query ($query, $conn_id);
#  Return if query fails  
$count = ($result_id ? mysql_affected_rows ($conn_id) : 0);
print ("$count rows were affected\n");

List of databases and data tables

You can easily get a list of databases and tables from the MySQL server.If you do not have sufficient privileges, the result will be returned to null.

You can also use the SHOW TABLES or SHOW DATABASES statement to get a list of databases and datatables.

PERL instance


#  Gets all available tables in the current database. 
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);
?>
 

Get server metadata

The following command statements can be used at the MySQL command prompt or in scripts, such as the PHP script.

命令 描述
SELECT VERSION( ) 服务器版本信息
SELECT DATABASE( ) 当前数据库名 (或者返回空)
SELECT USER( ) 当前用户名
SHOW STATUS 服务器状态
SHOW VARIABLES 服务器配置变量

Thank you for reading, I hope to help you, thank you for your support on this site!


Related articles: