mysql 指南

MySQL-快速指南 (MySQL - Quick Guide)

MySQL-简介 (MySQL - Introduction)

什么是数据库? (What is a Database?)

A database is a separate application that stores a collection of data. Each database has one or more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.

数据库是存储数据集合的独立应用程序。 每个数据库都有一个或多个不同的API,用于创建,访问,管理,搜索和复制其拥有的数据。

Other kinds of data stores can also be used, such as files on the file system or large hash tables in memory but data fetching and writing would not be so fast and easy with those type of systems.

也可以使用其他类型的数据存储,例如文件系统上的文件或内存中的大型哈希表,但是使用这些类型的系统,数据的获取和写入将不那么快捷,容易。

Nowadays, we use relational database management systems (RDBMS) to store and manage huge volume of data. This is called relational database because all the data is stored into different tables and relations are established using primary keys or other keys known as Foreign Keys.

如今,我们使用关系数据库管理系统(RDBMS)来存储和管理大量数据。 之所以称为关系数据库,是因为所有数据都存储在不同的表中,并且使用主键或称为外键的其他键来建立关系。

A Relational DataBase Management System (RDBMS) is a software that −

关系数据库管理系统(RDBMS)是一种软件,该软件-

  • Enables you to implement a database with tables, columns and indexes.

    使您能够使用表,列和索引来实现数据库。

  • Guarantees the Referential Integrity between rows of various tables.

    确保各种表的行之间的引用完整性。

  • Updates the indexes automatically.

    自动更新索引。

  • Interprets an SQL query and combines information from various tables.

    解释SQL查询并合并来自各个表的信息。

RDBMS术语 (RDBMS Terminology)

Before we proceed to explain the MySQL database system, let us revise a few definitions related to the database.

在继续解释MySQL数据库系统之前,让我们修改一些与数据库有关的定义。

  • Database − A database is a collection of tables, with related data.

    数据库 -数据库是具有相关数据的表的集合。

  • Table − A table is a matrix with data. A table in a database looks like a simple spreadsheet.

    表格 -表格是包含数据的矩阵。 数据库中的表看起来像一个简单的电子表格。

  • Column − One column (data element) contains data of one and the same kind, for example the column postcode.

    -一列(数据元素)包含一种相同类型的数据,例如列邮政编码。

  • Row − A row (= tuple, entry or record) is a group of related data, for example the data of one subscription.

    -行(=元组,条目或记录)是一组相关数据,例如一个订阅的数据。

  • Redundancy − Storing data twice, redundantly to make the system faster.

    冗余 -两次存储数据,以提高系统速度。

  • Primary Key − A primary key is unique. A key value can not occur twice in one table. With a key, you can only find one row.

    主键 -主键是唯一的。 一个表中的键值不能出现两次。 使用密钥,您只能找到一行。

  • Foreign Key − A foreign key is the linking pin between two tables.

    外键 -外键是两个表之间的链接销。

  • Compound Key − A compound key (composite key) is a key that consists of multiple columns, because one column is not sufficiently unique.

    复合键 -复合键(复合键)是由多列组成的键,因为一列不够唯一。

  • Index − An index in a database resembles an index at the back of a book.

    索引 -数据库中的索引类似于书后部的索引。

  • Referential Integrity − Referential Integrity makes sure that a foreign key value always points to an existing row.

    引用完整性 -引用完整性可确保外键值始终指向现有行。

MySQL数据库 (MySQL Database)

MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is becoming so popular because of many good reasons −

MySQL是一种快速,易于使用的RDBMS,可用于许多大小企业。 MySQL由瑞典公司MySQL AB开发,销售和支持。 由于许多原因,MySQL变得如此流行-

  • MySQL is released under an open-source license. So you have nothing to pay to use it.

    MySQL是在开源许可证下发布的。 因此,您无需付费即可使用它。

  • MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages.

    MySQL本身就是一个非常强大的程序。 它处理最昂贵和功能最强大的数据库程序包的大部分功能。

  • MySQL uses a standard form of the well-known SQL data language.

    MySQL使用众所周知SQL数据语言的标准形式。

  • MySQL works on many operating systems and with many languages including PHP, PERL, C, C++, JAVA, etc.

    MySQL可在许多操作系统上运行,并支持多种语言,包括PHP,PERL,C,C ++,JAVA等。

  • MySQL works very quickly and works well even with large data sets.

    MySQL可以非常快速地运行,并且即使对于大型数据集也可以很好地运行。

  • MySQL is very friendly to PHP, the most appreciated language for web development.

    MySQL对PHP非常友好,PHP是Web开发中最受欢迎的语言。

  • MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB).

    MySQL支持大型数据库,一个表中最多有5000万行或更多行。 表的默认文件大小限制为4GB,但您可以将其增加(如果操作系统可以处理),理论上可以达到800万兆字节(TB)。

  • MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL software to fit their own specific environments.

    MySQL是可定制的。 开源GPL许可证允许程序员修改MySQL软件以适合他们自己的特定环境。

在你开始之前 (Before You Begin)

Before you begin this tutorial, you should have a basic knowledge of the information covered in our PHP and HTML tutorials.

在开始本教程之前,您应该对我们PHP和HTML教程中所包含的信息有基本的了解。

This tutorial focuses heavily on using MySQL in a PHP environment. Many examples given in this tutorial will be useful for PHP Programmers.

本教程着重于在PHP环境中使用MySQL。 本教程中给出的许多示例对于PHP程序员都是有用的。

We recommend you check our PHP Tutorial for your reference.

我们建议您检查我们的PHP教程以供参考。

MySQL-安装 (MySQL - Installation)

All downloads for MySQL are located at MySQL Downloads. Pick the version number of MySQL Community Server which is required along with the platform you will be running it on.

MySQL的所有下载均位于MySQL下载中 。 选择所需的MySQL Community Server版本号以及将在其上运行的平台。

在Linux / UNIX上安装MySQL (Installing MySQL on Linux/UNIX)

The recommended way to install MySQL on a Linux system is via RPM. MySQL AB makes the following RPMs available for download on its website −

建议在Linux系统上安装MySQL的方法是通过RPM。 MySQL AB在其网站上提供了以下RPM可供下载-

  • MySQL − The MySQL database server manages the databases and tables, controls user access and processes the SQL queries.

    MySQL -MySQL数据库服务器管理数据库和表,控制用户访问并处理SQL查询。

  • MySQL-client − MySQL client programs, which make it possible to connect to and interact with the server.

    MySQL客户端 -MySQL客户端程序,可以连接到服务器并与服务器交互。

  • MySQL-devel − Libraries and header files that come in handy when compiling other programs that use MySQL.

    MySQL-devel-编译使用MySQL的其他程序时会派上用场的库和头文件。

  • MySQL-shared − Shared libraries for the MySQL client.

    MySQL共享 -MySQL客户端的共享库。

  • MySQL-bench − Benchmark and performance testing tools for the MySQL database server.

    MySQL-be​​nch -MySQL数据库服务器的基准测试和性能测试工具。

The MySQL RPMs listed here are all built on a SuSE Linux system, but they will usually work on other Linux variants with no difficulty.

此处列出MySQL RPM都是基于SuSE Linux系统构建的 ,但是它们通常可以毫不费力地在其他Linux变体上运行。

Now, you will need to adhere to the steps given below, to proceed with the installation −

现在,您将需要遵循以下步骤,继续进行安装-

  • Login to the system using the root user.

    使用root用户登录系统。

  • Switch to the directory containing the RPMs.

    切换到包含RPM的目录。

  • Install the MySQL database server by executing the following command. Remember to replace the filename in italics with the file name of your RPM.

    通过执行以下命令来安装MySQL数据库服务器。 请记住用RPM的文件名替换斜体文件名。


[root@host]# rpm -i MySQL-5.0.9-0.i386.rpm

The above command takes care of installing the MySQL server, creating a user of MySQL, creating necessary configuration and starting the MySQL server automatically.

上面的命令负责安装MySQL服务器,创建MySQL用户,创建必要的配置以及自动启动MySQL服务器。

You can find all the MySQL related binaries in /usr/bin and /usr/sbin. All the tables and databases will be created in the /var/lib/mysql directory.

您可以在/ usr / bin和/ usr / sbin中找到所有与MySQL相关的二进制文件。 所有的表和数据库都将在/ var / lib / mysql目录中创建。

The following code box has an optional but recommended step to install the remaining RPMs in the same manner −

以下代码框包含一个可选的但建议执行的步骤,以相同的方式安装其余的RPM-


[root@host]# rpm -i MySQL-client-5.0.9-0.i386.rpm
[root@host]# rpm -i MySQL-devel-5.0.9-0.i386.rpm
[root@host]# rpm -i MySQL-shared-5.0.9-0.i386.rpm
[root@host]# rpm -i MySQL-bench-5.0.9-0.i386.rpm

在Windows上安装MySQL (Installing MySQL on Windows)

The default installation on any version of Windows is now much easier than it used to be, as MySQL now comes neatly packaged with an installer. Simply download the installer package, unzip it anywhere and run the setup.exe file.

现在,在任何Windows版本上的默认安装都比以前容易得多,因为MySQL现在与安装程序打包在一起了。 只需下载安装程序包,将其解压缩到任何地方并运行setup.exe文件即可。

The default installer setup.exe will walk you through the trivial process and by default will install everything under C:\mysql.

默认的安装程序setup.exe将引导您完成整个过程,默认情况下,所有程序都将安装在C:\ mysql下。

Test the server by firing it up from the command prompt the first time. Go to the location of the mysqld server which is probably C:\mysql\bin, and type −

通过在第一次命令提示符下启动服务器来测试服务器。 转到可能是C:\ mysql \ bin的mysqld服务器的位置,然后键入-


mysqld.exe --console

NOTE − If you are on NT, then you will have to use mysqld-nt.exe instead of mysqld.exe

–如果在NT上,则必须使用mysqld-nt.exe而不是mysqld.exe

If all went well, you will see some messages about startup and InnoDB. If not, you may have a permissions issue. Make sure that the directory that holds your data is accessible to whatever user (probably MySQL) the database processes run under.

如果一切顺利,您将看到一些有关startup和InnoDB的消息。 否则,您可能会遇到权限问题。 确保数据库进程所在的任何用户(可能是MySQL)都可以访问保存数据的目录。

MySQL will not add itself to the start menu, and there is no particularly nice GUI way to stop the server either. Therefore, if you tend to start the server by double clicking the mysqld executable, you should remember to halt the process by hand by using mysqladmin, Task List, Task Manager, or other Windows-specific means.

MySQL不会将自己添加到开始菜单中,也没有特别好的GUI方法来停止服务器。 因此,如果您倾向于通过双击mysqld可执行文件来启动服务器,则应记住使用mysqladmin,任务列表,任务管理器或其他Windows专用方法手动停止该过程。

验证MySQL安装 (Verifying MySQL Installation)

After MySQL, has been successfully installed, the base tables have been initialized and the server has been started: you can verify that everything is working as it should be via some simple tests.

成功安装MySQL之后,已初始化基表并启动了服务器:您可以通过一些简单的测试来验证一切是否正常。

使用mysqladmin实用程序获取服务器状态 (Use the mysqladmin Utility to Obtain Server Status)

Use mysqladmin binary to check the server version. This binary would be available in /usr/bin on linux and in C:\mysql\bin on windows.

使用mysqladmin binary检查服务器版本。 该二进制文件将在Linux上的/ usr / bin和Windows上的C:\ mysql \ bin中可用。


[root@host]# mysqladmin --version

It will produce the following result on Linux. It may vary depending on your installation −

在Linux上将产生以下结果。 它可能会因您的安装而异-


mysqladmin  Ver 8.23 Distrib 5.0.9-0, for redhat-linux-gnu on i386

If you do not get such a message, then there may be some problem in your installation and you would need some help to fix it.

如果未收到此消息,则说明您的安装可能存在问题,您将需要一些帮助来修复它。

使用MySQL客户端执行简单SQL命令 (Execute simple SQL commands using the MySQL Client)

You can connect to your MySQL server through the MySQL client and by using the mysql command. At this moment, you do not need to give any password as by default it will be set as blank.

您可以通过MySQL客户端并使用mysql命令连接到MySQL服务器。 目前,您无需提供任何密码,因为默认情况下它将被设置为空白。

You can just use following command −

您可以只使用以下命令-


[root@host]# mysql

It should be rewarded with a mysql> prompt. Now, you are connected to the MySQL server and you can execute all the SQL commands at the mysql> prompt as follows −

应该用mysql>提示符来奖励它。 现在,您已连接到MySQL服务器,并且可以在mysql>提示符下执行所有SQL命令,如下所示-


mysql> SHOW DATABASES;
+----------+
| Database |
+----------+
|   mysql  |
|   test   |
+----------+
2 rows in set (0.13 sec)

安装后步骤 (Post-installation Steps)

MySQL ships with a blank password for the root MySQL user. As soon as you have successfully installed the database and the client, you need to set a root password as given in the following code block −

MySQL附带MySQL根用户的空白密码。 成功安装数据库和客户端后,您需要按照以下代码块中的设置设置root密码-


[root@host]# mysqladmin -u root password "new_password";

Now to make a connection to your MySQL server, you would have to use the following command −

现在要建立与MySQL服务器的连接,您将必须使用以下命令-


[root@host]# mysql -u root -p
Enter password:*******

UNIX users will also want to put your MySQL directory in your PATH, so you won't have to keep typing out the full path everytime you want to use the command-line client.

UNIX用户还将希望将MySQL目录放在PATH中,因此您不必每次都要使用命令行客户端时都输入完整路径。

For bash, it would be something like −

对于bash来说,它类似于-


export PATH = $PATH:/usr/bin:/usr/sbin

在启动时运行MySQL (Running MySQL at Boot Time)

If you want to run the MySQL server at boot time, then make sure you have the following entry in the /etc/rc.local file.

如果要在引导时运行MySQL服务器,请确保在/etc/rc.local文件中具有以下条目。


/etc/init.d/mysqld start

Also,you should have the mysqld binary in the /etc/init.d/ directory.

另外,您应该在/etc/init.d/目录中具有mysqld二进制文件。

MySQL-管理 (MySQL - Administration)

运行和关闭MySQL服务器 (Running and Shutting down MySQL Server)

First check if your MySQL server is running or not. You can use the following command to check it −

首先检查您MySQL服务器是否正在运行。 您可以使用以下命令进行检查-


ps -ef | grep mysqld

If your MySql is running, then you will see mysqld process listed out in your result. If server is not running, then you can start it by using the following command −

如果MySql正在运行,则结果中将列出mysqld进程。 如果服务器未运行,则可以使用以下命令启动它-


root@host# cd /usr/bin
./safe_mysqld &

Now, if you want to shut down an already running MySQL server, then you can do it by using the following command −

现在,如果您想关闭已经运行MySQL服务器,则可以使用以下命令进行操作-


root@host# cd /usr/bin
./mysqladmin -u root -p shutdown
Enter password: ******

设置一个MySQL用户帐户 (Setting Up a MySQL User Account)

For adding a new user to MySQL, you just need to add a new entry to the user table in the database mysql.

要将新用户添加到MySQL,只需在数据库mysqluser表中添加一个新条目。

The following program is an example of adding a new user guest with SELECT, INSERT and UPDATE privileges with the password guest123; the SQL query is −

以下程序是添加具有SELECT,INSERT和UPDATE特权且密码为guest123的新用户guest 虚拟机的示例; SQL查询是-


root@host# mysql -u root -p
Enter password:*******
mysql> use mysql;
Database changedmysql> INSERT INTO user (host, user, password, select_priv, insert_priv, update_priv) VALUES ('localhost', 'guest', PASSWORD('guest123'), 'Y', 'Y', 'Y');
Query OK, 1 row affected (0.20 sec)mysql> FLUSH PRIVILEGES;
Query OK, 1 row affected (0.01 sec)mysql> SELECT host, user, password FROM user WHERE user = 'guest';
+-----------+---------+------------------+
|    host   |   user  |     password     |
+-----------+---------+------------------+
| localhost |  guest  | 6f8c114b58f2ce9e |
+-----------+---------+------------------+
1 row in set (0.00 sec)

When adding a new user, remember to encrypt the new password using PASSWORD() function provided by MySQL. As you can see in the above example, the password mypass is encrypted to 6f8c114b58f2ce9e.

添加新用户时,请记住使用MySQL提供的PASSWORD()函数对新密码进行加密。 如上例所示,密码mypass已加密为6f8c114b58f2ce9e。

Notice the FLUSH PRIVILEGES statement. This tells the server to reload the grant tables. If you don't use it, then you won't be able to connect to MySQL using the new user account at least until the server is rebooted.

注意FLUSH PRIVILEGES语句。 这告诉服务器重新加载授权表。 如果不使用它,那么至少在重新启动服务器之前,您将无法使用新的用户帐户连接到MySQL。

You can also specify other privileges to a new user by setting the values of following columns in user table to 'Y' when executing the INSERT query or you can update them later using UPDATE query.

您还可以通过在执行INSERT查询时将用户表中以下列的值设置为'Y',来为新用户指定其他特权,或者您以后可以使用UPDATE查询来更新它们。

  • Select_privSelect_priv
  • Insert_privInsert_priv
  • Update_privUpdate_priv
  • Delete_privDelete_priv
  • Create_privCreate_priv
  • Drop_privDrop_priv
  • Reload_privReload_priv
  • Shutdown_privShutdown_priv
  • Process_privProcess_priv
  • File_privFile_priv
  • Grant_privGrant_priv
  • References_privReferences_priv
  • Index_privIndex_priv
  • Alter_privAlter_priv

Another way of adding user account is by using GRANT SQL command. The following example will add user zara with password zara123 for a particular database, which is named as TUTORIALS.

添加用户帐户的另一种方法是使用GRANT SQL命令。 以下示例将为密码为zara123的特定数据库添加用户zara ,该数据库名为TUTORIALS


root@host# mysql -u root -p password;
Enter password:*******
mysql> use mysql;
Database changedmysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP-> ON TUTORIALS.*-> TO 'zara'@'localhost'-> IDENTIFIED BY 'zara123';

This will also create an entry in the MySQL database table called as user.

这还将在MySQL数据库表中创建一个名为user的条目。

NOTE − MySQL does not terminate a command until you give a semi colon (;) at the end of the SQL command.

– MySQL不会终止命令,除非在SQL命令的末尾加上分号(;)。

/etc/my.cnf文件配置 (The /etc/my.cnf File Configuration)

In most of the cases, you should not touch this file. By default, it will have the following entries −

在大多数情况下,您不应触摸此文件。 默认情况下,它将具有以下条目-


[mysqld]
datadir = /var/lib/mysql
socket = /var/lib/mysql/mysql.sock[mysql.server]
user = mysql
basedir = /var/lib[safe_mysqld]
err-log = /var/log/mysqld.log
pid-file = /var/run/mysqld/mysqld.pid

Here, you can specify a different directory for the error log, otherwise you should not change any entry in this table.

在这里,您可以为错误日志指定其他目录,否则,您不应更改此表中的任何条目。

管理MySQL命令 (Administrative MySQL Command)

Here is the list of the important MySQL commands, which you will use time to time to work with MySQL database −

