可以在命令行方式下使用 mysql 命令建立 MySQL數(shù)據(jù)庫。
下面這個例子顯示如何采用命令行方式連接 MySQL 服務(wù)器:
[root@host]# mysql -u root -p
Enter password:******
上述命令將顯示 mysql> 命令提示符。在該命令提示符后面,可以執(zhí)行任何 SQL 命令。下面就是上述命令的顯示結(jié)果:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2854760 to server version: 5.0.9
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
在上面這個例子中,使用 root 作為用戶(你也可以使用其他用戶)。任何用戶都能執(zhí)行 root 用戶所能執(zhí)行的全部 SQL 操作。
無論何時,只要在 mysql> 提示符下輸入 exit,就能隨時中斷與 MySQL 的連接。
mysql> exit
Bye
通過 PHP 的 mysql_connect() 函數(shù),可以開啟數(shù)據(jù)庫連接。該函數(shù)有5個參數(shù)。當成功連接后,該函數(shù)返回一個 MySQL 連接標識;如連接失敗,則返回FALSE。
connection mysql_connect(server,user,passwd,new_link,client_flag);
| 參數(shù) | 說明 |
|---|---|
server |
可選參數(shù)。運行數(shù)據(jù)庫服務(wù)器的主機名。如未指定,則默認值 localhost:3036。 |
user |
可選參數(shù)。訪問數(shù)據(jù)庫的用戶名。如未指定,則默認值為擁有服務(wù)器進程的用戶名稱。 |
passwd |
可選參數(shù)。用戶訪問數(shù)據(jù)庫所用密碼。如未指定,則默認沒有密碼。 |
new_link |
可選參數(shù)。如果利用同樣的參數(shù)第二次調(diào)用mysql_connect(),則不會建立新的連接,而是返回已打開連接的標識。 |
client_flags |
可選參數(shù)。是由下列常量組合而成: |
通過 PHP 的 mysql_close() 函數(shù),隨時可以中斷與 MySQL 數(shù)據(jù)庫的連接。該函數(shù)只有一個參數(shù),是一個由 mysql_connect()函數(shù)所返回的連接。
bool mysql_close ( resource $link_identifier );
如果某個資源未被指定,則最后打開的數(shù)據(jù)庫就會被關(guān)閉。如果成功中斷連接,該函數(shù)返回 true,否則返回 false。
下面通過一個具體的范例來實際了解如何連接 MySQL 服務(wù)器。
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
</body>
</html>