MySQLi - 資料庫資訊



獲取和使用MySQL元資料

您可能需要從MySQL獲取三種類型的資訊。

  • 查詢結果資訊 − 這包括任何SELECT、UPDATE或DELETE語句影響的記錄數量。

  • 關於表和資料庫的資訊 − 這包括與表和資料庫結構相關的資訊。

  • 關於MySQL伺服器的資訊 − 這包括資料庫伺服器的狀態、版本號等。

在MySQL提示符下很容易獲取所有這些資訊,但在使用PERL或PHP API時,我們需要顯式呼叫各種API來獲取所有這些資訊。

獲取查詢影響的行數

現在讓我們看看如何獲取這些資訊。

PERL示例

在DBI指令碼中,受影響的行數由do( )execute( )命令返回,具體取決於您如何執行查詢。

# Method 1
# execute $query using do( )
my $count = $dbh→do ($query);
# report 0 rows if an error occurred
printf "%d rows were affected\n", (defined ($count) ? $count : 0);

# Method 2
# execute query using prepare( ) plus execute( )
my $sth = $dbh→prepare ($query);
my $count = $sth→execute ( );
printf "%d rows were affected\n", (defined ($count) ? $count : 0);

PHP示例

在PHP中,呼叫mysql_affected_rows( )函式來找出查詢更改了多少行。

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

列出表和資料庫

列出資料庫伺服器上所有可用資料庫和表非常容易。如果您沒有足夠的許可權,您的結果可能為null

除了以下程式碼塊中顯示的方法外,您還可以使用SHOW TABLESSHOW DATABASES查詢來獲取PHP或PERL中表或資料庫的列表。

PERL示例

# Get all the tables available in current database.
my @tables = $dbh→tables ( );

foreach $table (@tables ){
   print "Table Name $table\n";
}

PHP示例

嘗試以下示例以獲取資料庫資訊:

複製並貼上以下示例作為mysql_example.php:

<html>
   <head>
      <title>Getting MySQL Database Info</title>
   </head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $dbname = 'TUTORIALS';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
         $tutorial_count = null;
         
         if($mysqli→connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli→connect_error);
            exit();
         }
         printf('Connected successfully.<br />');
		 
         if ($result = mysqli_query($mysqli, "SELECT DATABASE()")) {
            $row = mysqli_fetch_row($result);
            printf("Default database is %s<br />", $row[0]);
            mysqli_free_result($result);
         }
         $mysqli→close();
      ?>
   </body>
</html>

輸出

訪問部署在Apache Web伺服器上的mysql_example.php並驗證輸出。

Connected successfully.
Default database is tutorials

獲取伺服器元資料

MySQL中有一些重要的命令,可以在MySQL提示符下執行,也可以使用PHP之類的指令碼執行,以獲取有關資料庫伺服器的各種重要資訊。

序號 命令和描述
1

SELECT VERSION( )

伺服器版本字串

2

SELECT DATABASE( )

當前資料庫名稱(如果沒有則為空)

3

SELECT USER( )

當前使用者名稱

4

SHOW STATUS

伺服器狀態指示器

5

SHOW VARIABLES

伺服器配置變數

廣告
© . All rights reserved.