这是重要MySQL命令的列表,您将不时使用它们来处理MySQL数据库-

  • USE Databasename − This will be used to select a database in the MySQL workarea.

    USE Databasename-这将用于在MySQL工作区中选择一个数据库。

  • SHOW DATABASES − Lists out the databases that are accessible by the MySQL DBMS.

    显示数据库 -列出MySQL DBMS可访问的数据库。

  • SHOW TABLES − Shows the tables in the database once a database has been selected with the use command.

    SHOW TABLES-使用use命令选择数据库后,显示数据库中的表。

  • SHOW COLUMNS FROM tablename: Shows the attributes, types of attributes, key information, whether NULL is permitted, defaults, and other information for a table.

    表名显示列显示属性,属性类型,键信息,是否允许使用NULL,默认值以及表的其他信息。

  • SHOW INDEX FROM tablename − Presents the details of all indexes on the table, including the PRIMARY KEY.

    SHOW INDEX FROM tablename-显示表上所有索引的详细信息,包括PRIMARY KEY。

  • SHOW TABLE STATUS LIKE tablename\G − Reports details of the MySQL DBMS performance and statistics.

    SHOW TABLE STATUS LIKE tablename \ G-报告MySQL DBMS性能和统计信息的详细信息。

In the next chapter, we will discuss regarding how PHP Syntax is used in MySQL.

在下一章中,我们将讨论如何在MySQL中使用PHP语法。

MySQL-PHP语法 (MySQL - PHP Syntax)

MySQL works very well in combination of various programming languages like PERL, C, C++, JAVA and PHP. Out of these languages, PHP is the most popular one because of its web application development capabilities.

MySQL与各种编程语言(例如PERL,C,C ++,JAVA和PHP)结合使用时效果很好。 在这些语言中,PHP因其Web应用程序开发功能而成为最受欢迎的语言。

This tutorial focuses heavily on using MySQL in a PHP environment. If you are interested in MySQL with PERL, then you can consider reading the PERL Tutorial.

本教程着重于在PHP环境中使用MySQL。 如果您对使用PERLMySQL感兴趣,则可以考虑阅读PERL教程。

PHP provides various functions to access the MySQL database and to manipulate the data records inside the MySQL database. You would require to call the PHP functions in the same way you call any other PHP function.

PHP提供了各种功能来访问MySQL数据库并处理MySQL数据库内部的数据记录。 您将需要以与调用其他任何PHP函数相同的方式来调用PHP函数。

The PHP functions for use with MySQL have the following general format −

与MySQL一起使用PHP函数具有以下常规格式-


mysql_function(value,value,...);

The second part of the function name is specific to the function, usually a word that describes what the function does. The following are two of the functions, which we will use in our tutorial −

函数名称的第二部分特定于函数,通常是一个描述函数功能的单词。 以下是我们将在教程中使用的两个功能-


mysqli_connect($connect);
mysqli_query($connect,"SQL statement");

The following example shows a generic syntax of PHP to call any MySQL function.

以下示例显示了PHP的通用语法,可以调用任何MySQL函数。


<html><head><title>PHP with MySQL</title></head><body><?php$retval = mysql_function(value, [value,...]);if( !$retval ) {die ( "Error: a related error message" );}// Otherwise MySQL  or PHP Statements?></body>
</html>

Starting from the next chapter, we will see all the important MySQL functionality along with PHP.

从下一章开始,我们将看到所有重要MySQL功能以及PHP。

MySQL-连接 (MySQL - Connection)

使用MySQL二进制文件MySQL连接 (MySQL Connection Using MySQL Binary)

You can establish the MySQL database using the mysql binary at the command prompt.

您可以在命令提示符下使用mysql二进制文件建立MySQL数据库。

例 (Example)

Here is a simple example to connect to the MySQL server from the command prompt −

这是一个从命令提示符连接到MySQL服务器的简单示例-


[root@host]# mysql -u root -p
Enter password:******

This will give you the mysql> command prompt where you will be able to execute any SQL command. Following is the result of above command −

这将为您提供mysql>命令提示符,您可以在其中执行任何SQL命令。 以下是上述命令的结果-

The following code block shows the result of above code −

以下代码块显示了以上代码的结果-


Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2854760 to server version: 5.0.9Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

In the above example, we have used root as a user but you can use any other user as well. Any user will be able to perform all the SQL operations, which are allowed to that user.

在上面的示例中,我们以root用户身份使用,但您也可以使用任何其他用户。 任何用户都可以执行该用户允许的所有SQL操作。

You can disconnect from the MySQL database any time using the exit command at mysql> prompt.

您可以随时在mysql>提示符下使用exit命令从MySQL数据库断开连接。


mysql> exit
Bye

使用PHP脚本MySQL连接 (MySQL Connection Using PHP Script)

PHP provides mysql_connect() function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success or FALSE on failure.

PHP提供mysql_connect()函数来打开数据库连接。 该函数有五个参数,如果成功则返回MySQL链接标识符,如果失败则返回FALSE。

句法 (Syntax)


connection mysql_connect(server,user,passwd,new_link,client_flag);

Sr.No. Parameter & Description
1

server

Optional − The host name running the database server. If not specified, then the default value will be localhost:3306.

2

user

Optional − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process.

3

passwd

Optional − The password of the user accessing the database. If not specified, then the default will be an empty password.

4

new_link

Optional − If a second call is made to mysql_connect() with the same arguments, no new connection will be established; instead, the identifier of the already opened connection will be returned.

5

client_flags

Optional − A combination of the following constants −

  • MYSQL_CLIENT_SSL − Use SSL encryption.

  • MYSQL_CLIENT_COMPRESS − Use compression protocol.

  • MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names.

  • MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity before closing the connection.

序号 参数及说明
1个

服务器

可选-运行数据库服务器的主机名。 如果未指定,则默认值为localhost:3306

2

用户

可选-访问数据库的用户名。 如果未指定,则默认值为拥有服务器进程的用户名。

3

密码

可选-访问数据库的用户密码。 如果未指定,则默认值为空密码。

4

new_link

可选-如果使用相同的参数再次调用mysql_connect(),则不会建立新的连接; 相反,将返回已经打开的连接的标识符。

5

client_flags

可选-以下常量的组合-

  • MYSQL_CLIENT_SSL-使用SSL加密。

  • MYSQL_CLIENT_COMPRESS-使用压缩协议。

  • MYSQL_CLIENT_IGNORE_SPACE-在函数名称后留空格。

  • MYSQL_CLIENT_INTERACTIVE-在关闭连接之前,允许不活动的交互超时秒数。

You can disconnect from the MySQL database anytime using another PHP function mysql_close(). This function takes a single parameter, which is a connection returned by the mysql_connect() function.

您可以随时使用另一个PHP函数mysql_close()与MySQL数据库断开连接。 该函数采用单个参数,该参数是mysql_connect()函数返回的连接

句法 (Syntax)


bool mysql_close ( resource $link_identifier );

If a resource is not specified, then the last opened database is closed. This function returns true if it closes the connection successfully otherwise it returns false.

如果未指定资源,则关闭最后打开的数据库。 如果成功关闭连接,此函数将返回true,否则返回false。

例 (Example)

Try the following example to connect to a MySQL server −

尝试以下示例连接到MySQL服务器-


<html><head><title>Connecting MySQL Server</title></head><body><?php$dbhost = 'localhost:3306';$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>

MySQL-创建数据库 (MySQL - Create Database)

使用mysqladmin创建数据库 (Create Database Using mysqladmin)

You would need special privileges to create or to delete a MySQL database. So assuming you have access to the root user, you can create any database using the mysql mysqladmin binary.

您将需要特殊特权才能创建或删除MySQL数据库。 因此,假设您有权访问root用户,则可以使用mysql mysqladmin二进制文件创建任何数据库。

例 (Example)

Here is a simple example to create a database called TUTORIALS

这是创建名为TUTORIALS的数据库的简单示例-


[root@host]# mysqladmin -u root -p create TUTORIALS
Enter password:******

This will create a MySQL database called TUTORIALS.

这将创建一个名为TUTORIALSMySQL数据库。

使用PHP脚本创建数据库 (Create a Database using PHP Script)

PHP uses mysql_query function to create or delete a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.

PHP使用mysql_query函数创建或删除MySQL数据库。 此函数有两个参数,如果成功则返回TRUE,否则返回FALSE。

句法 (Syntax)


bool mysql_query( sql, connection );

Sr.No. Parameter & Description
1

sql

Required - SQL query to create or delete a MySQL database

2

connection

Optional - if not specified, then the last opened connection by mysql_connect will be used.

序号 参数及说明
1个

sql

必需-用于创建或删除MySQL数据库SQL查询

2

连接

可选-如果未指定,则将使用mysql_connect上次打开的连接。

例 (Example)

The following example to create a database −

以下示例创建数据库-


<html><head><title>Creating MySQL Database</title></head><body><?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}echo 'Connected successfully<br />';$sql = 'CREATE DATABASE TUTORIALS';$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not create database: ' . mysql_error());}echo "Database TUTORIALS created successfully\n";mysql_close($conn);?></body>
</html>

删除MySQL数据库 (Drop MySQL Database)

使用mysqladmin删除数据库 (Drop a Database using mysqladmin)

You would need special privileges to create or to delete a MySQL database. So, assuming you have access to the root user, you can create any database using the mysql mysqladmin binary.

您将需要特殊特权才能创建或删除MySQL数据库。 因此,假设您有权访问root用户,则可以使用mysql mysqladmin二进制文件创建任何数据库。

Be careful while deleting any database because you will lose your all the data available in your database.

删除任何数据库时请小心,因为您将丢失数据库中所有可用的数据。

Here is an example to delete a database(TUTORIALS) created in the previous chapter −

这是删除上一章中创建的数据库(TUTORIALS)的示例-


[root@host]# mysqladmin -u root -p drop TUTORIALS
Enter password:******

This will give you a warning and it will confirm if you really want to delete this database or not.

这将给您一个警告,并确认您是否确实要删除此数据库。


Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.Do you really want to drop the 'TUTORIALS' database [y/N] y
Database "TUTORIALS" dropped

使用PHP脚本删除数据库 (Drop Database using PHP Script)

PHP uses mysql_query function to create or delete a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.

PHP使用mysql_query函数创建或删除MySQL数据库。 此函数有两个参数,如果成功则返回TRUE,否则返回FALSE。

句法 (Syntax)


bool mysql_query( sql, connection );

Sr.No Parameter & Description
1

sql

Required − SQL query to create or delete a MySQL database

2

connection

Optional − if not specified, then the last opened connection by mysql_connect will be used.

序号 参数及说明
1个

sql

必需-创建或删除MySQL数据库SQL查询

2

连接

可选-如果未指定,则将使用mysql_connect上次打开的连接。

例 (Example)

Try the following example to delete a database −

尝试以下示例删除数据库-


<html><head><title>Deleting MySQL Database</title></head><body><?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}echo 'Connected successfully<br />';$sql = 'DROP DATABASE TUTORIALS';$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not delete database: ' . mysql_error());}echo "Database TUTORIALS deleted successfully\n";mysql_close($conn);?></body>
</html>

WARNING − While deleting a database using the PHP script, it does not prompt you for any confirmation. So be careful while deleting a MySQL database.

警告 -使用PHP脚本删除数据库时,它不会提示您进行任何确认。 因此,删除MySQL数据库时要小心。

选择MySQL数据库 (Selecting MySQL Database)

Once you get connected with the MySQL server, it is required to select a database to work with. This is because there might be more than one database available with the MySQL Server.

与MySQL服务器建立连接后,需要选择要使用的数据库。 这是因为MySQL服务器可能有多个数据库可用。

从命令提示符中选择MySQL数据库 (Selecting MySQL Database from the Command Prompt)

It is very simple to select a database from the mysql> prompt. You can use the SQL command use to select a database.

从mysql>提示符下选择数据库非常简单。 您可以使用SQL命令use选择数据库。

例 (Example)

Here is an example to select a database called TUTORIALS

这是一个选择名为TUTORIALS的数据库的示例-


[root@host]# mysql -u root -p
Enter password:******
mysql> use TUTORIALS;
Database changed
mysql>

Now, you have selected the TUTORIALS database and all the subsequent operations will be performed on the TUTORIALS database.

现在,您已经选择了TUTORIALS数据库,所有后续操作将在TUTORIALS数据库上执行。

NOTE − All the database names, table names, table fields name are case sensitive. So you would have to use the proper names while giving any SQL command.

–所有数据库名称,表名称,表字段名称均区分大小写。 因此,在发出任何SQL命令时,您必须使用适当的名称。

使用PHP脚本选择MySQL数据库 (Selecting a MySQL Database Using PHP Script)

PHP provides function mysql_select_db to select a database. It returns TRUE on success or FALSE on failure.

PHP提供了mysql_select_db函数来选择数据库。 成功返回TRUE,失败返回FALSE。

句法 (Syntax)


bool mysql_select_db( db_name, connection );

Sr.No. Parameter & Description
1

db_name

Required − MySQL Database name to be selected

2

connection

Optional − if not specified, then the last opened connection by mysql_connect will be used.

序号 参数及说明
1个

db_name

必需-要选择MySQL数据库名称

2

连接

可选-如果未指定,则将使用mysql_connect上次打开的连接。

例 (Example)

Here is an example showing you how to select a database.

这是显示如何选择数据库的示例。


<html><head><title>Selecting MySQL Database</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_select_db( 'TUTORIALS' );mysql_close($conn);?></body>
</html>

MySQL-数据类型 (MySQL - Data Types)

Properly defining the fields in a table is important to the overall optimization of your database. You should use only the type and size of field you really need to use. For example, do not define a field 10 characters wide, if you know you are only going to use 2 characters. These type of fields (or columns) are also referred to as data types, after the type of data you will be storing in those fields.

正确定义表中的字段对于数据库的整体优化很重要。 您应该只使用您真正需要使用的字段的类型和大小。 例如,如果您只打算使用2个字符,则不要定义10个字符宽的字段。 这些类型的字段(或列)的,也被称为数据类型,将在这些字段被存储的数据的类型之后。

MySQL uses many different data types broken into three categories −

MySQL使用分为三类的许多不同数据类型-

  • Numeric数字
  • Date and Time日期和时间
  • String Types.字符串类型。

Let us now discuss them in detail.

现在让我们详细讨论它们。

数值数据类型 (Numeric Data Types)

MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from a different database system, these definitions will look familiar to you.

MySQL使用所有标准的ANSI SQL数字数据类型,因此,如果您是从其他数据库系统访问MySQL的,则这些定义对您来说很熟悉。

The following list shows the common numeric data types and their descriptions −

以下列表显示了常见的数字数据类型及其描述-

  • INT − A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from -2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295. You can specify a width of up to 11 digits.

    INT-可以带符号或无符号的普通大小的整数。 如果已签名,则允许范围是-2147483648至2147483647。如果未签名,则允许范围是0至4294967295。您可以指定最大11位数字的宽度。

  • TINYINT − A very small integer that can be signed or unsigned. If signed, the allowable range is from -128 to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits.

    TINYINT-一个非常小的整数,可以有符号或无符号。 如果已签名,则允许范围是-128到127。如果是未签名,则允许范围是0到255。您可以指定最多4位数字的宽度。

  • SMALLINT − A small integer that can be signed or unsigned. If signed, the allowable range is from -32768 to 32767. If unsigned, the allowable range is from 0 to 65535. You can specify a width of up to 5 digits.

    SMALLINT-一个小的整数,可以有符号或无符号。 如果已签名,则允许范围是-32768到32767。如果是未签名,则允许范围是0到65535。您可以指定最多5位数字的宽度。

  • MEDIUMINT − A medium-sized integer that can be signed or unsigned. If signed, the allowable range is from -8388608 to 8388607. If unsigned, the allowable range is from 0 to 16777215. You can specify a width of up to 9 digits.

    MEDIUMINT-可以签名或不签名的中型整数。 如果已签名,则允许的范围是-8388608至8388607。如果未签名,则允许的范围是0至16777215。您可以指定最多9位数字的宽度。

  • BIGINT − A large integer that can be signed or unsigned. If signed, the allowable range is from -9223372036854775808 to 9223372036854775807. If unsigned, the allowable range is from 0 to 18446744073709551615. You can specify a width of up to 20 digits.

    BIGINT-可以有符号或无符号的大整数。 如果签名,则允许范围是-9223372036854775808至9223372036854775807。如果未签名,则允许范围是0到18446744073709551615。您可以指定最大20位数字的宽度。

  • FLOAT(M,D) − A floating-point number that cannot be unsigned. You can define the display length (M) and the number of decimals (D). This is not required and will default to 10,2, where 2 is the number of decimals and 10 is the total number of digits (including decimals). Decimal precision can go to 24 places for a FLOAT.

    FLOAT(M,D) -不能无符号的浮点数。 您可以定义显示长度(M)和小数位数(D)。 这不是必需的,默认为10,2,其中2是小数位数,而10是数字总数(包括小数位数)。 浮点数的小数精度可以达到24位。

  • DOUBLE(M,D) − A double precision floating-point number that cannot be unsigned. You can define the display length (M) and the number of decimals (D). This is not required and will default to 16,4, where 4 is the number of decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE.

    DOUBLE(M,D) -不能无符号的双精度浮点数。 您可以定义显示长度(M)和小数位数(D)。 这不是必需的,并且默认为16,4,其中4是小数位数。 小数精度可以达到53位(双精度)。 REAL是DOUBLE的同义词。

  • DECIMAL(M,D) − An unpacked floating-point number that cannot be unsigned. In the unpacked decimals, each decimal corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required. NUMERIC is a synonym for DECIMAL.

    DECIMAL(M,D) -无法解压缩的解压缩浮点数。 在解压缩的十进制中,每个十进制对应一个字节。 需要定义显示长度(M)和小数位数(D)。 NUMERIC是DECIMAL的同义词。

日期和时间类型 (Date and Time Types)

The MySQL date and time datatypes are as follows −

MySQL日期和时间数据类型如下-

  • DATE − A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th, 1973 would be stored as 1973-12-30.

    日期 -YYYY-MM-DD格式的日期,介于1000-01-01和9999-12-31之间。 例如,1973年12月30 将存储为1973-12-30。

  • DATETIME − A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00.

    DATETIME-日期和时间组合,格式为YYYY-MM-DD HH:MM:SS,介于1000-01-01 00:00:00和9999-12-31 23:59:59之间。 例如,1973年12月30 下午3:30将存储为1973-12-30 15:30:00。

  • TIMESTAMP − A timestamp between midnight, January 1st, 1970 and sometime in 2037. This looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ).

    时间戳 -1970年1月1 午夜到2037年之间的时间戳。这看起来像以前的DATETIME格式,只是数字之间没有连字符。 1973年12月30 下午3:30将存储为19731230153000(YYYYMMDDHHMMSS)。

  • TIME − Stores the time in a HH:MM:SS format.

    TIME-以HH:MM:SS格式存储时间。

  • YEAR(M) − Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for example YEAR(2)), YEAR can be between 1970 to 2069 (70 to 69). If the length is specified as 4, then YEAR can be 1901 to 2155. The default length is 4.

    YEAR(M) -以2位数或4位数格式存储年份。 如果将长度指定为2(例如YEAR(2)),则YEAR可以介于1970到2069(70到69)之间。 如果将长度指定为4,则YEAR可以是1901至2155。默认长度是4。

字符串类型 (String Types)

Although the numeric and date types are fun, most data you'll store will be in a string format. This list describes the common string datatypes in MySQL.

尽管数字和日期类型很有趣,但是您将存储的大多数数据都是字符串格式。 此列表描述了MySQL中的常见字符串数据类型。

  • CHAR(M) − A fixed-length string between 1 and 255 characters in length (for example CHAR(5)), right-padded with spaces to the specified length when stored. Defining a length is not required, but the default is 1.

    CHAR(M) -长度介于1到255个字符之间的固定长度字符串(例如CHAR(5)),在存储时用空格填充到指定的长度。 不需要定义长度,但默认值为1。

  • VARCHAR(M) − A variable-length string between 1 and 255 characters in length. For example, VARCHAR(25). You must define a length when creating a VARCHAR field.

    VARCHAR(M) -长度在1到255个字符之间的可变长度字符串。 例如,VARCHAR(25)。 创建VARCHAR字段时必须定义长度。

  • BLOB or TEXT − A field with a maximum length of 65535 characters. BLOBs are "Binary Large Objects" and are used to store large amounts of binary data, such as images or other types of files. Fields defined as TEXT also hold large amounts of data. The difference between the two is that the sorts and comparisons on the stored data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a length with BLOB or TEXT.

    BLOB或TEXT-字段的最大长度为65535个字符。 BLOB是“二进制大对象”,用于存储大量二进制数据,例如图像或其他类型的文件。 定义为TEXT的字段也包含大量数据。 两者之间的区别在于,所存储的数据的种类和比较是区分上的BLOB 敏感不区分在文本字段中敏感 。 您没有使用BLOB或TEXT指定长度。

  • TINYBLOB or TINYTEXT − A BLOB or TEXT column with a maximum length of 255 characters. You do not specify a length with TINYBLOB or TINYTEXT.

    TINYBLOB或TINYTEXT -BLOB或TEXT列,最大长度为255个字符。 您未使用TINYBLOB或TINYTEXT指定长度。

  • MEDIUMBLOB or MEDIUMTEXT − A BLOB or TEXT column with a maximum length of 16777215 characters. You do not specify a length with MEDIUMBLOB or MEDIUMTEXT.

    MEDIUMBLOB或MEDIUMTEXT -BLOB或TEXT列,最大长度为16777215个字符。 您没有使用MEDIUMBLOB或MEDIUMTEXT指定长度。

  • LONGBLOB or LONGTEXT − A BLOB or TEXT column with a maximum length of 4294967295 characters. You do not specify a length with LONGBLOB or LONGTEXT.

    LONGBLOB或LONGTEXT -BLOB或TEXT列,最大长度为4294967295个字符。 您没有使用LONGBLOB或LONGTEXT指定长度。

  • ENUM − An enumeration, which is a fancy term for list. When defining an ENUM, you are creating a list of items from which the value must be selected (or it can be NULL). For example, if you wanted your field to contain "A" or "B" or "C", you would define your ENUM as ENUM ('A', 'B', 'C') and only those values (or NULL) could ever populate that field.

    枚举 -一个枚举,这是一个花哨的术语列表。 定义ENUM时,您将创建一个项目列表,必须从中选择值(或者可以为NULL)。 例如,如果希望字段包含“ A”,“ B”或“ C”,则可以将ENUM定义为ENUM(“ A”,“ B”,“ C”),并且仅将这些值(或NULL)定义为ENUM可能会填充该字段。

In the next chapter, we will discuss how to create tables in MySQL.

在下一章中,我们将讨论如何在MySQL中创建表。

创建MySQL表 (Create MySQL Tables)

To begin with, the table creation command requires the following details −

首先,表创建命令需要以下详细信息-

  • Name of the table表名
  • Name of the fields字段名称
  • Definitions for each field每个字段的定义

句法 (Syntax)

Here is a generic SQL syntax to create a MySQL table −

这是创建MySQL表的通用SQL语法-


CREATE TABLE table_name (column_name column_type);

Now, we will create the following table in the TUTORIALS database.

现在,我们将在TUTORIALS数据库中创建下表。


create table tutorials_tbl(tutorial_id INT NOT NULL AUTO_INCREMENT,tutorial_title VARCHAR(100) NOT NULL,tutorial_author VARCHAR(40) NOT NULL,submission_date DATE,PRIMARY KEY ( tutorial_id )
);

Here, a few items need explanation −

在这里,一些项目需要解释-

  • Field Attribute NOT NULL is being used because we do not want this field to be NULL. So, if a user will try to create a record with a NULL value, then MySQL will raise an error.

    使用字段属性NOT NULL的原因是我们不希望该字段为NULL。 因此,如果用户尝试使用NULL值创建记录,则MySQL将引发错误。

  • Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available number to the id field.

    字段属性AUTO_INCREMENT告诉MySQL继续并将下一个可用数字添加到id字段。

  • Keyword PRIMARY KEY is used to define a column as a primary key. You can use multiple columns separated by a comma to define a primary key.

    关键字PRIMARY KEY用于将列定义为主键。 您可以使用由逗号分隔的多个列来定义主键。

从命令提示符创建表 (Creating Tables from Command Prompt)

It is easy to create a MySQL table from the mysql> prompt. You will use the SQL command CREATE TABLE to create a table.

从mysql>提示符创建MySQL表很容易。 您将使用SQL命令CREATE TABLE创建一个表。

例 (Example)

Here is an example, which will create tutorials_tbl

这是一个示例,它将创建tutorials_tbl-


root@host# mysql -u root -p
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> CREATE TABLE tutorials_tbl(-> tutorial_id INT NOT NULL AUTO_INCREMENT,-> tutorial_title VARCHAR(100) NOT NULL,-> tutorial_author VARCHAR(40) NOT NULL,-> submission_date DATE,-> PRIMARY KEY ( tutorial_id )-> );
Query OK, 0 rows affected (0.16 sec)
mysql>

NOTE − MySQL does not terminate a command until you give a semicolon (;) at the end of SQL command.

– MySQL不会终止命令,直到在SQL命令的末尾加上分号(;)为止。

使用PHP脚本创建表 (Creating Tables Using PHP Script)

To create new table in any existing database you would need to use PHP function mysql_query(). You will pass its second argument with a proper SQL command to create a table.

要在任何现有数据库中创建新表,您将需要使用PHP函数mysql_query() 。 您将使用适当SQL命令传递其第二个参数来创建表。

例 (Example)

The following program is an example to create a table using PHP script −

以下程序是使用PHP脚本创建表的示例-


<html><head><title>Creating MySQL Tables</title></head><body><?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}echo 'Connected successfully<br />';$sql = "CREATE TABLE tutorials_tbl( "."tutorial_id INT NOT NULL AUTO_INCREMENT, "."tutorial_title VARCHAR(100) NOT NULL, "."tutorial_author VARCHAR(40) NOT NULL, "."submission_date DATE, "."PRIMARY KEY ( tutorial_id )); ";mysql_select_db( 'TUTORIALS' );$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not create table: ' . mysql_error());}echo "Table created successfully\n";mysql_close($conn);?></body>
</html>

删除MySQL表 (Drop MySQL Tables)

It is very easy to drop an existing MySQL table, but you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table.

删除现有MySQL表非常容易,但是删除任何现有的表时要非常小心,因为删除表后丢失的数据将无法恢复。

句法 (Syntax)

Here is a generic SQL syntax to drop a MySQL table −

这是删除MySQL表的通用SQL语法-


DROP TABLE table_name ;

从命令提示符中删除表 (Dropping Tables from the Command Prompt)

To drop tables from the command prompt, we need to execute the DROP TABLE SQL command at the mysql> prompt.

要从命令提示符下删除表,我们需要在mysql>提示符下执行DROP TABLE SQL命令。

例 (Example)

The following program is an example which deletes the tutorials_tbl

以下程序是一个删除tutorials_tbl的示例-


root@host# mysql -u root -p
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> DROP TABLE tutorials_tbl
Query OK, 0 rows affected (0.8 sec)
mysql>

使用PHP脚本删除表 (Dropping Tables Using PHP Script)

To drop an existing table in any database, you would need to use the PHP function mysql_query(). You will pass its second argument with a proper SQL command to drop a table.

要删除任何数据库中的现有表,您需要使用PHP函数mysql_query() 。 您将使用适当SQL命令传递其第二个参数来删除表。

例 (Example)


<html><head><title>Creating MySQL Tables</title></head><body><?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}echo 'Connected successfully<br />';$sql = "DROP TABLE tutorials_tbl";mysql_select_db( 'TUTORIALS' );$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not delete table: ' . mysql_error());}echo "Table deleted successfully\n";mysql_close($conn);?></body>
</html>

MySQL-插入查询 (MySQL - Insert Query)

To insert data into a MySQL table, you would need to use the SQL INSERT INTO command. You can insert data into the MySQL table by using the mysql> prompt or by using any script like PHP.

要将数据插入MySQL表中,您将需要使用SQL INSERT INTO命令。 您可以使用mysql>提示符或使用任何脚本(如PHP)将数据插入MySQL表。

句法 (Syntax)

Here is a generic SQL syntax of INSERT INTO command to insert data into the MySQL table −

这是INSERT INTO命令的通用SQL语法,用于将数据插入MySQL表-


INSERT INTO table_name ( field1, field2,...fieldN )VALUES( value1, value2,...valueN );

To insert string data types, it is required to keep all the values into double or single quotes. For example "value".

要插入字符串数据类型,需要将所有值都保留在双引号或单引号中。 例如“ value”

从命令提示符插入数据 (Inserting Data from the Command Prompt)

To insert data from the command prompt, we will use SQL INSERT INTO command to insert data into MySQL table tutorials_tbl.

要从命令提示符处插入数据,我们将使用SQL INSERT INTO命令将数据插入MySQL表tutorials_tbl。

例 (Example)

The following example will create 3 records into tutorials_tbl table −

下面的示例将在tutorials_tbl表中创建3条记录-


root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changedmysql> INSERT INTO tutorials_tbl ->(tutorial_title, tutorial_author, submission_date)->VALUES->("Learn PHP", "John Poul", NOW());
Query OK, 1 row affected (0.01 sec)mysql> INSERT INTO tutorials_tbl->(tutorial_title, tutorial_author, submission_date)->VALUES->("Learn MySQL", "Abdul S", NOW());
Query OK, 1 row affected (0.01 sec)mysql> INSERT INTO tutorials_tbl->(tutorial_title, tutorial_author, submission_date)->VALUES->("JAVA Tutorial", "Sanjay", '2007-05-06');
Query OK, 1 row affected (0.01 sec)
mysql>

NOTE − Please note that all the arrow signs (->) are not a part of the SQL command. They are indicating a new line and they are created automatically by the MySQL prompt while pressing the enter key without giving a semicolon at the end of each line of the command.

注意 -请注意,所有箭头符号(->)都不是SQL命令的一部分。 它们表示新行,它们是由MySQL提示符自动创建的,同时按下Enter键,而无需在命令的每一行末尾添加分号。

In the above example, we have not provided a tutorial_id because at the time of table creation, we had given AUTO_INCREMENT option for this field. So MySQL takes care of inserting these IDs automatically. Here, NOW() is a MySQL function, which returns the current date and time.

在上面的示例中,我们没有提供tutorial_id,因为在创建表时,我们为此字段提供了AUTO_INCREMENT选项。 因此,MySQL负责自动插入这些ID。 在这里, NOW()是一个MySQL函数,它返回当前日期和时间。

使用PHP脚本插入数据 (Inserting Data Using a PHP Script)

You can use the same SQL INSERT INTO command into the PHP function mysql_query() to insert data into a MySQL table.

您可以在PHP函数mysql_query()中使用相同SQL INSERT INTO命令,以将数据插入MySQL表。

例 (Example)

This example will take three parameters from the user and will insert them into the MySQL table −

此示例将从用户那里获取三个参数,并将其插入到MySQL表中-


<html><head><title>Add New Record in MySQL Database</title></head><body><?phpif(isset($_POST['add'])) {$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}if(! get_magic_quotes_gpc() ) {$tutorial_title = addslashes ($_POST['tutorial_title']);$tutorial_author = addslashes ($_POST['tutorial_author']);} else {$tutorial_title = $_POST['tutorial_title'];$tutorial_author = $_POST['tutorial_author'];}$submission_date = $_POST['submission_date'];$sql = "INSERT INTO tutorials_tbl "."(tutorial_title,tutorial_author, submission_date) "."VALUES "."('$tutorial_title','$tutorial_author','$submission_date')";mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not enter data: ' . mysql_error());}echo "Entered data successfully\n";mysql_close($conn);} else {?><form method = "post" action = "<?php $_PHP_SELF ?>"><table width = "600" border = "0" cellspacing = "1" cellpadding = "2"><tr><td width = "250">Tutorial Title</td><td><input name = "tutorial_title" type = "text" id = "tutorial_title"></td></tr><tr><td width = "250">Tutorial Author</td><td><input name = "tutorial_author" type = "text" id = "tutorial_author"></td></tr><tr><td width = "250">Submission Date [   yyyy-mm-dd ]</td><td><input name = "submission_date" type = "text" id = "submission_date"></td></tr><tr><td width = "250"> </td><td> </td></tr><tr><td width = "250"> </td><td><input name = "add" type = "submit" id = "add"  value = "Add Tutorial"></td></tr></table></form><?php}?></body>
</html>

While doing a data insert, it is best to use the function get_magic_quotes_gpc() to check if the current configuration for magic quote is set or not. If this function returns false, then use the function addslashes() to add slashes before the quotes.

进行数据插入时,最好使用函数get_magic_quotes_gpc()来检查是否设置了魔术引号的当前配置。 如果此函数返回false,则使用函数addlashes()在引号之前添加斜杠。

You can put many validations around to check if the entered data is correct or not and can take the appropriate action.

您可以进行很多验证来检查输入的数据是否正确,并可以采取适当的措施。

MySQL-选择查询 (MySQL - Select Query)

The SQL SELECT command is used to fetch data from the MySQL database. You can use this command at mysql> prompt as well as in any script like PHP.

SQL SELECT命令用于从MySQL数据库获取数据。 您可以在mysql>提示符以及任何脚本(如PHP)中使用此命令。

句法 (Syntax)

Here is generic SQL syntax of SELECT command to fetch data from the MySQL table −

这是SELECT命令的通用SQL语法,用于从MySQL表中获取数据-


SELECT field1, field2,...fieldN
FROM table_name1, table_name2...
[WHERE Clause]
[OFFSET M ][LIMIT N]

  • You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command.

    您可以使用WHERE子句来使用一个或多个用逗号分隔的表来包含各种条件,但是WHERE子句是SELECT命令的可选部分。

  • You can fetch one or more fields in a single SELECT command.

    您可以在单个SELECT命令中获取一个或多个字段。

  • You can specify star (*) in place of fields. In this case, SELECT will return all the fields.

    您可以指定星号(*)代替字段。 在这种情况下,SELECT将返回所有字段。

  • You can specify any condition using the WHERE clause.

    您可以使用WHERE子句指定任何条件。

  • You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero.

    您可以使用OFFSET指定偏移量,SELECT将从该偏移量开始返回记录。 默认情况下,偏移量从零开始。

  • You can limit the number of returns using the LIMIT attribute.

    您可以使用LIMIT属性限制退货数量。

从命令提示符中获取数据 (Fetching Data from a Command Prompt)

This will use SQL SELECT command to fetch data from the MySQL table tutorials_tbl.

这将使用SQL SELECT命令从MySQL表tutorials_tbl中获取数据。

例 (Example)

The following example will return all the records from the tutorials_tbl table −

以下示例将返回tutorials_tbl表中的所有记录-


root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
|           1 | Learn PHP      | John Poul       | 2007-05-21      |
|           2 | Learn MySQL    | Abdul S         | 2007-05-21      |
|           3 | JAVA Tutorial  | Sanjay          | 2007-05-21      |
+-------------+----------------+-----------------+-----------------+
3 rows in set (0.01 sec)mysql>

使用PHP脚本获取数据 (Fetching Data Using a PHP Script)

You can use the same SQL SELECT command into a PHP function mysql_query(). This function is used to execute the SQL command and then later another PHP function mysql_fetch_array() can be used to fetch all the selected data. This function returns the row as an associative array, a numeric array, or both. This function returns FALSE if there are no more rows.

您可以在PHP函数mysql_query()中使用相同SQL SELECT命令。 该函数用于执行SQL命令,然后可以使用另一个PHP函数mysql_fetch_array()来获取所有选定数据。 此函数以关联数组,数字数组或两者兼有的形式返回该行。 如果没有更多行,此函数将返回FALSE。

The following program is a simple example which will show how to fetch / display records from the tutorials_tbl table.

下面的程序是一个简单的示例,它将显示如何从tutorials_tbl表中获取/显示记录。

例 (Example)

The following code block will display all the records from the tutorials_tbl table.

下面的代码块将显示tutorials_tbl表中的所有记录。


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not get data: ' . mysql_error());}while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {echo "Tutorial ID :{$row['tutorial_id']}  <br> "."Title: {$row['tutorial_title']} <br> "."Author: {$row['tutorial_author']} <br> "."Submission Date : {$row['submission_date']} <br> "."--------------------------------<br>";} echo "Fetched data successfully\n";mysql_close($conn);
?>

The content of the rows is assigned to the variable $row and the values in that row are then printed.

将行的内容分配给变量$ row,然后打印该行中的值。

NOTE − Always remember to put curly brackets when you want to insert an array value directly into a string.

注意 -当您想将数组值直接插入字符串时,请始终记住使用大括号。

In the above example, the constant MYSQL_ASSOC is used as the second argument to the PHP function mysql_fetch_array(), so that it returns the row as an associative array. With an associative array you can access the field by using their name instead of using the index.

在上面的示例中,常量MYSQL_ASSOC用作PHP函数mysql_fetch_array()的第二个参数,因此它将行作为关联数组返回。 使用关联数组,您可以使用字段名称而不是使用索引来访问该字段。

PHP provides another function called mysql_fetch_assoc(), which also returns the row as an associative array.

PHP提供了另一个名为mysql_fetch_assoc()的函数,该函数还以关联数组的形式返回该行。

例 (Example)

The following example to display all the records from the tutorial_tbl table using mysql_fetch_assoc() function.

下面的示例使用mysql_fetch_assoc()函数显示tutorial_tbl表中的所有记录。


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_dateFROM tutorials_tbl';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not get data: ' . mysql_error());}while($row = mysql_fetch_assoc($retval)) {echo "Tutorial ID :{$row['tutorial_id']}  <br> "."Title: {$row['tutorial_title']} <br> "."Author: {$row['tutorial_author']} <br> "."Submission Date : {$row['submission_date']} <br> "."--------------------------------<br>";} echo "Fetched data successfully\n";mysql_close($conn);
?>

You can also use the constant MYSQL_NUM as the second argument to the PHP function mysql_fetch_array(). This will cause the function to return an array with the numeric index.

您还可以将常量MYSQL_NUM用作PHP函数mysql_fetch_array()的第二个参数。 这将导致函数返回带有数字索引的数组。

例 (Example)

Try out the following example to display all the records from tutorials_tbl table using the MYSQL_NUM argument.

尝试以下示例使用MYSQL_NUM参数显示tutorials_tbl表中的所有记录。


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_dateFROM tutorials_tbl';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not get data: ' . mysql_error());}while($row = mysql_fetch_array($retval, MYSQL_NUM)) {echo "Tutorial ID :{$row[0]}  <br> "."Title: {$row[1]} <br> "."Author: {$row[2]} <br> "."Submission Date : {$row[3]} <br> "."--------------------------------<br>";}echo "Fetched data successfully\n";mysql_close($conn);
?>

All the above three examples will produce the same result.

以上三个示例都将产生相同的结果。

释放内存 (Releasing Memory)

It is a good practice to release cursor memory at the end of each SELECT statement. This can be done by using the PHP function mysql_free_result(). The following program is the example to show how it should be used.

在每个SELECT语句的末尾释放游标内存是一个好习惯。 这可以通过使用PHP函数mysql_free_result()来完成。 下面的程序是显示应如何使用的示例。

例 (Example)

Try out the following example −

尝试以下示例-


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_dateFROM tutorials_tbl';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not get data: ' . mysql_error());}while($row = mysql_fetch_array($retval, MYSQL_NUM)) {echo "Tutorial ID :{$row[0]}  <br> "."Title: {$row[1]} <br> "."Author: {$row[2]} <br> "."Submission Date : {$row[3]} <br> "."--------------------------------<br>";}mysql_free_result($retval);echo "Fetched data successfully\n";mysql_close($conn);
?>

While fetching data, you can write as complex a code as you like, but the procedure will remain the same as mentioned above.

在获取数据时,您可以根据需要编写复杂的代码,但是该过程将保持与上述相同。

MySQL-WHERE子句 (MySQL - WHERE Clause)

We have seen the SQL SELECT command to fetch data from a MySQL table. We can use a conditional clause called the WHERE Clause to filter out the results. Using this WHERE clause, we can specify a selection criteria to select the required records from a table.

我们已经看到了SQL SELECT命令从MySQL表中获取数据。 我们可以使用称为WHERE子句的条件子句来过滤结果。 使用此WHERE子句,我们可以指定选择条件以从表中选择所需的记录。

句法 (Syntax)

The following code block has a generic SQL syntax of the SELECT command with the WHERE clause to fetch data from the MySQL table −

以下代码块具有SELECT命令的通用SQL语法和WHERE子句,可从MySQL表中获取数据-


SELECT field1, field2,...fieldN table_name1, table_name2...
[WHERE condition1 [AND [OR]] condition2.....

  • You can use one or more tables separated by a comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command.

    您可以使用WHERE子句来使用一个或多个用逗号分隔的表来包含各种条件,但是WHERE子句是SELECT命令的可选部分。

  • You can specify any condition using the WHERE clause.

    您可以使用WHERE子句指定任何条件。

  • You can specify more than one condition using the AND or the OR operators.

    您可以使用ANDOR运算符指定多个条件。

  • A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition.

    WHERE子句可以与DELETE或UPDATE SQL命令一起使用,也可以指定条件。

The WHERE clause works like an if condition in any programming language. This clause is used to compare the given value with the field value available in a MySQL table. If the given value from outside is equal to the available field value in the MySQL table, then it returns that row.

WHERE子句的作用类似于任何编程语言中的if条件 。 该子句用于将给定值与MySQL表中可用的字段值进行比较。 如果外部的给定值等于MySQL表中的可用字段值,则它将返回该行。

Here is the list of operators, which can be used with the WHERE clause.

这是可与WHERE子句一起使用的运算符列表。

Assume field A holds 10 and field B holds 20, then −

假设字段A持有10,字段B持有20,则-

Operator Description Example
= Checks if the values of the two operands are equal or not, if yes, then the condition becomes true. (A = B) is not true.
!= Checks if the values of the two operands are equal or not, if the values are not equal then the condition becomes true. (A != B) is true.
> Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true. (A > B) is not true.
< Checks if the value of the left operand is less than the value of the right operand, if yes then the condition becomes true. (A < B) is true.
>= Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true. (A >= B) is not true.
<= Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true. (A <= B) is true.
操作员 描述
= 检查两个操作数的值是否相等,如果是,则条件为真。 (A = B)不正确。
!= 检查两个操作数的值是否相等,如果值不相等,则条件为真。 (A!= B)为真。
> 检查左操作数的值是否大于右操作数的值,如果是,则条件变为true。 (A> B)不正确。
< 检查左操作数的值是否小于右操作数的值,如果是,则条件为true。 (A <B)是真的。
> = 检查左操作数的值是否大于或等于右操作数的值,如果是,则条件为true。 (A> = B)不正确。
<= 检查左操作数的值是否小于或等于右操作数的值,如果是,则条件为true。 (A <= B)是正确的。

The WHERE clause is very useful when you want to fetch the selected rows from a table, especially when you use the MySQL Join. Joins are discussed in another chapter.

当您想从表中获取选定的行时,WHERE子句非常有用,尤其是当您使用MySQL Join时 。 连接将在另一章中讨论。

It is a common practice to search for records using the Primary Key to make the search faster.

使用主键搜索记录以加快搜索速度是一种常见的做法。

If the given condition does not match any record in the table, then the query would not return any row.

如果给定条件与表中的任何记录都不匹配,则查询将不返回任何行。

从命令提示符中获取数据 (Fetching Data from the Command Prompt)

This will use the SQL SELECT command with the WHERE clause to fetch the selected data from the MySQL table – tutorials_tbl.

这将使用带有WHERE子句SQL SELECT命令从MySQL表– tutorials_tbl中获取所选数据。

例 (Example)

The following example will return all the records from the tutorials_tbl table for which the author name is Sanjay.

下面的示例将返回tutorials_tbl表中所有记录的作者姓名为Sanjay


root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl WHERE tutorial_author = 'Sanjay';
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
|      3      | JAVA Tutorial  |      Sanjay     |    2007-05-21   |
+-------------+----------------+-----------------+-----------------+
1 rows in set (0.01 sec)mysql>

Unless performing a LIKE comparison on a string, the comparison is not case sensitive. You can make your search case sensitive by using the BINARY keyword as follows −

除非对字符串执行LIKE比较,否则比较不区分大小写。 您可以使用BINARY关键字使搜索区分大小写,如下所示:


root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl \WHERE BINARY tutorial_author = 'sanjay';
Empty set (0.02 sec)mysql>

使用PHP脚本获取数据 (Fetching Data Using a PHP Script)

You can use the same SQL SELECT command with the WHERE CLAUSE into the PHP function mysql_query(). This function is used to execute the SQL command and later another PHP function mysql_fetch_array() can be used to fetch all the selected data. This function returns a row as an associative array, a numeric array, or both. This function returns FALSE if there are no more rows.

您可以在WHERE CLAUSE中使用相同SQL SELECT命令到PHP函数mysql_query()中 。 该函数用于执行SQL命令,以后可以使用另一个PHP函数mysql_fetch_array()来获取所有选定的数据。 此函数以关联数组和/或数字数组的形式返回一行。 如果没有更多行,此函数将返回FALSE。

例 (Example)

The following example will return all the records from the tutorials_tbl table for which the author name is Sanjay

以下示例将返回tutorials_tbl表中所有记录的作者姓名为Sanjay的记录 -


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_dateFROM tutorials_tblWHERE tutorial_author = "Sanjay"';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not get data: ' . mysql_error());}while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {echo "Tutorial ID :{$row['tutorial_id']}  <br> "."Title: {$row['tutorial_title']} <br> "."Author: {$row['tutorial_author']} <br> "."Submission Date : {$row['submission_date']} <br> "."--------------------------------<br>";} echo "Fetched data successfully\n";mysql_close($conn);
?>

MySQL-更新查询 (MySQL - UPDATE Query)

There may be a requirement where the existing data in a MySQL table needs to be modified. You can do so by using the SQL UPDATE command. This will modify any field value of any MySQL table.

可能需要修改MySQL表中的现有数据。 您可以通过使用SQL UPDATE命令来实现。 这将修改任何MySQL表的任何字段值。

句法 (Syntax)

The following code block has a generic SQL syntax of the UPDATE command to modify the data in the MySQL table −

以下代码块具有UPDATE命令的通用SQL语法,用于修改MySQL表中的数据-


UPDATE table_name SET field1 = new-value1, field2 = new-value2
[WHERE Clause]

  • You can update one or more field altogether.您可以总共更新一个或多个字段。
  • You can specify any condition using the WHERE clause.您可以使用WHERE子句指定任何条件。
  • You can update the values in a single table at a time.您可以一次更新一个表中的值。

The WHERE clause is very useful when you want to update the selected rows in a table.

当您要更新表中的选定行时,WHERE子句非常有用。

从命令提示符更新数据 (Updating Data from the Command Prompt)

This will use the SQL UPDATE command with the WHERE clause to update the selected data in the MySQL table tutorials_tbl.

这将使用带有WHERE子句SQL UPDATE命令来更新MySQL表tutorials_tbl中的选定数据。

例 (Example)

The following example will update the tutorial_title field for a record having the tutorial_id as 3.

以下示例将更新tutorial_id为3的记录的tutorial_title字段。


root@host# mysql -u root -p password;
Enter password:*******mysql> use TUTORIALS;
Database changedmysql> UPDATE tutorials_tbl -> SET tutorial_title = 'Learning JAVA' -> WHERE tutorial_id = 3;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1  Changed: 1  Warnings: 0mysql>

使用PHP脚本更新数据 (Updating Data Using a PHP Script)

You can use the SQL UPDATE command with or without the WHERE CLAUSE into the PHP function – mysql_query(). This function will execute the SQL command in a similar way it is executed at the mysql> prompt.

您可以在SQL函数mysql_query()中使用带有或不带有WHERE子句SQL UPDATE命令。 该函数将以与在mysql>提示符下执行的类似方式执行SQL命令。

例 (Example)

The following example to update the tutorial_title field for a record having tutorial_id as 3.

以下示例更新了tutorial_id为3的记录的tutorial_title字段。


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}$sql = 'UPDATE tutorials_tblSET tutorial_title="Learning JAVA"WHERE tutorial_id=3';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not update data: ' . mysql_error());}echo "Updated data successfully\n";mysql_close($conn);
?>

MySQL-删除查询 (MySQL - DELETE Query)

If you want to delete a record from any MySQL table, then you can use the SQL command DELETE FROM. You can use this command at the mysql> prompt as well as in any script like PHP.

如果要从任何MySQL表中删除记录,则可以使用SQL命令DELETE FROM 。 您可以在mysql>提示符以及任何脚本(如PHP)中使用此命令。

句法 (Syntax)

The following code block has a generic SQL syntax of the DELETE command to delete data from a MySQL table.

以下代码块具有DELETE命令的通用SQL语法,用于从MySQL表中删除数据。


DELETE FROM table_name [WHERE Clause]

  • If the WHERE clause is not specified, then all the records will be deleted from the given MySQL table.

    如果未指定WHERE子句,则将从给定MySQL表中删除所有记录。

  • You can specify any condition using the WHERE clause.

    您可以使用WHERE子句指定任何条件。

  • You can delete records in a single table at a time.

    您可以一次删除单个表中的记录。

The WHERE clause is very useful when you want to delete selected rows in a table.

当您要删除表中的选定行时,WHERE子句非常有用。

从命令提示符中删除数据 (Deleting Data from the Command Prompt)

This will use the SQL DELETE command with the WHERE clause to delete selected data into the MySQL table – tutorials_tbl.

这将使用带有WHERE子句SQL DELETE命令将所选数据删除到MySQL表– tutorials_tbl中

例 (Example)

The following example will delete a record from the tutorial_tbl whose tutorial_id is 3.

以下示例将从tutorial_tbl中删除其tutorial_id为3的记录。


root@host# mysql -u root -p password;
Enter password:*******mysql> use TUTORIALS;
Database changedmysql> DELETE FROM tutorials_tbl WHERE tutorial_id=3;
Query OK, 1 row affected (0.23 sec)mysql>

使用PHP脚本删除数据 (Deleting Data Using a PHP Script)

You can use the SQL DELETE command with or without the WHERE CLAUSE into the PHP function – mysql_query(). This function will execute the SQL command in the same way as it is executed at the mysql> prompt.

您可以在SQL函数mysql_query()中使用带有或不带有WHERE子句SQL DELETE命令。 该函数将以与在mysql>提示符下执行的相同方式执行SQL命令。

例 (Example)

Try the following example to delete a record from the tutorial_tbl whose tutorial_id is 3.

请尝试以下示例从tutorial_id为3的tutorial_tbl中删除一条记录。


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}$sql = 'DELETE FROM tutorials_tbl WHERE tutorial_id = 3';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not delete data: ' . mysql_error());}echo "Deleted data successfully\n";mysql_close($conn);
?>

MySQL-赞子句 (MySQL - LIKE Clause)

We have seen the SQL SELECT command to fetch data from the MySQL table. We can also use a conditional clause called as the WHERE clause to select the required records.

我们已经看到了SQL SELECT命令从MySQL表中获取数据。 我们还可以使用称为WHERE子句的条件子句来选择所需的记录。

A WHERE clause with the ‘equal to’ sign (=) works fine where we want to do an exact match. Like if "tutorial_author = 'Sanjay'". But there may be a requirement where we want to filter out all the results where tutorial_author name should contain "jay". This can be handled using SQL LIKE Clause along with the WHERE clause.

WHERE子句带有“等于”符号(=)的地方可以正常工作。 就像“ tutorial_author ='Sanjay'”一样。 但是在某些情况下可能需要过滤掉所有结果,其中tutorial_author名称应包含“ jay”。 可以使用SQL LIKE子句和WHERE子句来处理。

If the SQL LIKE clause is used along with the % character, then it will work like a meta character (*) as in UNIX, while listing out all the files or directories at the command prompt. Without a % character, the LIKE clause is very same as the equal to sign along with the WHERE clause.

如果将SQL LIKE子句与%字符一起使用,则它将在UNIX中像元字符(*)一样工作,同时在命令提示符下列出所有文件或目录。 没有%字符,LIKE子句与等于符号以及WHERE子句非常相似。

句法 (Syntax)

The following code block has a generic SQL syntax of the SELECT command along with the LIKE clause to fetch data from a MySQL table.

以下代码块具有SELECT命令的通用SQL语法以及LIKE子句,用于从MySQL表中获取数据。


SELECT field1, field2,...fieldN table_name1, table_name2...
WHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'

  • You can specify any condition using the WHERE clause.

    您可以使用WHERE子句指定任何条件。

  • You can use the LIKE clause along with the WHERE clause.

    您可以将LIKE子句与WHERE子句一起使用。

  • You can use the LIKE clause in place of the equals to sign.

    您可以使用LIKE子句代替等于符号。

  • When LIKE is used along with % sign then it will work like a meta character search.

    当LIKE与%符号一起使用时,它将像元字符搜索一样工作。

  • You can specify more than one condition using AND or OR operators.

    您可以使用ANDOR运算符指定多个条件。

  • A WHERE...LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition.

    WHERE ... LIKE子句可以与DELETE或UPDATE SQL命令一起使用,还可以指定条件。

在命令提示符处使用LIKE子句 (Using the LIKE clause at the Command Prompt)

This will use the SQL SELECT command with the WHERE...LIKE clause to fetch the selected data from the MySQL table – tutorials_tbl.

这将使用带有WHERE ... LIKE子句SQL SELECT命令从MySQL表– tutorials_tbl中获取所选数据。

例 (Example)

The following example will return all the records from the tutorials_tbl table for which the author name ends with jay

以下示例将返回tutorials_tbl表中所有记录的作者姓名以jay结尾的记录-


root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl -> WHERE tutorial_author LIKE '%jay';
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
|      3      |  JAVA Tutorial |     Sanjay      |    2007-05-21   |
+-------------+----------------+-----------------+-----------------+
1 rows in set (0.01 sec)mysql>

在PHP脚本中使用LIKE子句 (Using LIKE clause inside PHP Script)

You can use similar syntax of the WHERE...LIKE clause into the PHP function – mysql_query(). This function is used to execute the SQL command and later another PHP function – mysql_fetch_array() can be used to fetch all the selected data, if the WHERE...LIKE clause is used along with the SELECT command.

您可以在PHP函数mysql_query()中使用类似WHERE ... LIKE子句的语法。 如果WHERE ... LIKE子句与SELECT命令一起使用,则此函数用于执行SQL命令,然后再执行另一个PHP函数– mysql_fetch_array()可用于获取所有选定的数据。

But if the WHERE...LIKE clause is being used with the DELETE or UPDATE command, then no further PHP function call is required.

但是,如果WHERE ... LIKE子句与DELETE或UPDATE命令一起使用,则不需要进一步PHP函数调用。

例 (Example)

Try out the following example to return all the records from the tutorials_tbl table for which the author name contains jay

尝试以下示例,以从authors_tbl表中返回其作者名称包含jay的所有记录-


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_dateFROM tutorials_tblWHERE tutorial_author LIKE "%jay%"';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not get data: ' . mysql_error());}while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {echo "Tutorial ID :{$row['tutorial_id']}  <br> "."Title: {$row['tutorial_title']} <br> "."Author: {$row['tutorial_author']} <br> "."Submission Date : {$row['submission_date']} <br> "."--------------------------------<br>";} echo "Fetched data successfully\n";mysql_close($conn);
?>

MySQL-排序结果 (MySQL - Sorting Results)

We have seen the SQL SELECT command to fetch data from a MySQL table. When you select rows, the MySQL server is free to return them in any order, unless you instruct it otherwise by saying how to sort the result. But, you sort a result set by adding an ORDER BY clause that names the column or columns which you want to sort.

我们已经看到了SQL SELECT命令从MySQL表中获取数据。 当您选择行时,MySQL服务器可以自由以任何顺序返回它们,除非您通过说出如何对结果排序来另外指示。 但是,您可以通过添加一个ORDER BY子句对结果集进行排序,该子句为要排序的一个或多个列命名。

句法 (Syntax)

The following code block is a generic SQL syntax of the SELECT command along with the ORDER BY clause to sort the data from a MySQL table.

以下代码块是SELECT命令的通用SQL语法,以及用于对MySQL表中的数据进行排序的ORDER BY子句。


SELECT field1, field2,...fieldN table_name1, table_name2...
ORDER BY field1, [field2...] [ASC [DESC]]

  • You can sort the returned result on any field, if that field is being listed out.

    如果列出了该字段,则可以在任何字段上对返回的结果进行排序。

  • You can sort the result on more than one field.

    您可以在多个字段上对结果进行排序。

  • You can use the keyword ASC or DESC to get result in ascending or descending order. By default, it's the ascending order.

    您可以使用关键字ASC或DESC来获得结果的升序或降序。 默认情况下,这是升序。

  • You can use the WHERE...LIKE clause in the usual way to put a condition.

    您可以按常规方式使用WHERE ... LIKE子句来放置条件。

在命令提示符处使用ORDER BY子句 (Using ORDER BY clause at the Command Prompt)

This will use the SQL SELECT command with the ORDER BY clause to fetch data from the MySQL table – tutorials_tbl.

这将使用带有SELECT ORDER BY子句SQL SELECT命令从MySQL表– tutorials_tbl中获取数据。

例 (Example)

Try out the following example, which returns the result in an ascending order.

尝试以下示例,该示例以升序返回结果。


root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl ORDER BY tutorial_author ASC
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
|      2      |  Learn MySQL   |     Abdul S     |    2007-05-24   |
|      1      |   Learn PHP    |    John Poul    |    2007-05-24   |
|      3      | JAVA Tutorial  |     Sanjay      |    2007-05-06   |
+-------------+----------------+-----------------+-----------------+
3 rows in set (0.42 sec)mysql>

Verify all the author names that are listed out in the ascending order.

验证以升序列出的所有作者姓名。

在PHP脚本中使用ORDER BY子句 (Using ORDER BY clause inside a PHP Script)

You can use a similar syntax of the ORDER BY clause into the PHP function – mysql_query(). This function is used to execute the SQL command and later another PHP function mysql_fetch_array() can be used to fetch all the selected data.

您可以在PHP函数mysql_query()中使用类似ORDER BY子句的语法。 该函数用于执行SQL命令,以后可以使用另一个PHP函数mysql_fetch_array()来获取所有选定的数据。

例 (Example)

Try out the following example, which returns the result in a descending order of the tutorial authors.

尝试以下示例,该示例按教程作者的降序返回结果。


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_dateFROM tutorials_tblORDER BY  tutorial_author DESC';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not get data: ' . mysql_error());}while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {echo "Tutorial ID :{$row['tutorial_id']}  <br> "."Title: {$row['tutorial_title']} <br> "."Author: {$row['tutorial_author']} <br> "."Submission Date : {$row['submission_date']} <br> "."--------------------------------<br>";} echo "Fetched data successfully\n";mysql_close($conn);
?>

使用MySQl联接 (Using MySQl Joins)

In the previous chapters, we were getting data from one table at a time. This is good enough for simple takes, but in most of the real world MySQL usages, you will often need to get data from multiple tables in a single query.

在前面的章节中,我们一次从一个表中获取数据。 这足以满足简单需要,但是在大多数实际MySQL使用中,您通常需要在单个查询中从多个表中获取数据。

You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table.

您可以在单个SQL查询中使用多个表。 MySQL中的联接行为是指将两个或多个表粉碎为一个表。

You can use JOINS in the SELECT, UPDATE and DELETE statements to join the MySQL tables. We will see an example of the LEFT JOIN also which is different from the simple MySQL JOIN.

您可以在SELECT,UPDATE和DELETE语句中使用JOINS来联接MySQL表。 我们还将看到LEFT JOIN的示例,它与简单MySQL JOIN不同。

在命令提示符下使用联接 (Using Joins at the Command Prompt)

Assume we have two tables tcount_tbl and tutorials_tbl, in TUTORIALS. Now take a look at the examples given below −

假设我们在TUTORIALS中有两个表tcount_tbltutorials_tbl 。 现在看看下面给出的示例-

例 (Example)

The following examples −

以下示例-


root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * FROM tcount_tbl;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
|      mahran     |       20       |
|      mahnaz     |      NULL      |
|       Jen       |      NULL      |
|      Gill       |       20       |
|    John Poul    |        1       |
|     Sanjay      |        1       |
+-----------------+----------------+
6 rows in set (0.01 sec)
mysql> SELECT * from tutorials_tbl;
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
|      1      |  Learn PHP     |     John Poul   |    2007-05-24   |
|      2      |  Learn MySQL   |      Abdul S    |    2007-05-24   |
|      3      | JAVA Tutorial  |      Sanjay     |    2007-05-06   |
+-------------+----------------+-----------------+-----------------+
3 rows in set (0.00 sec)
mysql>

Now we can write an SQL query to join these two tables. This query will select all the authors from table tutorials_tbl and will pick up the corresponding number of tutorials from the tcount_tbl.

现在我们可以编写一个SQL查询来连接这两个表。 该查询将从表tutorials_tbl中选择所有作者,并从tcount_tbl中选择相应数量的教程。


mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count-> FROM tutorials_tbl a, tcount_tbl b-> WHERE a.tutorial_author = b.tutorial_author;
+-------------+-----------------+----------------+
| tutorial_id | tutorial_author | tutorial_count |
+-------------+-----------------+----------------+
|      1      |    John Poul    |        1       |
|      3      |     Sanjay      |        1       |
+-------------+-----------------+----------------+
2 rows in set (0.01 sec)
mysql>

在PHP脚本中使用联接 (Using Joins in a PHP Script)

You can use any of the above-mentioned SQL query in the PHP script. You only need to pass the SQL query into the PHP function mysql_query() and then you will fetch results in the usual way.

您可以在PHP脚本中使用任何上述SQL查询。 您只需要将SQL查询传递到PHP函数mysql_query()中 ,然后将以通常的方式获取结果。

例 (Example)

The following example −

以下示例-


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}$sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_countFROM tutorials_tbl a, tcount_tbl bWHERE a.tutorial_author = b.tutorial_author';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not get data: ' . mysql_error());}while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {echo "Author:{$row['tutorial_author']}  <br> "."Count: {$row['tutorial_count']} <br> "."Tutorial ID: {$row['tutorial_id']} <br> "."--------------------------------<br>";} echo "Fetched data successfully\n";mysql_close($conn);
?>

MySQL左联接 (MySQL LEFT JOIN)

A MySQL left join is different from a simple join. A MySQL LEFT JOIN gives some extra consideration to the table that is on the left.

MySQL左联接不同于简单联接。 MySQL LEFT JOIN对左侧的表进行了一些额外的考虑。

If I do a LEFT JOIN, I get all the records that match in the same way and IN ADDITION I get an extra record for each unmatched record in the left table of the join: thus ensuring (in my example) that every AUTHOR gets a mention.

如果我执行LEFT JOIN ,我将以相同的方式获得所有匹配的记录,并且在连接的左表中,对于每个不匹配的记录,我还将获得一个额外的记录:因此,确保(在我的示例中)每个AUTHOR都获得一个提到。

例 (Example)

Try the following example to understand the LEFT JOIN.

请尝试以下示例,以了解LEFT JOIN。


root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count-> FROM tutorials_tbl a LEFT JOIN tcount_tbl b-> ON a.tutorial_author = b.tutorial_author;
+-------------+-----------------+----------------+
| tutorial_id | tutorial_author | tutorial_count |
+-------------+-----------------+----------------+
|      1      |    John Poul    |       1        |
|      2      |     Abdul S     |      NULL      |
|      3      |     Sanjay      |       1        |
+-------------+-----------------+----------------+
3 rows in set (0.02 sec)

You would need to do more practice to become familiar with JOINS. This is slightly a bit complex concept in MySQL/SQL and will become more clear while doing real examples.

您需要做更多的练习才能熟悉JOINS。 这在MySQL / SQL中有点复杂,在做实际示例时会更加清楚。

处理MySQL NULL值 (Handling MySQL NULL Values)

We have seen the SQL SELECT command along with the WHERE clause to fetch data from a MySQL table, but when we try to give a condition, which compares the field or the column value to NULL, it does not work properly.

我们已经看到了SQL SELECT命令和WHERE子句,以便从MySQL表中获取数据,但是当我们尝试给出一个条件,该条件将字段或列的值与NULL进行比较时,它不能正常工作。

To handle such a situation, MySQL provides three operators −

为了处理这种情况,MySQL提供了三个运算符-

  • IS NULL − This operator returns true, if the column value is NULL.

    IS NULL-如果列值为NULL,则此运算符返回true。

  • IS NOT NULL − This operator returns true, if the column value is not NULL.

    IS NOT NULL-如果列值不为NULL,则此运算符返回true。

  • <=> − This operator compares values, which (unlike the = operator) is true even for two NULL values.

    <=> -此运算符比较值(与=运算符不同),即使对于两个NULL值也是如此。

The conditions involving NULL are special. You cannot use = NULL or != NULL to look for NULL values in columns. Such comparisons always fail because it is impossible to tell whether they are true or not. Sometimes, even NULL = NULL fails.

涉及NULL的条件是特殊的。 您不能使用= NULL或!= NULL在列中查找NULL值。 这样的比较总是失败的,因为无法判断它们是否正确。 有时,即使NULL = NULL也会失败。

To look for columns that are or are not NULL, use IS NULL or IS NOT NULL.

要查找是否为NULL的列,请使用IS NULLIS NOT NULL

在命令提示符处使用NULL值 (Using NULL values at the Command Prompt)

Assume that there is a table called tcount_tbl in the TUTORIALS database and it contains two columns namely tutorial_author and tutorial_count, where a NULL tutorial_count indicates that the value is unknown.

假定在TUTORIALS数据库中有一个名为tcount_tbl的表,它包含两列,即tutorial_authortutorial_count ,其中NULL tutorial_count表示该值未知。

例 (Example)

Try the following examples −

尝试以下示例-


root@host# mysql -u root -p password;
Enter password:*******mysql> use TUTORIALS;
Database changedmysql> create table tcount_tbl-> (-> tutorial_author varchar(40) NOT NULL,-> tutorial_count  INT-> );
Query OK, 0 rows affected (0.05 sec)mysql> INSERT INTO tcount_tbl-> (tutorial_author, tutorial_count) values ('mahran', 20);mysql> INSERT INTO tcount_tbl-> (tutorial_author, tutorial_count) values ('mahnaz', NULL);mysql> INSERT INTO tcount_tbl-> (tutorial_author, tutorial_count) values ('Jen', NULL);mysql> INSERT INTO tcount_tbl-> (tutorial_author, tutorial_count) values ('Gill', 20);mysql> SELECT * from tcount_tbl;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
|     mahran      |       20       |
|     mahnaz      |      NULL      |
|      Jen        |      NULL      |
|     Gill        |       20       |
+-----------------+----------------+
4 rows in set (0.00 sec)mysql>

You can see that = and != do not work with NULL values as follows −

您可以看到=和!=不适用于NULL值,如下所示-


mysql> SELECT * FROM tcount_tbl WHERE tutorial_count = NULL;
Empty set (0.00 sec)mysql> SELECT * FROM tcount_tbl WHERE tutorial_count != NULL;
Empty set (0.01 sec)

To find the records where the tutorial_count column is or is not NULL, the queries should be written as shown in the following program.

要查找tutorial_count列为NULL或不为NULL的记录,应按以下程序所示编写查询。


mysql> SELECT * FROM tcount_tbl -> WHERE tutorial_count IS NULL;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
|     mahnaz      |      NULL      |
|      Jen        |      NULL      |
+-----------------+----------------+
2 rows in set (0.00 sec)
mysql> SELECT * from tcount_tbl -> WHERE tutorial_count IS NOT NULL;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
|     mahran      |       20       |
|     Gill        |       20       |
+-----------------+----------------+
2 rows in set (0.00 sec)

在PHP脚本中处理NULL值 (Handling NULL Values in a PHP Script)

You can use the if...else condition to prepare a query based on the NULL value.

您可以使用if ... else条件根据NULL值准备查询。

例 (Example)

The following example takes the tutorial_count from outside and then compares it with the value available in the table.

以下示例从外部获取tutorial_count ,然后将其与表中的可用值进行比较。


<?php$dbhost = 'localhost:3036';$dbuser = 'root';$dbpass = 'rootpassword';$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ) {die('Could not connect: ' . mysql_error());}if( isset($tutorial_count )) {$sql = 'SELECT tutorial_author, tutorial_countFROM  tcount_tblWHERE tutorial_count = $tutorial_count';} else {$sql = 'SELECT tutorial_author, tutorial_countFROM  tcount_tblWHERE tutorial_count IS $tutorial_count';}mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ) {die('Could not get data: ' . mysql_error());}while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {echo "Author:{$row['tutorial_author']}  <br> "."Count: {$row['tutorial_count']} <br> "."--------------------------------<br>";} echo "Fetched data successfully\n";mysql_close($conn);
?>

MySQL-正则表达式 (MySQL - Regexps)

You have seen MySQL pattern matching with LIKE ...%. MySQL supports another type of pattern matching operation based on the regular expressions and the REGEXP operator. If you are aware of PHP or PERL, then it is very simple for you to understand because this matching is same like those scripting the regular expressions.

您已经看到与LIKE ...%匹配MySQL模式。 MySQL支持基于正则表达式和REGEXP运算符的另一种模式匹配操作。 如果您了解PHP或PERL,那么对您来说很简单,因为这种匹配与对正则表达式进行脚本编写的方式相同。

Following is the table of pattern, which can be used along with the REGEXP operator.

以下是模式表,可以与REGEXP运算符一起使用。

Pattern What the pattern matches
^ Beginning of string
$ End of string
. Any single character
[...] Any character listed between the square brackets
[^...] Any character not listed between the square brackets
p1|p2|p3 Alternation; matches any of the patterns p1, p2, or p3
* Zero or more instances of preceding element
+ One or more instances of preceding element
{n} n instances of preceding element
{m,n} m through n instances of preceding element
模式 模式匹配什么
^ 字符串开头
$ 字符串结尾
任何单个字符
[...] 方括号之间列出的任何字符
[^ ...] 方括号之间未列出的任何字符
p1 | p2 | p3 交替; 匹配任何模式p1,p2或p3
* 零个或多个前一元素的实例
+ 前一个元素的一个或多个实例
{n} n个先前元素的实例
{m,n} m至n个先前元素的实例

例子 (Examples)

Now based on above table, you can device various type of SQL queries to meet your requirements. Here, I am listing a few for your understanding.

现在,基于上表,您可以配置各种类型SQL查询以满足您的要求。 在这里,我列出一些供您理解。

Consider we have a table called person_tbl and it is having a field called name

考虑我们有一个名为person_tbl的表,它有一个名为name的字段-

Query to find all the names starting with 'st'

查询以'st'开头的所有名称-


mysql> SELECT name FROM person_tbl WHERE name REGEXP '^st';

Query to find all the names ending with 'ok'

查询以找到所有以'ok'结尾的名称-


mysql> SELECT name FROM person_tbl WHERE name REGEXP 'ok$';

Query to find all the names, which contain 'mar'

查询以查找所有包含“ mar”的名称-


mysql> SELECT name FROM person_tbl WHERE name REGEXP 'mar';

Query to find all the names starting with a vowel and ending with 'ok'

查询以找到所有以元音开头并以'ok'结尾的名称-


mysql> SELECT FirstName FROM intque.person_tbl WHERE FirstName REGEXP '^[aeiou].*ok$';

MySQL-交易 (MySQL - Transactions)

A transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will never be complete unless each individual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail.

事务是一组顺序的数据库操作,它们被当作一个单独的工作单元执行。 换句话说,除非组中的每个单独操作成功,否则交易将永远不会完成。 如果事务中的任何操作失败,则整个事务将失败。

Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction.

实际上,您会将许多SQL查询组成一个组,并将它们全部作为事务的一部分一起执行。

交易性质 (Properties of Transactions)

Transactions have the following four standard properties, usually referred to by the acronym ACID

事务具有以下四个标准属性,通常由首字母缩写ACID引用-

  • Atomicity − This ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state.

    原子性 -确保工作单元内的所有操作均成功完成; 否则,事务将在失败点中止,并且先前的操作将回滚到它们以前的状态。

  • Consistency − This ensures that the database properly changes states upon a successfully committed transaction.

    一致性 -这可以确保数据库在成功提交事务后正确更改状态。

  • Isolation − This enables transactions to operate independently on and transparent to each other.

    隔离 -这使事务能够独立运行并且彼此透明。

  • Durability − This ensures that the result or effect of a committed transaction persists in case of a system failure.

    持久性 -这样可以确保在系统故障的情况下,持续执行已提交事务的结果或效果。

In MySQL, the transactions begin with the statement BEGIN WORK and end with either a COMMIT or a ROLLBACK statement. The SQL commands between the beginning and ending statements form the bulk of the transaction.

在MySQL中,事务以BEGIN WORK语句开始,以COMMITROLLBACK语句结束。 开头和结尾语句之间SQL命令构成了事务的主体。

提交和回滚 (COMMIT and ROLLBACK)

These two keywords Commit and Rollback are mainly used for MySQL Transactions.

这两个关键字CommitRollback主要用于MySQL Transactions。

  • When a successful transaction is completed, the COMMIT command should be issued so that the changes to all involved tables will take effect.

    成功完成事务后,应发出COMMIT命令,以便对所有涉及的表所做的更改都将生效。

  • If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the transaction to its previous state.

    如果发生故障,则应发出ROLLBACK命令以使事务中引用的每个表返回其先前状态。

You can control the behavior of a transaction by setting session variable called AUTOCOMMIT. If AUTOCOMMIT is set to 1 (the default), then each SQL statement (within a transaction or not) is considered a complete transaction and committed by default when it finishes.

您可以通过设置名为AUTOCOMMIT的会话变量来控制事务的行为。 如果AUTOCOMMIT设置为1(默认值),则每个SQL语句(无论是否在事务中)都被视为完整事务,并在完成时默认情况下提交。

When AUTOCOMMIT is set to 0, by issuing the SET AUTOCOMMIT = 0 command, the subsequent series of statements acts like a transaction and no activities are committed until an explicit COMMIT statement is issued.

当AUTOCOMMIT设置为0时,通过发出SET AUTOCOMMIT = 0命令,随后的一系列语句就像一个事务,并且在发出明确的COMMIT语句之前,不会提交任何活动。

You can execute these SQL commands in PHP by using the mysql_query() function.

您可以使用mysql_query()函数在PHP中执行这些SQL命令。

交易的一般例子 (A Generic Example on Transaction)

This sequence of events is independent of the programming language used. The logical path can be created in whichever language you use to create your application.

事件的顺序与所使用的编程语言无关。 可以使用用于创建应用程序的任何语言来创建逻辑路径。

You can execute these SQL commands in PHP by using the mysql_query() function.

您可以使用mysql_query()函数在PHP中执行这些SQL命令。

  • Begin transaction by issuing the SQL command BEGIN WORK.

    通过发出SQL命令BEGIN WORK开始事务。

  • Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE.

    发出一个或多个SQL命令,例如SELECT,INSERT,UPDATE或DELETE。

  • Check if there is no error and everything is according to your requirement.

    检查是否没有错误,一切都根据您的要求。

  • If there is any error, then issue a ROLLBACK command, otherwise issue a COMMIT command.

    如果有任何错误,则发出ROLLBACK命令,否则发出COMMIT命令。

MySQL中的交易安全表类型 (Transaction-Safe Table Types in MySQL)

You cannot use transactions directly, but for certain exceptions you can. However, they are not safe and guaranteed. If you plan to use transactions in your MySQL programming, then you need to create your tables in a special way. There are many types of tables, which support transactions, but the most popular one is InnoDB.

您不能直接使用事务,但是可以使用某些例外情况。 但是,它们并不安全且不能保证。 如果计划在MySQL编程中使用事务,则需要以特殊方式创建表。 表有很多类型,它们支持事务,但是最流行的一种是InnoDB

Support for InnoDB tables requires a specific compilation parameter when compiling MySQL from the source. If your MySQL version does not have InnoDB support, ask your Internet Service Provider to build a version of MySQL with support for InnoDB table types or download and install the MySQL-Max Binary Distribution for Windows or Linux/UNIX and work with the table type in a development environment.

从源编译MySQL时,对InnoDB表的支持需要特定的编译参数。 如果您MySQL版本不支持InnoDB,请要求您的Internet服务提供商构建一个支持InnoDB表类型MySQL版本,或者下载并安装适用于Windows或Linux / UNIX的MySQL-Max Binary Distribution ,并在其中使用该表类型。开发环境。

If your MySQL installation supports InnoDB tables, simply add a TYPE = InnoDB definition to the table creation statement.

如果您MySQL安装支持InnoDB表,只需在表创建语句中添加TYPE = InnoDB定义。

For example, the following code creates an InnoDB table called tcount_tbl

例如,以下代码创建一个名为tcount_tbl的InnoDB表-


root@host# mysql -u root -p password;
Enter password:*******mysql> use TUTORIALS;
Database changedmysql> create table tcount_tbl-> (-> tutorial_author varchar(40) NOT NULL,-> tutorial_count  INT-> ) TYPE = InnoDB;
Query OK, 0 rows affected (0.05 sec)

For more details on InnoDB, you can click on the following link −InnoDB

有关InnoDB的更多详细信息,您可以单击以下链接-InnoDB

You can use other table types like GEMINI or BDB, but it depends on your installation, whether it supports these two table types or not.

您可以使用其他表类型,例如GEMINIBDB ,但它取决于您的安装,是否支持这两种表类型。

MySQL-ALTER命令 (MySQL - ALTER Command)

The MySQL ALTER command is very useful when you want to change a name of your table, any table field or if you want to add or delete an existing column in a table.

当您要更改表的名称,任何表字段或要添加或删除表中的现有列时,MySQL ALTER命令非常有用。

Let us begin with the creation of a table called testalter_tbl.

让我们从创建一个名为testalter_tbl的表开始


root@host# mysql -u root -p password;
Enter password:*******mysql> use TUTORIALS;
Database changedmysql> create table testalter_tbl-> (-> i INT,-> c CHAR(1)-> );
Query OK, 0 rows affected (0.05 sec)
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field |  Type   | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
|   i   | int(11) | YES  |     |   NULL  |       |
|   c   | char(1) | YES  |     |   NULL  |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

删除,添加或重新定位列 (Dropping, Adding or Repositioning a Column)

If you want to drop an existing column i from the above MySQL table, then you will use the DROP clause along with the ALTER command as shown below −

如果要从上面MySQL表中删除现有列i,则将使用DROP子句以及ALTER命令,如下所示-


mysql> ALTER TABLE testalter_tbl  DROP i;

A DROP clause will not work if the column is the only one left in the table.

如果列是表中剩下的唯一列,则DROP子句将不起作用。

To add a column, use ADD and specify the column definition. The following statement restores the i column to the testalter_tbl −

要添加列,请使用ADD并指定列定义。 以下语句将i列还原到testalter_tbl-


mysql> ALTER TABLE testalter_tbl ADD i INT;

After issuing this statement, testalter will contain the same two columns that it had when you first created the table, but will not have the same structure. This is because there are new columns that are added to the end of the table by default. So even though i originally was the first column in mytbl, now it is the last one.

发出此语句后,testalter将包含与您第一次创建表时相同的两列,但结构不会相同。 这是因为默认情况下,有新列添加到表的末尾。 因此,即使最初是mytbl中的第一列,但现在却是最后一列。


mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field |  Type   | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
|   c   | char(1) | YES  |     |   NULL  |       |
|   i   | int(11) | YES  |     |   NULL  |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

To indicate that you want a column at a specific position within the table, either use FIRST to make it the first column or AFTER col_name to indicate that the new column should be placed after the col_name.

要表明您希望在表中的特定位置上放置一列,请使用FIRST将其设为第一列,或者使用AFTER col_name指示将新列放置在col_name之后。

Try the following ALTER TABLE statements, using SHOW COLUMNS after each one to see what effect each one has −

尝试以下ALTER TABLE语句,在每个语句之后使用SHOW COLUMNS来查看每个语句有什么作用-


ALTER TABLE testalter_tbl DROP i;
ALTER TABLE testalter_tbl ADD i INT FIRST;
ALTER TABLE testalter_tbl DROP i;
ALTER TABLE testalter_tbl ADD i INT AFTER c;

The FIRST and AFTER specifiers work only with the ADD clause. This means that if you want to reposition an existing column within a table, you first must DROP it and then ADD it at the new position.

FIRST和AFTER说明符仅与ADD子句一起使用。 这意味着,如果要重新定位表中的现有列,则必须先删除它,然后再将其添加到新位置。

更改(更改)列定义或名称 (Altering (Changing) a Column Definition or a Name)

To change a column's definition, use MODIFY or CHANGE clause along with the ALTER command.

要更改列的定义,请使用MODIFYCHANGE子句以及ALTER命令。

For example, to change column c from CHAR(1) to CHAR(10), you can use the following command −

例如,要将列c从CHAR(1)更改为CHAR(10),可以使用以下命令-


mysql> ALTER TABLE testalter_tbl MODIFY c CHAR(10);

With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name the column you want to change, then specify the new definition, which includes the new name.

使用CHANGE ,语法有些不同。 在CHANGE关键字之后,为要更改的列命名,然后指定新定义,其中包括新名称。

Try out the following example −

尝试以下示例-


mysql> ALTER TABLE testalter_tbl CHANGE i j BIGINT;

If you now use CHANGE to convert j from BIGINT back to INT without changing the column name, the statement will be as shown below −

如果现在使用CHANGE在不更改列名的情况下将jBIGINT转换回INT ,该语句将如下所示-


mysql> ALTER TABLE testalter_tbl CHANGE j j INT;

The Effect of ALTER TABLE on Null and Default Value Attributes − When you MODIFY or CHANGE a column, you can also specify whether or not the column can contain NULL values and what its default value is. In fact, if you don't do this, MySQL automatically assigns values for these attributes.

ALTER TABLE对空值和默认值属性的影响 -修改或更改列时,您还可以指定该列是否可以包含NULL值及其默认值。 实际上,如果您不这样做,MySQL会自动为这些属性分配值。

The following code block is an example, where the NOT NULL column will have the value as 100 by default.

下面的代码块是一个示例,其中NOT NULL列的默认值将为100。


mysql> ALTER TABLE testalter_tbl -> MODIFY j BIGINT NOT NULL DEFAULT 100;

If you don't use the above command, then MySQL will fill up NULL values in all the columns.

如果您不使用上述命令,则MySQL将在所有列中填充NULL值。

更改(更改)列的默认值 (Altering (Changing) a Column's Default Value)

You can change a default value for any column by using the ALTER command.

您可以使用ALTER命令更改任何列的默认值。

Try out the following example.

试试下面的例子。


mysql> ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field |  Type   | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
|   c   | char(1) | YES  |     |   NULL  |       |
|   i   | int(11) | YES  |     |   1000  |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

You can remove the default constraint from any column by using DROP clause along with the ALTER command.

您可以使用DROP子句以及ALTER命令从任何列中删除默认约束。


mysql> ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field |  Type   | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
|   c   | char(1) | YES  |     |   NULL  |       |
|   i   | int(11) | YES  |     |   NULL  |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

更改(更改)表格类型 (Altering (Changing) a Table Type)

You can use a table type by using the TYPE clause along with the ALTER command. Try out the following example to change the testalter_tbl to MYISAM table type.

您可以通过将TYPE子句与ALTER命令一起使用来使用表类型。 尝试以下示例将testalter_tbl更改为MYISAM表类型。

To find out the current type of a table, use the SHOW TABLE STATUS statement.

要找出表的当前类型,请使用SHOW TABLE STATUS语句。


mysql> ALTER TABLE testalter_tbl TYPE = MYISAM;
mysql>  SHOW TABLE STATUS LIKE 'testalter_tbl'\G
*************************** 1. row ****************Name: testalter_tblType: MyISAMRow_format: FixedRows: 0Avg_row_length: 0Data_length: 0
Max_data_length: 25769803775Index_length: 1024Data_free: 0Auto_increment: NULLCreate_time: 2007-06-03 08:04:36Update_time: 2007-06-03 08:04:36Check_time: NULLCreate_options:Comment:
1 row in set (0.00 sec)

重命名(更改)表 (Renaming (Altering) a Table)

To rename a table, use the RENAME option of the ALTER TABLE statement.

要重命名表,请使用ALTER TABLE语句的RENAME选项。

Try out the following example to rename testalter_tbl to alter_tbl.

尝试以下示例将testalter_tbl重命名为alter_tbl


mysql> ALTER TABLE testalter_tbl RENAME TO alter_tbl;

You can use the ALTER command to create and drop the INDEX command on a MySQL file. We will discuss in detail about this command in the next chapter.

您可以使用ALTER命令在MySQL文件上创建和删除INDEX命令。 在下一章中,我们将详细讨论该命令。

MySQL-索引 (MySQL - INDEXES)

A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.

数据库索引是一种数据结构,可以提高表中操作的速度。 可以使用一个或多个列创建索引,这为快速随机查找和对记录访问的有效排序提供了基础。

While creating index, it should be taken into consideration which all columns will be used to make SQL queries and create one or more indexes on those columns.

创建索引时,应考虑将所有列都用于进行SQL查询并在这些列上创建一个或多个索引。

Practically, indexes are also a type of tables, which keep primary key or index field and a pointer to each record into the actual table.

实际上,索引也是表的一种,保留主键或索引字段以及指向实际表中每个记录的指针。

The users cannot see the indexes, they are just used to speed up queries and will be used by the Database Search Engine to locate records very fast.

用户看不到索引,它们仅用于加速查询,并且数据库搜索引擎将使用它们非常快速地定位记录。

The INSERT and UPDATE statements take more time on tables having indexes, whereas the SELECT statements become fast on those tables. The reason is that while doing insert or update, a database needs to insert or update the index values as well.

INSERT和UPDATE语句在具有索引的表上花费更多时间,而SELECT语句在那些表上变得很快。 原因是在进行插入或更新时,数据库也需要插入或更新索引值。

简单唯一索引 (Simple and Unique Index)

You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Here is the syntax to create an Index on a table.

您可以在表上创建唯一索引。 唯一索引意味着两行不能具有相同的索引值。 这是在表上创建索引的语法。


CREATE UNIQUE INDEX index_name ON table_name ( column1, column2,...);

You can use one or more columns to create an index.

您可以使用一个或多个列来创建索引。

For example, we can create an index on tutorials_tbl using tutorial_author.

例如,我们可以使用tutorial_authortutorials_tbl上创建索引。


CREATE UNIQUE INDEX AUTHOR_INDEX ON tutorials_tbl (tutorial_author)

You can create a simple index on a table. Just omit the UNIQUE keyword from the query to create a simple index. A Simple index allows duplicate values in a table.

您可以在表上创建一个简单的索引。 只需从查询中省略UNIQUE关键字即可创建一个简单的索引。 简单索引允许在表中重复值。

If you want to index the values in a column in a descending order, you can add the reserved word DESC after the column name.

如果要按降序索引列中的值,可以在列名后添加保留字DESC。


mysql> CREATE UNIQUE INDEX AUTHOR_INDEX ON tutorials_tbl (tutorial_author DESC)

ALTER命令添加和删除INDEX (ALTER command to add and drop INDEX)

There are four types of statements for adding indexes to a table −

有四种类型的语句可向表添加索引-

  • ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds a PRIMARY KEY, which means that the indexed values must be unique and cannot be NULL.

    ALTER TABLE tbl_name ADD PRIMARY KEY(column_list) -此语句添加了PRIMARY KEY ,这意味着索引值必须唯一且不能为NULL。

  • ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This statement creates an index for which the values must be unique (except for the NULL values, which may appear multiple times).

    ALTER TABLE tbl_name ADD UNIQUE index_name(column_list) -此语句创建一个索引,该索引的值必须唯一(NULL值除外,该值可能出现多次)。

  • ALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once.

    ALTER TABLE tbl_name添加索引index_name(column_list) -这将添加一个普通索引,其中任何值都可能出现多次。

  • ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes.

    ALTER TABLE tbl_name添加FULLTEXT index_name(column_list) -这将创建一个特殊的FULLTEXT索引,该索引用于文本搜索。

The following code block is an example to add index in an existing table.

以下代码块是在现有表中添加索引的示例。


mysql> ALTER TABLE testalter_tbl ADD INDEX (c);

You can drop any INDEX by using the DROP clause along with the ALTER command.

您可以使用DROP子句以及ALTER命令删除任何INDEX。

Try out the following example to drop the above-created index.

尝试以下示例删除上面创建的索引。


mysql> ALTER TABLE testalter_tbl DROP INDEX (c);

You can drop any INDEX by using the DROP clause along with the ALTER command.

您可以使用DROP子句以及ALTER命令删除任何INDEX。

ALTER命令添加和删除PRIMARY KEY (ALTER Command to add and drop the PRIMARY KEY)

You can add a primary key as well in the same way. But make sure the Primary Key works on columns, which are NOT NULL.

您也可以以相同的方式添加主键。 但是,请确保主键可以在非NULL的列上使用。

The following code block is an example to add the primary key in an existing table. This will make a column NOT NULL first and then add it as a primary key.

以下代码块是在现有表中添加主键的示例。 这将使列NOT NOT NULL首先出现,然后将其添加为主键。


mysql> ALTER TABLE testalter_tbl MODIFY i INT NOT NULL;
mysql> ALTER TABLE testalter_tbl ADD PRIMARY KEY (i);

You can use the ALTER command to drop a primary key as follows −

您可以使用ALTER命令来删除主键,如下所示:


mysql> ALTER TABLE testalter_tbl DROP PRIMARY KEY;

To drop an index that is not a PRIMARY KEY, you must specify the index name.

要删除不是PRIMARY KEY的索引,必须指定索引名称。

显示索引信息 (Displaying INDEX Information)

You can use the SHOW INDEX command to list out all the indexes associated with a table. The vertical-format output (specified by \G) often is useful with this statement, to avoid a long line wraparound −

您可以使用SHOW INDEX命令列出与表关联的所有索引。 垂直格式输出(由\ G指定)通常对于此语句很有用,以避免长行换行-

Try out the following example −

尝试以下示例-


mysql> SHOW INDEX FROM table_name\G
........

MySQL-临时表 (MySQL - Temporary Tables)

The temporary tables could be very useful in some cases to keep temporary data. The most important thing that should be known for temporary tables is that they will be deleted when the current client session terminates.

在某些情况下,临时表对于保留临时数据可能非常有用。 临时表应该知道的最重要的事情是,当当前客户端会话终止时,它们将被删除。

什么是临时表? (What are Temporary Tables?)

Temporary tables were added in the MySQL Version 3.23. If you use an older version of MySQL than 3.23, you cannot use the temporary tables, but you can use Heap Tables.

在MySQL 3.23版中添加了临时表。 如果您使用MySQL版本早于3.23,则不能使用临时表,但可以使用堆表

As stated earlier, temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQL database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table.

如前所述,临时表仅在会话处于活动状态时才持续存在。 如果您在PHP脚本中运行代码,则脚本执行完后,临时表将自动销毁。 如果您通过MySQL客户端程序连接到MySQL数据库服务器,则临时表将存在,直到您关闭客户端或手动销毁该表为止。

例 (Example)

The following program is an example showing you the usage of the temporary table. The same code can be used in PHP scripts using the mysql_query() function.

以下程序是一个示例,向您显示临时表的用法。 可以使用mysql_query()函数在PHP脚本中使用相同的代码。


mysql> CREATE TEMPORARY TABLE SalesSummary (-> product_name VARCHAR(50) NOT NULL-> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00-> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00-> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)mysql> INSERT INTO SalesSummary-> (product_name, total_sales, avg_unit_price, total_units_sold)-> VALUES-> ('cucumber', 100.25, 90, 2);mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
|   cucumber   |   100.25    |     90.00      |         2        |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)

When you issue a SHOW TABLES command, then your temporary table would not be listed out in the list. Now, if you will log out of the MySQL session and then you will issue a SELECT command, then you will find no data available in the database. Even your temporary table will not exist.

发出SHOW TABLES命令时,临时表不会在列表中列出。 现在,如果您要退出MySQL会话,然后发出SELECT命令,那么数据库中将找不到可用的数据。 甚至您的临时表也将不存在。

删除临时表 (Dropping Temporary Tables)

By default, all the temporary tables are deleted by MySQL when your database connection gets terminated. Still if you want to delete them in between, then you do so by issuing the DROP TABLE command.

默认情况下,当数据库连接终止时,MySQL将删除所有临时表。 仍然,如果要在它们之间删除它们,则可以通过发出DROP TABLE命令来删除它们。

The following program is an example on dropping a temporary table −

以下程序是删除临时表的示例-


mysql> CREATE TEMPORARY TABLE SalesSummary (-> product_name VARCHAR(50) NOT NULL-> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00-> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00-> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)mysql> INSERT INTO SalesSummary-> (product_name, total_sales, avg_unit_price, total_units_sold)-> VALUES-> ('cucumber', 100.25, 90, 2);mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
|   cucumber   |   100.25    |     90.00      |         2        |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
mysql> DROP TABLE SalesSummary;
mysql>  SELECT * FROM SalesSummary;
ERROR 1146: Table 'TUTORIALS.SalesSummary' doesn't exist

MySQL-克隆表 (MySQL - Clone Tables)

There may be a situation when you need an exact copy of a table and CREATE TABLE ... SELECT doesn't suit your purposes because the copy must include the same indexes, default values and so forth.

在某些情况下,您需要精确的表副本和CREATE TABLE ... SELECT不适合您的目的,因为该副本必须包含相同的索引,默认值等。

You can handle this situation by following the steps given below −

您可以按照以下步骤处理这种情况-

  • Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table's structure, indexes and all.

    使用SHOW CREATE TABLE获得一个CREATE TABLE语句,该语句指定源表的结构,索引和所有内容。

  • Modify the statement to change the table name to that of the clone table and execute the statement. This way, you will have the exact clone table.

    修改该语句以将表名更改为克隆表的名称,然后执行该语句。 这样,您将拥有确切的克隆表。

  • Optionally, if you need the table contents copied as well, issue an INSERT INTO ... SELECT statement, too.

    可选地,如果您还需要复制表内容,也可以发出INSERT INTO ... SELECT语句。

例 (Example)

Try out the following example to create a clone table for tutorials_tbl.

试用以下示例为tutorials_tbl创建一个克隆表。

Step 1 − Get the complete structure about the table.

步骤1-获取有关表的完整结构。


mysql> SHOW CREATE TABLE tutorials_tbl \G;
*************************** 1. row ***************************Table: tutorials_tbl
Create Table: CREATE TABLE `tutorials_tbl` (`tutorial_id` int(11) NOT NULL auto_increment,`tutorial_title` varchar(100) NOT NULL default '',`tutorial_author` varchar(40) NOT NULL default '',`submission_date` date default NULL,PRIMARY KEY  (`tutorial_id`),UNIQUE KEY `AUTHOR_INDEX` (`tutorial_author`)
) TYPE = MyISAM
1 row in set (0.00 sec)ERROR:
No query specified

Step 2 − Rename this table and create another table.

步骤2-重命名该表并创建另一个表。


mysql> CREATE TABLE clone_tbl (-> tutorial_id int(11) NOT NULL auto_increment,-> tutorial_title varchar(100) NOT NULL default '',-> tutorial_author varchar(40) NOT NULL default '',-> submission_date date default NULL,-> PRIMARY KEY  (tutorial_id),-> UNIQUE KEY AUTHOR_INDEX (tutorial_author)
-> ) TYPE = MyISAM;
Query OK, 0 rows affected (1.80 sec)

Step 3 − After executing step 2, you will create a clone table in your database. If you want to copy data from old table then you can do it by using INSERT INTO... SELECT statement.

步骤3-执行步骤2之后,您将在数据库中创建一个克隆表。 如果要从旧表中复制数据,则可以使用INSERT INTO ... SELECT语句来完成。


mysql> INSERT INTO clone_tbl (tutorial_id,-> tutorial_title,-> tutorial_author,-> submission_date)-> SELECT tutorial_id,tutorial_title,-> tutorial_author,submission_date-> FROM tutorials_tbl;
Query OK, 3 rows affected (0.07 sec)
Records: 3  Duplicates: 0  Warnings: 0

Finally, you will have an exact clone table as you wanted to have.

最后,您将拥有一个想要的精确克隆表。

MySQL-数据库信息 (MySQL - Database Info)

获取和使用MySQL元数据 (Obtaining and Using MySQL Metadata)

There are three types of information, which you would like to have from MySQL.

您希望从MySQL获得三种信息。

  • Information about the result of queries − This includes the number of records affected by any SELECT, UPDATE or DELETE statement.

    有关查询结果的信息 -这包括受任何SELECT,UPDATE或DELETE语句影响的记录数。

  • Information about the tables and databases − This includes information pertaining to the structure of the tables and the databases.

    有关表和数据库的信息-这包括与表和数据库的结构有关的信息。

  • Information about the MySQL server − This includes the status of the database server, version number, etc.

    有关MySQL服务器的信息 -这包括数据库服务器的状态,版本号等。

It is very easy to get all this information at the MySQL prompt, but while using PERL or PHP APIs, we need to call various APIs explicitly to obtain all this information.

在MySQL提示符下很容易获得所有这些信息,但是在使用PERL或PHP API时,我们需要显式调用各种AP​​I以获得所有这些信息。

获取查询影响的行数 (Obtaining the Number of Rows Affected by a Query)

Let is now see how to obtain this information.

现在让我们看看如何获​​取此信息。

PERL示例 (PERL Example)

In DBI scripts, the affected row count is returned by the do( ) or by the execute( ) command, depending on how you execute the query.

在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 Example)

In PHP, invoke the mysql_affected_rows( ) function to find out how many rows a query changed.

在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");

列出表和数据库 (Listing Tables and Databases)

It is very easy to list down all the databases and the tables available with a database server. Your result may be null if you don't have the sufficient privileges.

列出数据库服务器可用的所有数据库和表非常容易。 如果您没有足够的特权,则结果可能为null

Apart from the method which is shown in the following code block, you can use SHOW TABLES or SHOW DATABASES queries to get the list of tables or databases either in PHP or in PERL.

除了下面的代码块中显示的方法之外,您还可以使用SHOW TABLESSHOW DATABASES查询来获取PHP或PERL中的表或数据库列表。

PERL示例 (PERL Example)


# Get all the tables available in current database.
my @tables = $dbh->tables ( );foreach $table (@tables ){print "Table Name $table\n";
}

PHP示例 (PHP Example)


<?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);
?>

获取服务器元数据 (Getting Server Metadata)

There are a few important commands in MySQL which can be executed either at the MySQL prompt or by using any script like PHP to get various important information about the database server.

MySQL中有一些重要的命令,可以在MySQL提示符下执行,也可以使用任何脚本(如PHP)执行以获取有关数据库服务器的各种重要信息。

Sr.No. Command & Description
1

SELECT VERSION( )

Server version string

2

SELECT DATABASE( )

Current database name (empty if none)

3

SELECT USER( )

Current username

4

SHOW STATUS

Server status indicators

5

SHOW VARIABLES

Server configuration variables

序号 命令与说明
1个

选择版本()

服务器版本字符串

2

选择数据库()

当前数据库名称(如果没有则为空)

3

选择用户()

当前用户名

4

显示状态

服务器状态指示灯

5

显示变量

服务器配置变量

使用MySQL序列 (Using MySQL Sequences)

A sequence is a set of integers 1, 2, 3, ... that are generated in order on a specific demand. Sequences are frequently used in the databases because many applications require each row in a table to contain a unique value and sequences provide an easy way to generate them.

序列是一组整数1、2、3,...,它们是根据特定需求顺序生成的。 序列在数据库中经常使用,因为许多应用程序要求表中的每一行都包含唯一值,并且序列提供了一种生成它们的简便方法。

This chapter describes how to use sequences in MySQL.

本章介绍如何在MySQL中使用序列。

使用AUTO_INCREMENT列 (Using AUTO_INCREMENT Column)

The simplest way in MySQL to use Sequences is to define a column as AUTO_INCREMENT and leave the remaining things to MySQL to take care.

MySQL中使用Sequences的最简单方法是将一列定义为AUTO_INCREMENT ,并将其余内容留给MySQL照顾。

例 (Example)

Try out the following example. This will create table and after that it will insert few rows in this table where it is not required to give record ID because it is auto incremented by MySQL.

试试下面的例子。 这将创建表,此后将在该表中插入几行,无需提供记录ID,因为它由MySQL自动递增。


mysql> CREATE TABLE insect-> (-> id INT UNSIGNED NOT NULL AUTO_INCREMENT,-> PRIMARY KEY (id),-> name VARCHAR(30) NOT NULL, # type of insect-> date DATE NOT NULL, # date collected-> origin VARCHAR(30) NOT NULL # where collected
);
Query OK, 0 rows affected (0.02 sec)
mysql> INSERT INTO insect (id,name,date,origin) VALUES-> (NULL,'housefly','2001-09-10','kitchen'),-> (NULL,'millipede','2001-09-10','driveway'),-> (NULL,'grasshopper','2001-09-10','front yard');
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0
mysql> SELECT * FROM insect ORDER BY id;
+----+-------------+------------+------------+
| id |    name     |    date    |   origin   |
+----+-------------+------------+------------+
|  1 |  housefly   | 2001-09-10 |   kitchen  |
|  2 |  millipede  | 2001-09-10 |  driveway  |
|  3 | grasshopper | 2001-09-10 | front yard |
+----+-------------+------------+------------+
3 rows in set (0.00 sec)

获取AUTO_INCREMENT值 (Obtain AUTO_INCREMENT Values)

The LAST_INSERT_ID( ) is a SQL function, so you can use it from within any client that understands how to issue SQL statements. Otherwise, PERL and PHP scripts provide exclusive functions to retrieve the auto incremented value of the last record.

LAST_INSERT_ID()是SQL函数,因此您可以在任何了解如何发出SQL语句的客户端中使用它。 否则,PERL和PHP脚本提供排他功能来检索最后一条记录的自动递增值。

PERL示例 (PERL Example)

Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This attribute is accessed through either a database handle or a statement handle, depending on how you issue the query.

使用mysql_insertid属性获取查询生成的AUTO_INCREMENT值。 可通过数据库句柄或语句句柄访问此属性,具体取决于您发出查询的方式。

The following example references it through the database handle.

以下示例通过数据库句柄引用了它。


$dbh->do ("INSERT INTO insect (name,date,origin)
VALUES('moth','2001-09-14','windowsill')");
my $seq = $dbh->{mysql_insertid};

PHP示例 (PHP Example)

After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling the mysql_insert_id( ) command.

发出生成AUTO_INCREMENT值的查询后,通过调用mysql_insert_id()命令检索该值。


mysql_query ("INSERT INTO insect (name,date,origin)
VALUES('moth','2001-09-14','windowsill')", $conn_id);
$seq = mysql_insert_id ($conn_id);

重新编号现有序列 (Renumbering an Existing Sequence)

There may be a case when you have deleted many records from a table and you want to re-sequence all the records. This can be done by using a simple trick, but you should be very careful to do so if your table is having joins with the other table.

在某些情况下,您已经从表中删除了许多记录,并且想要对所有记录重新排序。 可以使用一个简单的技巧完成此操作,但是如果您的表与另一个表联接,则应非常小心。

If you determine that the resequencing of an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again.

如果确定不可避免要对AUTO_INCREMENT列进行重新排序,则要做的方法是从表中删除该列,然后再次添加它。

The following example shows how to renumber the id values in the table using this technique.

下面的示例演示如何使用此技术对表中的id值重新编号。


mysql> ALTER TABLE insect DROP id;
mysql> ALTER TABLE insect-> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,-> ADD PRIMARY KEY (id);

以特定值开始序列 (Starting a Sequence at a Particular Value)

By default, MySQL will start sequence from 1, but you can specify any other number as well at the time of the table creation.

默认情况下,MySQL将从1开始序列,但是您也可以在创建表时指定其他任何数字。

The following program is an example which shows how MySQL will start the sequence from 100.

以下程序是一个示例,显示了MySQL如何从100开始序列。


mysql> CREATE TABLE insect-> (-> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100,-> PRIMARY KEY (id),-> name VARCHAR(30) NOT NULL, # type of insect-> date DATE NOT NULL, # date collected-> origin VARCHAR(30) NOT NULL # where collected
);

Alternatively, you can create the table and then set the initial sequence value with the ALTER TABLE command.

或者,您可以创建表,然后使用ALTER TABLE命令设置初始序列值。


mysql> ALTER TABLE t AUTO_INCREMENT = 100;

MySQL-处理重复项 (MySQL - Handling Duplicates)

Generally, tables or result sets sometimes contain duplicate records. Most of the times it is allowed but sometimes it is required to stop duplicate records. It is required to identify duplicate records and remove them from the table. This chapter will describe how to prevent the occurrence of duplicate records in a table and how to remove the already existing duplicate records.

通常,表或结果集有时包含重复的记录。 在大多数情况下,它是允许的,但有时需要停止重复的记录。 需要标识重复的记录并将其从表中删除。 本章将介绍如何防止表中出现重复记录,以及如何删除已经存在的重复记录。

防止表中出现重复项 (Preventing Duplicates from Occurring in a Table)

You can use a PRIMARY KEY or a UNIQUE Index on a table with the appropriate fields to stop duplicate records.

您可以在具有适当字段的表上使用PRIMARY KEYUNIQUE索引来停止重复记录。

Let us take an example – The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name.

让我们举个例子–下表不包含此类索引或主键,因此它将允许重复记录first_namelast_name


CREATE TABLE person_tbl (first_name CHAR(20),last_name CHAR(20),sex CHAR(10)
);

To prevent multiple records with the same first and last name values from being created in this table, add a PRIMARY KEY to its definition. When you do this, it is also necessary to declare the indexed columns to be NOT NULL, because a PRIMARY KEY does not allow NULL values −

为了防止在此表中创建具有相同的名字和姓氏值的多个记录,请在其定义中添加一个PRIMARY KEY 。 这样做时,还必须声明索引列为NOT NULL ,因为PRIMARY KEY不允许NULL值-


CREATE TABLE person_tbl (first_name CHAR(20) NOT NULL,last_name CHAR(20) NOT NULL,sex CHAR(10),PRIMARY KEY (last_name, first_name)
);

The presence of a unique index in a table normally causes an error to occur if you insert a record into the table that duplicates an existing record in the column or columns that define the index.

如果在表中插入一条记录,该记录与定义索引的一个或多个列中的现有记录重复,则表中存在唯一索引通常会导致错误发生。

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

使用INSERT IGNORE命令而不是INSERT命令。 如果一条记录与现有记录不重复,则MySQL照常插入它。 如果记录是重复的,则IGNORE关键字告诉MySQL静默丢弃它而不会产生错误。

The following example does not error out and at the same time it will not insert duplicate records as well.

下面的示例不会出错,同时也不会插入重复的记录。


mysql> INSERT IGNORE INTO person_tbl (last_name, first_name)-> VALUES( 'Jay', 'Thomas');
Query OK, 1 row affected (0.00 sec)mysql> INSERT IGNORE INTO person_tbl (last_name, first_name)-> VALUES( 'Jay', 'Thomas');
Query OK, 0 rows affected (0.00 sec)

Use the REPLACE command rather than the INSERT command. If the record is new, it is inserted just as with INSERT. If it is a duplicate, the new record replaces the old one.

使用REPLACE命令而不是INSERT命令。 如果记录是新记录,则与INSERT一样插入。 如果重复,则新记录将替换旧记录。


mysql> REPLACE INTO person_tbl (last_name, first_name)-> VALUES( 'Ajay', 'Kumar');
Query OK, 1 row affected (0.00 sec)mysql> REPLACE INTO person_tbl (last_name, first_name)-> VALUES( 'Ajay', 'Kumar');
Query OK, 2 rows affected (0.00 sec)

The INSERT IGNORE and REPLACE commands should be chosen as per the duplicate-handling behavior you want to effect. The INSERT IGNORE command keeps the first set of the duplicated records and discards the remaining. The REPLACE command keeps the last set of duplicates and erases out any earlier ones.

应该根据要执行的重复处理行为来选择INSERT IGNORE和REPLACE命令。 INSERT IGNORE命令保留第一组重复的记录,并丢弃其余的记录。 REPLACE命令保留最后一组重复项,并清除所有较早的重复项。

Another way to enforce uniqueness is to add a UNIQUE index rather than a PRIMARY KEY to a table.

强制唯一性的另一种方法是向表中添加UNIQUE索引而不是PRIMARY KEY。


CREATE TABLE person_tbl (first_name CHAR(20) NOT NULL,last_name CHAR(20) NOT NULL,sex CHAR(10)UNIQUE (last_name, first_name)
);

计数和识别重复项 (Counting and Identifying Duplicates)

Following is the query to count duplicate records with first_name and last_name in a table.

以下是对表中具有first_name和last_name的重复记录进行计数的查询。


mysql> SELECT COUNT(*) as repetitions, last_name, first_name-> FROM person_tbl-> GROUP BY last_name, first_name-> HAVING repetitions > 1;

This query will return a list of all the duplicate records in the person_tbl table. In general, to identify sets of values that are duplicated, follow the steps given below.

该查询将返回person_tbl表中所有重复记录的列表。 通常,要标识重复的值集,请执行以下步骤。

  • Determine which columns contain the values that may be duplicated.

    确定哪些列包含可能重复的值。

  • List those columns in the column selection list, along with the COUNT(*).

    在列选择列表中列出这些列,以及COUNT(*)

  • List the columns in the GROUP BY clause as well.

    还要列出GROUP BY子句中的列。

  • Add a HAVING clause that eliminates the unique values by requiring the group counts to be greater than one.

    添加一个HAVING子句,该子句通过要求组计数大于1来消除唯一值。

从查询结果中消除重复 (Eliminating Duplicates from a Query Result)

You can use the DISTINCT command along with the SELECT statement to find out unique records available in a table.

您可以将DISTINCT命令与SELECT语句一起使用,以查找表中可用的唯一记录。


mysql> SELECT DISTINCT last_name, first_name-> FROM person_tbl-> ORDER BY last_name;

An alternative to the DISTINCT command is to add a GROUP BY clause that names the columns you are selecting. This has the effect of removing duplicates and selecting only the unique combinations of values in the specified columns.

DISTINCT命令的替代方法是添加一个GROUP BY子句,该子句命名您选择的列。 这具有删除重复项并仅选择指定列中值的唯一组合的效果。


mysql> SELECT last_name, first_name-> FROM person_tbl-> GROUP BY (last_name, first_name);

使用表替换删除重复项 (Removing Duplicates Using Table Replacement)

If you have duplicate records in a table and you want to remove all the duplicate records from that table, then follow the procedure given below.

如果表中有重复的记录,并且要从该表中删除所有重复的记录,请按照以下步骤进行操作。


mysql> CREATE TABLE tmp SELECT last_name, first_name, sex-> FROM person_tbl;-> GROUP BY (last_name, first_name);mysql> DROP TABLE person_tbl;
mysql> ALTER TABLE tmp RENAME TO person_tbl;

An easy way of removing duplicate records from a table is to add an INDEX or a PRIMARY KEY to that table. Even if this table is already available, you can use this technique to remove the duplicate records and you will be safe in future as well.

从表中删除重复记录的一种简单方法是将INDEX或PRIMARY KEY添加到该表。 即使此表已经可用,您也可以使用此技术删除重复的记录,以后也将很安全。


mysql> ALTER IGNORE TABLE person_tbl-> ADD PRIMARY KEY (last_name, first_name);

MySQL-和SQL注入 (MySQL - and SQL Injection)

If you take user input through a webpage and insert it into a MySQL database, there's a chance that you have left yourself wide open for a security issue known as SQL Injection. This chapter will teach you how to help prevent this from happening and help you secure your scripts and MySQL statements.

如果您通过网页获取用户输入并将其插入到MySQL数据库中,那么您就有可能对称为SQL Injection的安全问题敞开大门 。 本章将教您如何防止这种情况的发生并帮助您保护脚本和MySQL语句。

The SQL Injection usually occurs when you ask a user for input, like their name and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

SQL注入通常在您要求用户输入时发生,例如用户名,而不是用户名,而是给您一条MySQL语句,您将在不知不觉中在数据库上运行。

Never trust the data provided by a user, process this data only after validation; as a rule, this is done by pattern matching. In the following example, the username is restricted to alphanumerical characters plus underscore and to a length between 8 and 20 characters – modify these rules as needed.

永远不要信任用户提供的数据,仅在验证后才处理这些数据; 通常,这是通过模式匹配完成的。 在以下示例中,用户名限制为字母数字字符和下划线,并且长度介于8到20个字符之间-根据需要修改这些规则。


if (preg_match("/^\w{8,20}$/", $_GET['username'], $matches)) {$result = mysql_query("SELECT * FROM users WHERE username = $matches[0]");
} else  {echo "username not accepted";
}

To demonstrate this problem, consider the following excerpt.

为了演示此问题,请考虑以下摘录。


// supposed input
$name = "Qadir'; DELETE FROM users;";
mysql_query("SELECT * FROM users WHERE name = '{$name}'");

The function call is supposed to retrieve a record from the users table, where the name column matches the name specified by the user. Under normal circumstances, $name would only contain alphanumeric characters and perhaps spaces. But here, by appending an entirely new query to $name, the call to the database turns into a disaster. The injected DELETE query removes all the records from users.

该函数调用应该从users表中检索一条记录,其中name列与用户指定的名称匹配。 通常情况下,$ name仅包含字母数字字符,也许还包含空格。 但是在这里,通过将一个全新的查询附加到$ name ,对数据库的调用变成了一场灾难。 注入的DELETE查询将从用户中删除所有记录。

Fortunately, if you use MySQL, the mysql_query() function does not permit query stacking or executing multiple queries in a single function call. If you try to stack queries, the call fails.

幸运的是,如果使用MySQL,则mysql_query()函数不允许查询堆栈或在单个函数调用中执行多个查询。 如果您尝试堆叠查询,则调用将失败。

However, other PHP database extensions, such as SQLite and PostgreSQL, happily perform stacked queries, executing all the queries provided in one string and creating a serious security problem.

但是,其他PHP数据库扩展(例如SQLitePostgreSQL )可以愉快地执行堆栈查询,执行一个字符串中提供的所有查询并造成严重的安全性问题。

防止SQL注入 (Preventing SQL Injection)

You can handle all escape characters smartly in scripting languages like PERL and PHP. The MySQL extension for PHP provides the function mysql_real_escape_string() to escape input characters that are special to MySQL.

您可以使用PERL和PHP等脚本语言来巧妙地处理所有转义字符。 PHPMySQL扩展提供了函数mysql_real_escape_string()来转义MySQL特有的输入字符。


if (get_magic_quotes_gpc()) {$name = stripslashes($name);
}$name = mysql_real_escape_string($name);
mysql_query("SELECT * FROM users WHERE name = '{$name}'");

像Quadary (The LIKE Quandary)

To address the LIKE quandary, a custom escaping mechanism must convert user-supplied % and _ characters to literals. Use addcslashes(), a function that lets you specify a character range to escape.

为了解决LIKE难题,自定义转义机制必须将用户提供的%和_字符转换为文字。 使用addcslashes() ,该函数可让您指定要转义的字符范围。


$sub = addcslashes(mysql_real_escape_string("%something_"), "%_");
// $sub == \%something\_
mysql_query("SELECT * FROM messages WHERE subject LIKE '{$sub}%'");

MySQL-数据库导出 (MySQL - Database Export)

The simplest way of exporting a table data into a text file is by using the SELECT...INTO OUTFILE statement that exports a query result directly into a file on the server host.

将表数据导出到文本文件的最简单方法是使用SELECT ... INTO OUTFILE语句,该语句将查询结果直接导出到服务器主机上的文件中。

使用SELECT ... INTO OUTFILE语句导出数据 (Exporting Data with the SELECT ... INTO OUTFILE Statement)

The syntax for this statement combines a regular SELECT command with INTO OUTFILE filename at the end. The default output format is the same as it is for the LOAD DATA command. So, the following statement exports the tutorials_tbl table into /tmp/tutorials.txt as a tab-delimited, linefeed-terminated file.

该语句的语法在末尾结合了常规的SELECT命令和INTO OUTFILE文件名 。 缺省输出格式与LOAD DATA命令的缺省输出格式相同。 所以,下面的语句导出tutorials_tbl表分成/tmp/tutorials.txt作为制表符分隔,换行终止的文件。


mysql> SELECT * FROM tutorials_tbl -> INTO OUTFILE '/tmp/tutorials.txt';

You can change the output format using various options to indicate how to quote and delimit columns and records. To export the tutorial_tbl table in a CSV format with CRLF-terminated lines, use the following code.

您可以使用各种选项来更改输出格式,以指示如何对列和记录进行引用和定界。 要以带有CRLF终止行的CSV格式导出tutorial_tbl表,请使用以下代码。


mysql> SELECT * FROM passwd INTO OUTFILE '/tmp/tutorials.txt'-> FIELDS TERMINATED BY ',' ENCLOSED BY '"'-> LINES TERMINATED BY '\r\n';

The SELECT ... INTO OUTFILE has the following properties −

SELECT ... INTO OUTFILE具有以下属性-

  • The output file is created directly by the MySQL server, so the filename should indicate where you want the file to be written on the server host. There is no LOCAL version of the statement analogous to the LOCAL version of LOAD DATA.

    输出文件是由MySQL服务器直接创建的,因此文件名应指示您要在服务器主机上写入文件的位置。 没有类似于LOAD DATALOCAL版本的语句的LOCAL版本。

  • You must have the MySQL FILE privilege to execute the SELECT ... INTO statement.

    您必须具有MySQL FILE特权才能执行SELECT ... INTO语句。

  • The output file must not already exist. This prevents MySQL from clobbering files that may be important.

    输出文件必须不存在。 这样可以防止MySQL破坏可能很重要的文件。

  • You should have a login account on the server host or some way to retrieve the file from that host. Otherwise, the SELECT ... INTO OUTFILE command will most likely be of no value to you.

    您应该在服务器主机上拥有一个登录帐户,或通过某种方式从该主机上检索文件。 否则, SELECT ... INTO OUTFILE命令对您很可能毫无价值

  • Under UNIX, the file is created world readable and is owned by the MySQL server. This means that although you will be able to read the file, you may not be able to delete it.

    在UNIX下,该文件是全球可读的,并且由MySQL服务器拥有。 这意味着尽管您将能够读取该文件,但可能无法将其删除。

将表导出为原始数据 (Exporting Tables as Raw Data)

The mysqldump program is used to copy or back up tables and databases. It can write the table output either as a Raw Datafile or as a set of INSERT statements that recreate the records in the table.

mysqldump程序用于复制或备份表和数据库。 它可以将表输出作为原始数据文件或一组在表中重新创建记录的INSERT语句来写入。

To dump a table as a datafile, you must specify a --tab option that indicates the directory, where you want the MySQL server to write the file.

要将表转储为数据文件,必须指定--tab选项,该选项指示MySQL服务器要在其中写入文件的目录。

For example, to dump the tutorials_tbl table from the TUTORIALS database to a file in the /tmp directory, use a command as shown below.

例如,要将Tutorials_tbl表从TUTORIALS数据库转储到/ tmp目录中的文件,请使用如下所示的命令。


$ mysqldump -u root -p --no-create-info \--tab=/tmp tutorials tutorials_tbl
password ******

以SQL格式导出表内容或定义 (Exporting Table Contents or Definitions in SQL Format)

To export a table in SQL format to a file, use the command shown below.

要将SQL格式的表导出到文件,请使用以下命令。


$ mysqldump -u root -p TUTORIALS tutorials_tbl > dump.txt
password ******

This will a create file having content as shown below.

这将创建一个具有如下所示内容的文件。


-- MySQL dump 8.23
--
-- Host: localhost    Database: TUTORIALS
---------------------------------------------------------
-- Server version       3.23.58--
-- Table structure for table `tutorials_tbl`
--CREATE TABLE tutorials_tbl (tutorial_id int(11) NOT NULL auto_increment,tutorial_title varchar(100) NOT NULL default '',tutorial_author varchar(40) NOT NULL default '',submission_date date default NULL,PRIMARY KEY  (tutorial_id),UNIQUE KEY AUTHOR_INDEX (tutorial_author)
) TYPE = MyISAM;--
-- Dumping data for table `tutorials_tbl`
--INSERT INTO tutorials_tbl VALUES (1,'Learn PHP','John Poul','2007-05-24');
INSERT INTO tutorials_tbl VALUES (2,'Learn MySQL','Abdul S','2007-05-24');
INSERT INTO tutorials_tbl VALUES (3,'JAVA Tutorial','Sanjay','2007-05-06');

To dump multiple tables, name them all followed by the database name argument. To dump an entire database, don't name any tables after the database as shown in the following code block.

要转储多个表,请将它们全部命名,后跟数据库名称参数。 要转储整个数据库,请不要在数据库后命名任何表,如以下代码块所示。


$ mysqldump -u root -p TUTORIALS > database_dump.txt
password ******

To back up all the databases available on your host, use the following code.

要备份主机上可用的所有数据库,请使用以下代码。


$ mysqldump -u root -p --all-databases > database_dump.txt
password ******

The --all-databases option is available in the MySQL 3.23.12 version. This method can be used to implement a database backup strategy.

--all-databases选项在MySQL 3.23.12版本中可用。 此方法可用于实现数据库备份策略。

将表或数据库复制到另一台主机 (Copying Tables or Databases to Another Host)

If you want to copy tables or databases from one MySQL server to another, then use the mysqldump with database name and table name.

如果要将表或数据库从一台MySQL服务器复制到另一台,请使用带有数据库名和表名的mysqldump

Run the following command at the source host. This will dump the complete database into dump.txt file.

在源主机上运行以下命令。 这会将整个数据库转储到dump.txt文件中。


$ mysqldump -u root -p database_name table_name > dump.txt
password *****

You can copy complete database without using a particular table name as explained above.

您可以在不使用特定表名的情况下复制完整的数据库,如上所述。

Now, ftp dump.txt file on another host and use the following command. Before running this command, make sure you have created database_name on destination server.

现在,在另一台主机上使用ftp dump.txt文件,并使用以下命令。 在运行此命令之前,请确保已在目标服务器上创建了database_name。


$ mysql -u root -p database_name < dump.txt
password *****

Another way to accomplish this without using an intermediary file is to send the output of the mysqldump directly over the network to the remote MySQL server. If you can connect to both the servers from the host where the source database resides, use the following command (Make sure you have access on both the servers).

在不使用中间文件的情况下完成此操作的另一种方法是直接通过网络将mysqldump的输出发送到远程MySQL服务器。 如果可以从源数据库所在的主机连接到两台服务器,请使用以下命令(确保两台服务器都具有访问权限)。


$ mysqldump -u root -p database_name \| mysql -h other-host.com database_name

In mysqldump, half of the command connects to the local server and writes the dump output to the pipe. The remaining half of the command connects to the remote MySQL server on the other-host.com. It reads the pipe for input and sends each statement to the other-host.com server.

在mysqldump中,一半的命令连接到本地服务器,并将转储输出写入管道。 该命令的其余一半连接到other-host.com上的远程MySQL服务器。 它读取用于输入的管道,并将每个语句发送到other-host.com服务器。

MySQL-数据库导入-恢复方法 (MySQL - Database Import - Recovery Methods)

There are two simple ways in MySQL to load data into the MySQL database from a previously backed up file.

MySQL中有两种简单的方法可以将数据从先前备份的文件加载到MySQL数据库中。

使用LOAD DATA导入数据 (Importing Data with LOAD DATA)

MySQL provides a LOAD DATA statement that acts as a bulk data loader. Here is an example statement that reads a file dump.txt from your current directory and loads it into the table mytbl in the current database.

MySQL提供了一个LOAD DATA语句,可以用作批量数据加载器。 这是一个示例语句,该语句从当前目录读取文件dump.txt并将其加载到当前数据库的表mytbl中。


mysql> LOAD DATA LOCAL INFILE 'dump.txt' INTO TABLE mytbl;

  • If the LOCAL keyword is not present, MySQL looks for the datafile on the server host using the looking into absolute pathname, which fully specifies the location of the file, beginning from the root of the filesystem. MySQL reads the file from the given location.

    如果没有LOCAL关键字,MySQL将使用对绝对路径名查找在服务器主机上查找数据文件,该路径名从文件系统的根开始完全指定文件的位置。 MySQL从给定位置读取文件。

  • By default, LOAD DATA assumes that datafiles contain lines that are terminated by linefeeds (newlines) and that data values within a line are separated by tabs.

    默认情况下, LOAD DATA假定数据文件包含以换行(换行符)结尾的行,并且行中的数据值由制表符分隔。

  • To specify a file format explicitly, use a FIELDS clause to describe the characteristics of fields within a line, and a LINES clause to specify the line-ending sequence. The following LOAD DATA statement specifies that the datafile contains values separated by colons and lines terminated by carriage returns and new line character.

    要明确指定文件格式,请使用FIELDS子句描述一行中字段的特征,并使用LINES子句指定行尾序列。 以下LOAD DATA语句指定数据文件包含用冒号和以回车符和换行符结尾的行分隔的值。


mysql> LOAD DATA LOCAL INFILE 'dump.txt' INTO TABLE mytbl-> FIELDS TERMINATED BY ':'-> LINES TERMINATED BY '\r\n';

  • The LOAD DATA command assumes the columns in the datafile have the same order as the columns in the table. If that is not true, you can specify a list to indicate which table columns the datafile columns should be loaded into. Suppose your table has columns a, b, and c, but successive columns in the datafile correspond to columns b, c, and a.

    LOAD DATA命令假定数据文件中的列与表中的列具有相同的顺序。 如果不是这样,则可以指定一个列表以指示数据文件列应加载到哪些表列中。 假设您的表具有列a,b和c,但是数据文件中的连续列对应于列b,c和a。

You can load the file as shown in the following code block.

您可以按照以下代码块中所示加载文件。


mysql> LOAD DATA LOCAL INFILE 'dump.txt' -> INTO TABLE mytbl (b, c, a);

使用mysqlimport导入数据 (Importing Data with mysqlimport)

MySQL also includes a utility program named mysqlimport that acts as a wrapper around LOAD DATA, so that you can load the input files directly from the command line.

MySQL还包括一个名为mysqlimport的实用程序,它充当LOAD DATA的包装,因此您可以直接从命令行加载输入文件。

To load data from the dump.txt into mytbl, use the following command at the UNIX prompt.

要将数据从dump.txt加载到mytbl中 ,请在UNIX提示符下使用以下命令。


$ mysqlimport -u root -p --local database_name dump.txt
password *****

If you use mysqlimport, command-line options provide the format specifiers. The mysqlimport commands that correspond to the preceding two LOAD DATA statements looks as shown in the following code block.

如果使用mysqlimport ,则命令行选项提供格式说明符。 对应于前两个LOAD DATA语句的mysqlimport命令的外观如以下代码块所示。


$ mysqlimport -u root -p --local --fields-terminated-by = ":" \--lines-terminated-by = "\r\n"  database_name dump.txt
password *****

The order in which you specify the options doesn't matter for mysqlimport, except that they should all precede the database name.

指定选项的顺序对mysqlimport无关紧要,只是它们都应在数据库名称之前。

The mysqlimport statement uses the --columns option to specify the column order −

mysqlimport语句使用--columns选项指定列顺序-


$ mysqlimport -u root -p --local --columns=b,c,a \database_name dump.txt
password *****

处理引号和特殊字符 (Handling Quotes and Special Characters)

The FIELDS clause can specify other format options besides TERMINATED BY. By default, LOAD DATA assumes that values are unquoted and interprets the backslash (\) as an escape character for the special characters. To indicate the value quoting character explicitly, use the ENCLOSED BY command. MySQL will strip that character from the ends of data values during input processing. To change the default escape character, use ESCAPED BY.

FIELDS子句可以指定除TERMINATED BY之外的其他格式选项。 默认情况下,LOAD DATA假定值未加引号,并将反斜杠(\)解释为特殊字符的转义字符。 要明确指示值引号字符,请使用ENCLOSED BY命令。 MySQL将在输入处理期间从数据值的末尾去除该字符。 要更改默认的转义字符,请使用ESCAPED BY

When you specify ENCLOSED BY to indicate that quote characters should be stripped from data values, it is possible to include the quote character literally within data values by doubling it or by preceding it with the escape character.

当您指定ENCLOSED BY以指示应从数据值中删除引号字符时,可以通过将其加倍或在其前面加上转义字符来在数据值中实际包括引号字符。

For example, if the quote and escape characters are " and \, the input value "a""b\"c" will be interpreted as a"b"c.

例如,如果引号和转义字符为“和\,则输入值” a“” b \“ c”将解释为“ b” c

For mysqlimport, the corresponding command-line options for specifying quote and escape values are --fields-enclosed-by and --fields-escaped-by.

对于mysqlimport ,用于指定引号和转义值的相应命令行选项是--fields-enclosed-by--fields-escaped-by

翻译自: https://www.tutorialspoint.com/mysql/mysql-quick-guide.htm

mysql 指南

mysql 指南_MySQL-快速指南相关推荐

  1. mysql指南_MySQL入门指南

    MySQL入门指南,希望对大家用处!! 一.SQL速成 以下是一些重要的SQL快速参考,有关SQL的语法和在标准SQL上增加的特性,请查询MySQL手册. 1.创建表 表是数据库的最基本元素之一,表与 ...

  2. Mysql数据库引擎快速指南

    如果你是个赛车手并且按一下按钮就能够立即更换引擎而不需要把车开到车库里去换,那会是怎么感觉呢? MySQL 数据库为开发人员所做的就好像是按按钮换引擎:它让你选择数据库引擎,并给你一条简单的途径来切换 ...

  3. rds for mysql的监控指标_支持的监控指标_云数据库 RDS_用户指南_MySQL用户指南_监控指标与告警_华为云...

    rds001_cpu_util CPU使用率 该指标用于统计测量对象的CPU使用率,以比率为单位. 0-100% 测量对象:弹性云服务器 监控实例类型:MySQL实例 1分钟 5秒 1秒 rds002 ...

  4. 机器学习指南_机器学习-快速指南

    机器学习指南 机器学习-快速指南 (Machine Learning - Quick Guide) 机器学习-简介 (Machine Learning - Introduction) Today's ...

  5. mysql怎么跑代码_MySQL菜鸟入门指南_mysql

    mysql是完全网络化的跨平台关系型数据库系统,一个真正的多用户.多线程SQL数据库服务器,同时是具有客户机/服务器体系结构的分布式数据库管理系统.它具有功能强.使用简便.管理方便.容易使用.运行速度 ...

  6. 闻与MyBatis之MyBatis快速指南

    本文内容如有错误.不足之处,欢迎技术爱好者们一同探讨,在本文下面讨论区留言,感谢.欢迎转载,转载请注明出处(https://blog.csdn.net/feng_xiaoshi/article/det ...

  7. MySQL Workbench 使用教程 - 如何使用 Workbench 操作 MySQL / MariaDB 数据库中文指南

    MySQL Workbench 是一款专门为 MySQL 设计的可视化数据库管理软件,我们可以在自己的计算机上,使用图形化界面远程管理 MySQL 数据库. 有关 MySQL 远程管理软件,你可以选择 ...

  8. 《树莓派Python编程指南》—— 1.3 树莓派快速指南

    本节书摘来自华章计算机<树莓派Python编程指南>一书中的第1章,第1.3节,作者:(美) Alex Bradbury Ben Everard更多章节内容可以访问云栖社区"华章 ...

  9. react 快速上手开发_React中测试驱动开发的快速指南

    react 快速上手开发 by Michał Baranowski 通过MichałBaranowski React中测试驱动开发的快速指南 (A quick guide to test-driven ...

最新文章

  1. ES6解构赋值学习总结
  2. 系分考试论文实例12篇
  3. # 起床困难综合症(二进制枚举+按位求贡献)
  4. ITK:二进制图像的最小和最大曲率流
  5. 前端学习(1324):anysc关键字
  6. LeetCode 310 最小高度树
  7. 产品经理面试必问问题与答题模板
  8. goeasy+jquery+ckplayer实现动态实时视频弹幕
  9. PS修补工具使用方法
  10. 如何快速实现高并发短文检索
  11. 亲测~Win10开启系统自带Wifi热点步骤
  12. 麻将 java_怎么用java做麻将游戏
  13. 家用洗地机买什么牌子好一点?家用洗地机推荐
  14. 【绝对详细!不好使你顺着网线敲我!】Django3.1在Ubuntu16.04上的部署
  15. 打开Word文档的时候提示mathtype “安全警告 宏已被禁用”
  16. docker build 18.04 镜像出现 Configuring tzdata - Please select the geographic area in which you live
  17. 利用端口,进程,文件,服务和日志信息来排查系统安全
  18. 拼音反查(转自大富翁)
  19. qt实现调用电脑摄像头
  20. SAP OData 编程指南

热门文章

  1. 家校互动、班级管理系统
  2. 如何修改tomcat默认端口号(详细步骤)
  3. Rosetta如何连接隐私计算与AI?道翰天琼认知智能机器人平台API接口大脑为您揭秘。
  4. 智云Smooth Q支持延时摄影多种滤镜 拍电影如此简单
  5. python对windows指定窗口截图
  6. [Datawhale-李宏毅机器学习-39期]-001-机器学习介绍
  7. 将绿色计算进行到底,蚂蚁集团四大硬核黑科技全公开
  8. 通信工程师给儿子的信2:为什么铜线能导电?
  9. 智能仓储行业:各细分毛利率与盈利模式分析
  10. 光安检场景下危险品检测