manualshive.com logo in svg
background image

MySQL 5.0 Reference Manual

Содержание 5.0

Страница 1: ...MySQL 5 0 Reference Manual ...

Страница 2: ... the MySQL 5 0 Release Notes For legal information see the Legal Notices Document generated on 2013 04 16 revision 34918 General Administrators MySQL Enterprise Developers Functionality Connectors APIs HA Scalability Tutorial Installation Upgrades MySQL Enterprise Edition MySQL Workbench Connectors and APIs HA Scalability Guide Server Administration MySQL Installer MySQL Enterprise Monitor Globali...

Страница 3: ...38 2 Installing and Upgrading MySQL 41 2 1 MySQL Installation Overview 42 2 2 Determining your current MySQL version 42 2 3 Notes for MySQL Enterprise Server 43 2 3 1 Enterprise Server Distribution Types 44 2 3 2 Upgrading MySQL Enterprise Server 44 2 4 Notes for MySQL Community Server 44 2 4 1 Overview of MySQL Community Server Installation 44 2 4 2 Operating Systems Supported by MySQL Community ...

Страница 4: ...ases to Another Machine 158 2 20 Operating System Specific Notes 159 2 20 1 Linux Notes 159 2 20 2 Mac OS X Notes 165 2 20 3 Solaris Notes 165 2 20 4 BSD Notes 169 2 20 5 Other Unix Notes 172 2 20 6 OS 2 Notes 187 2 21 Environment Variables 187 2 22 Perl Installation Notes 188 2 22 1 Installing Perl on Unix 189 2 22 2 Installing ActiveState Perl on Windows 190 2 22 3 Problems Using the Perl DBI DB...

Страница 5: ...checksum Offline InnoDB File Checksum Utility 315 4 6 2 myisam_ftdump Display Full Text Index information 316 4 6 3 myisamchk MyISAM Table Maintenance Utility 317 4 6 4 myisamlog Display MyISAM Log File Contents 333 4 6 5 myisampack Generate Compressed Read Only MyISAM Tables 334 4 6 6 mysqlaccess Client for Checking Access Privileges 339 4 6 7 mysqlbinlog Utility for Processing Binary Log Files 3...

Страница 6: ... User 571 6 1 6 Security Issues with LOAD DATA LOCAL 572 6 1 7 Client Programming Security Guidelines 573 6 2 The MySQL Access Privilege System 574 6 2 1 Privileges Provided by MySQL 575 6 2 2 Privilege System Grant Tables 579 6 2 3 Specifying Account Names 583 6 2 4 Access Control Stage 1 Connection Verification 585 6 2 5 Access Control Stage 2 Request Verification 588 6 2 6 When Privilege Change...

Страница 7: ...timizing Non SELECT Statements 685 8 3 3 Other Optimization Tips 689 8 4 Controlling the Query Optimizer 691 8 5 Optimization and Indexes 692 8 5 1 Column Indexes 692 8 5 2 Multiple Column Indexes 692 8 5 3 How MySQL Uses Indexes 694 8 5 4 MyISAM Index Statistics Collection 696 8 6 Buffering and Caching 698 8 6 1 The MyISAM Key Cache 698 8 6 2 The InnoDB Buffer Pool 702 8 6 3 The MySQL Query Cache...

Страница 8: ...Sets and Collations 770 10 1 4 Connection Character Sets and Collations 776 10 1 5 Configuring the Character Set and Collation for Applications 778 10 1 6 Character Set for Error Messages 780 10 1 7 Collation Issues 780 10 1 8 String Repertoire 787 10 1 9 Operations Affected by Character Set Support 788 10 1 10 Unicode Support 791 10 1 11 UTF 8 for Metadata 792 10 1 12 Column Character Set Convers...

Страница 9: ...Full Text Searches 935 12 9 2 Boolean Full Text Searches 938 12 9 3 Full Text Searches with Query Expansion 940 12 9 4 Full Text Stopwords 941 12 9 5 Full Text Restrictions 944 12 9 6 Fine Tuning MySQL Full Text Search 944 12 9 7 Adding a Collation for Full Text Indexing 946 12 10 Cast Functions and Operators 948 12 11 Bit Functions 950 12 12 Encryption and Compression Functions 952 12 13 Informat...

Страница 10: ... 1065 13 2 6 LOAD DATA INFILE Syntax 1072 13 2 7 REPLACE Syntax 1081 13 2 8 SELECT Syntax 1082 13 2 9 Subquery Syntax 1098 13 2 10 UPDATE Syntax 1108 13 3 MySQL Transactional and Locking Statements 1110 13 3 1 START TRANSACTION COMMIT and ROLLBACK Syntax 1110 13 3 2 Statements That Cannot Be Rolled Back 1113 13 3 3 Statements That Cause an Implicit Commit 1113 13 3 4 SAVEPOINT ROLLBACK TO SAVEPOIN...

Страница 11: ... 14 2 11 InnoDB Error Handling 1280 14 2 12 InnoDB Performance Tuning and Troubleshooting 1284 14 2 13 Limits on InnoDB Tables 1297 14 3 The MERGE Storage Engine 1300 14 3 1 MERGE Table Advantages and Disadvantages 1302 14 3 2 MERGE Table Problems 1303 14 4 The MEMORY HEAP Storage Engine 1305 14 5 The BDB BerkeleyDB Storage Engine 1307 14 5 1 Operating Systems Supported by BDB 1308 14 5 2 Installi...

Страница 12: ...1488 16 3 3 Using Replication for Scale Out 1489 16 3 4 Replicating Different Databases to Different Slaves 1490 16 3 5 Improving Replication Performance 1492 16 3 6 Switching Masters During Failover 1493 16 3 7 Setting Up Replication Using SSL 1495 16 4 Replication Notes and Tips 1497 16 4 1 Replication Features and Issues 1497 16 4 2 Replication Compatibility Between MySQL Versions 1508 16 4 3 U...

Страница 13: ...tions Common to MySQL Cluster Programs Options Common to MySQL Cluster Programs 1650 17 5 Management of MySQL Cluster 1653 17 5 1 Summary of MySQL Cluster Start Phases 1653 17 5 2 Commands in the MySQL Cluster Management Client 1655 17 5 3 Online Backup of MySQL Cluster 1656 17 5 4 MySQL Server Usage for MySQL Cluster 1660 17 5 5 Performing a Rolling Restart of a MySQL Cluster 1661 17 5 6 Event Re...

Страница 14: ...r Net Versions 1816 20 2 2 Connector Net Installation 1818 20 2 3 Connector Net Visual Studio Integration 1826 20 2 4 Connector Net Tutorials 1856 20 2 5 Connector Net Programming 1896 20 2 6 Connector Net Connection String Options Reference 1935 20 2 7 Connector Net API Reference 1942 20 2 8 Connector Net Support 2045 20 2 9 Connector Net FAQ 2046 20 3 MySQL Connector J 2047 20 3 1 Overview of My...

Страница 15: ...ginal MySQL API Mysql 2237 20 7 3 MySQL Improved Extension Mysqli 2306 20 7 4 MySQL Functions PDO_MYSQL MySQL PDO 2520 20 7 5 MySQL Native Driver Mysqlnd 2524 20 7 6 Mysqlnd replication and load balancing plugin mysqlnd_ms 2556 20 7 7 Mysqlnd query result cache plugin mysqlnd_qc 2657 20 7 8 Mysqlnd user handler plugin mysqlnd_uh 2708 20 7 9 Mysqlnd connection multiplexing plugin mysqlnd_mux 2791 2...

Страница 16: ...gorithm 1 SHA1 License 2864 A 26 Richard A O Keefe String Library License 2864 A 27 SHA 1 in C License 2865 A 28 Simple Logging Facade for Java SLF4J License 2865 A 29 zlib License 2865 A 30 ZLIB NET License 2866 B MySQL 5 0 Frequently Asked Questions 2867 B 1 MySQL 5 0 FAQ General 2867 B 2 MySQL 5 0 FAQ Storage Engines 2869 B 3 MySQL 5 0 FAQ Server SQL Mode 2869 B 4 MySQL 5 0 FAQ Stored Procedure...

Страница 17: ...ter Sets 2988 E 7 Limits in MySQL 2988 E 7 1 Limits of Joins 2988 E 7 2 Limits on Number of Databases and Tables 2988 E 7 3 Limits on Table Size 2989 E 7 4 Limits on Table Column Count and Row Size 2990 E 7 5 Limits Imposed by frm File Structure 2991 E 7 6 Windows Platform Limitations 2992 General Index 2995 C Function Index 3055 Command Index 3063 Function Index 3087 INFORMATION_SCHEMA Index 3103...

Страница 18: ...xviii ...

Страница 19: ...ata delivered to U S Government customers are commercial computer software or commercial technical data pursuant to the applicable Federal Acquisition Regulation and agency specific supplemental regulations As such the use duplication disclosure modification and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract and to the extent appli...

Страница 20: ...it that is electronically for download on a Web site with the software or on a CD ROM or similar medium provided however that the documentation is disseminated together with the software on the same medium Any other use such as any dissemination of printed copies or use of this documentation in whole or in part in another publication requires the prior written consent from an authorized representa...

Страница 21: ...ers various support offerings which may be of interest For details and more information see the MySQL section of the Lifetime Support Policy for Oracle Technology Products http www oracle com us support lifetime support index html Please consider upgrading to a recent version The MySQL software delivers a very fast multi threaded multi user and robust SQL Structured Query Language database server ...

Страница 22: ...through release 5 0 96 Differences between minor versions of MySQL 5 0 are noted in the present text with reference to release numbers 5 0 x For license information see the Legal Notices This product may contain third party code For license information on third party code see Appendix A Licenses for Third Party Components This manual is not intended for use with older versions of the MySQL softwar...

Страница 23: ... IP address of the MySQL server that it should connect to File names and directory names are written like this The global my cnf file is located in the etc directory Character sequences are written like this To specify a wildcard use the character When commands are shown that are meant to be executed from within a particular program the prompt shown preceding the command indicates which command to...

Страница 24: ...ndicate that the preceding syntax element of a statement may be repeated In the following example multiple reset_option values may be given with each of those after the first preceded by commas RESET reset_option reset_option Commands for setting shell variables are shown using Bourne shell syntax For example the sequence to set the CC environment variable and run the configure command looks like ...

Страница 25: ...uations If you feel uncomfortable with the GPL or need to embed MySQL code into a commercial application you can buy a commercially licensed version from us See the MySQL Licensing Overview for more information http www mysql com company legal licensing The MySQL Database Server is very fast reliable scalable and easy to use If that is what you are looking for you should give it a try MySQL Server...

Страница 26: ...rdj Uses multi layered server design with independent modules Designed to be fully multi threaded using kernel threads to easily use multiple CPUs if they are available Provides transactional and nontransactional storage engines Uses very fast B tree disk tables MyISAM with index compression Designed to make it relatively easy to add other storage engines This is useful if you want to provide an S...

Страница 27: ...name and the that follows it See Section 9 3 Reserved Words You can refer to tables from different databases in the same statement Security A privilege and password system that is very flexible and secure and that enables host based verification Password security by encryption of all password traffic when you connect to a server Scalability and Limits Support for large databases We use MySQL Serve...

Страница 28: ...ö are permitted in table and column names Unicode support is available as of MySQL 4 1 All data is saved in the chosen character set Sorting and comparisons are done according to the chosen character set and collation using latin1 and Swedish collation by default It is possible to change this when the MySQL server is started To see an example of very advanced sorting look at the Czech sorting code...

Страница 29: ... of others was improved New storage engines in MySQL 5 0 include ARCHIVE and FEDERATED See Section 14 8 The ARCHIVE Storage Engine and Section 14 7 The FEDERATED Storage Engine Performance Improvements in the InnoDB Storage Engine New compact storage format which can save up to 20 of the disk space required in previous MySQL InnoDB versions Faster recovery from a failed or aborted ALTER TABLE Fast...

Страница 30: ...N is the number of tables to be joined The greedy optimizer reduces this to N D 1 where D is the depth of the search Although the greedy optimizer does not guarantee the best possible of all execution plans this is currently being worked on it can reduce the time spent arriving at an execution plan for a join involving a great many tables 30 40 or more by a factor of as much as 1 000 This should e...

Страница 31: ...ees 4 1 for the MyISAM storage engine Stored procedures and functions 5 0 Views 5 0 Cursors 5 0 XA transactions 5 0 Triggers 5 0 and 5 1 Event scheduler 5 1 Partitioning 5 1 Pluggable storage engine API 5 1 Plugin API 5 1 InnoDB Plugin 5 1 Row based replication 5 1 Server log tables 5 1 1 6 MySQL Information Sources This section lists sources of additional information that you may find helpful suc...

Страница 32: ...e of MySQL or who want to be actively involved in the process of bug hunting and fixing See Section 1 7 How to Report Bugs or Problems internals The list for people who work on the MySQL code This is also the forum for discussions on MySQL development and for posting patches mysqldoc The list for people who work on the MySQL documentation benchmarks The list for anyone interested in performance is...

Страница 33: ...n about this mailing list at http www 4t2 com mysql mysql br request listas linkway com br A Portuguese mailing list To subscribe email subscribe mysql br your email address to this list mysql alta elistas net A Spanish mailing list To subscribe email subscribe mysql your email address to this list 1 6 1 1 Guidelines for Using the Mailing Lists Please do not post mail messages from your browser wi...

Страница 34: ...re also common If you are looking for IRC client software to connect to an IRC network take a look at xChat http www xchat org X Chat GPL licensed is available for Unix as well as for Windows platforms a free Windows build of X Chat is available at http www silverex org download 1 6 4 MySQL Enterprise Oracle offers technical support in the form of MySQL Enterprise For organizations that rely on th...

Страница 35: ...public and can be browsed and searched by anyone If you log in to the system you can enter new reports Bugs posted in the bugs database at http bugs mysql com that are corrected for a given release are noted in the release notes If you find a sensitive security bug in MySQL Server please let us know immediately by sending an email message to secalert_us oracle com Exception Support customers shoul...

Страница 36: ...age into your report You should never try to reproduce the message from memory If you have a problem with Connector ODBC MyODBC please try to generate a trace file and send it with your report See Section 20 1 8 2 How to Report Connector ODBC Problems or Bugs If your report includes long query output lines from test cases that you run with the mysql command line tool you can make the output more r...

Страница 37: ...o run the query mysql SHOW STATUS output from SHOW STATUS If a bug or problem occurs while running mysqld try to provide an input script that reproduces the anomaly This script should include any necessary source files The more closely the script can reproduce your situation the better If you can make a reproducible test case you should upload it to be attached to the bug report If you cannot prov...

Страница 38: ...what it depends on are usually wrong Even the MySQL team cannot guess such things without first using a debugger to determine the real cause of a bug Indicate in your bug report that you have checked the reference manual and mail archive so that others know you have tried to solve the problem yourself If your data appears corrupt or you get errors when you access a particular table first check you...

Страница 39: ...tical 24 7 usage and heavy Web or logging usage MySQL Server was originally designed to work with medium sized databases 10 100 million rows or about 100MB per table on small computer systems Today MySQL Server handles terabyte sized databases but the code can also be compiled in a reduced version suitable for hand held and embedded devices The compact design of the MySQL server makes development ...

Страница 40: ...be portable to other SQL servers In some cases you can write code that includes MySQL extensions but is still portable by using comments of the following form MySQL specific code In this case MySQL Server parses and executes the code within the comment as it would any other SQL statement but other SQL servers will ignore the extensions For example MySQL Server recognizes the STRAIGHT_JOIN keyword ...

Страница 41: ...XPLAIN SELECT to obtain a description of how tables are processed by the query optimizer The FLUSH and RESET statements The SET statement See Section 13 7 4 SET Syntax The SHOW statement See Section 13 7 5 SHOW Syntax The information produced by many of the MySQL specific SHOW statements can be obtained in more standard fashion by using SELECT to query INFORMATION_SCHEMA See Chapter 19 INFORMATION...

Страница 42: ...ical OR and AND as in the C programming language In MySQL Server 881 and OR 881 are synonyms as are 880 and AND 880 Because of this nice syntax MySQL Server doesn t support the standard SQL 881 operator for string concatenation use CONCAT 887 instead Because CONCAT 887 takes any number of arguments it is easy to convert use of the 881 operator to MySQL Server Use of COUNT DISTINCT value_list 970 w...

Страница 43: ...d standard SQL privilege systems For example in MySQL privileges for a table are not automatically revoked when you delete a table You must explicitly issue a REVOKE statement to revoke privileges for a table For more information see Section 13 7 1 5 REVOKE Syntax The CAST 948 function does not support cast to REAL or BIGINT See Section 12 10 Cast Functions and Operators Standard SQL requires that...

Страница 44: ...the server is given the opportunity to do an automatic rollback and your database is saved If you use nontransactional tables MySQL Server in almost all cases enables you to resolve potential problems by including simple checks before updates and by running simple scripts that check the databases for inconsistencies and automatically repair or warn if such an inconsistency occurs You can normally ...

Страница 45: ...ave been executed You can also use functions to update records in a single operation You can get a very efficient application by using the following techniques Modify columns relative to their current value Update only those columns that actually have changed For example when we are updating customer information we update only the customer data that has changed and test only that none of the chang...

Страница 46: ...ide This eliminates the possibility that different applications may not all check the constraints in the same way Using cascading updates and deletes can simplify the application code Properly designed foreign key rules aid in documenting relationships between tables Do keep in mind that these benefits come at the cost of additional overhead for the database server to perform the necessary checks ...

Страница 47: ...r comments and MySQL Server supports this syntax as well MySQL also support extensions to this syntax that enable MySQL specific SQL to be embedded in the comment as described in Section 9 6 Comment Syntax Standard SQL uses as a start comment sequence MySQL Server uses as the start comment character MySQL Server 3 23 3 and up also supports a variant of the comment style That is the start comment s...

Страница 48: ...vide greater control over handling of bad data values and whether to continue statement execution or abort when errors occur Using these options you can configure MySQL Server to act in a more traditional fashion that is like other DBMSs that reject improper input The SQL mode can be set globally at server startup to affect all clients Individual clients can set the SQL mode at runtime which enabl...

Страница 49: ...CED_TABLE_SCHEMA IS NOT NULL TABLE_SCHEMA TABLE_NAME COLUMN_NAME CONSTRAINT_NAME fk1 myuser myuser_id f fk1 product_order customer_id f2 fk1 product_order product_id f1 3 rows in set 0 01 sec Information about foreign keys on InnoDB tables can also be found in the INNODB_SYS_FOREIGN and INNODB_SYS_FOREIGN_COLS tables in the INFORMATION_SCHEMA database Currently only InnoDB tables support foreign k...

Страница 50: ... column MySQL Server instead stores zero the smallest possible value or the largest possible value whichever is closest to the invalid value For strings MySQL stores either the empty string or as much of the string as can be stored in the column If you try to store a string that doesn t start with a number into a numeric column MySQL Server stores 0 Invalid values for ENUM and SET columns are hand...

Страница 51: ... for nontransactional tables either use single row statements or else use STRICT_TRANS_TABLES 539 if conversion warnings rather than errors are acceptable To avoid problems in the first place do not use MySQL to check column content It is safest and often faster to let the application ensure that it passes only legal values to the database With either of the strict mode options you can cause error...

Страница 52: ...of the dynamic record format Irena Pancirov irena mail yacc it Win32 port with Borland compiler mysqlshutdown exe and mysqlwatch exe David J Hughes For the effort to make a shareware SQL database At TcX the predecessor of MySQL AB we started with mSQL but found that it couldn t satisfy our purposes so instead we wrote an SQL interface to our application builder Unireg mysqladmin and mysql client a...

Страница 53: ...nd other MySQL related Java tools James Cooper pixel organic com For setting up a searchable mailing list archive at his site Rick Mehalick Rick_Mehalick i o com For xmysql a graphical X client for MySQL Server Doug Sisk sisk wix com For providing RPM packages of MySQL for Red Hat Linux Diemand Alexander V axeld vial ethz ch For providing RPM packages of MySQL for Red Hat Linux Alpha Antoni Pamies...

Страница 54: ... for MySQL Win32 Jethro Wright III jetman li net The libmysql dll library James Pereria jpereira iafrica com Mysqlmanager a Win32 GUI tool for administering MySQL Servers Curt Sampson cjs portal ca Porting of MIT pthreads to NetBSD Alpha and NetBSD 1 3 i386 Martin Ramsch m ramsch computer org Examples in the MySQL Tutorial Steve Harvey For making mysqlaccess more secure Konark IA 64 Centre of Pers...

Страница 55: ...e Google Inc for contributions to the MySQL distribution Mark Callaghan s SMP Performance patches and other patches Other contributors bugfinders and testers James H Thompson Maurizio Menghini Wojciech Tryc Luca Berra Zarko Mocnik Wim Bonis Elmar Haneke jehamby lightside psmith BayNetworks com duane connect com au Ted Deppner ted psyber com Mike Simons Jaakko Hyvatti And lots of bug report patches...

Страница 56: ...translating the documentation or error messages in MySQL Paul DuBois Ongoing help with making this manual correct and understandable That includes rewriting Monty s and David s attempts at English into English as other people know it Kim Aldale Helped to rewrite Monty s and David s early attempts at English into English Michael J Miller Jr mke terrapin turbolift com For the first MySQL manual And ...

Страница 57: ... uniag sk Slovak error messages Stefan Saroiu tzoompy cs washington edu Romanian error messages Peter Feher Hungarian error messages Roberto M Serqueira Portuguese error messages Carsten H Pedersen Danish error messages Arjen Lentz Dutch error messages completing earlier partial translation also work on consistency and spelling 1 9 3 Packages that support MySQL The following is a list of creators ...

Страница 58: ...ould not have made MySQL what it is today Free Software Foundation From whom we got an excellent compiler gcc an excellent debugger gdb and the libc library from which we have borrowed strto c to get some code working in Linux Free Software Foundation The XEmacs development team For a really great editor environment Julian Seward Author of valgrind an excellent memory checker tool that has helped ...

Страница 59: ... Design studio The MySQL Web site in use between 1998 2000 Intel Contributed to development on Windows and Linux platforms Compaq Contributed to Development on Linux Alpha SWSoft Development on the embedded mysqld version FutureQuest The skip show database 421 option ...

Страница 60: ...40 ...

Страница 61: ...ows Using a noinstall Zip Archive 79 2 10 5 Troubleshooting a MySQL Installation Under Windows 86 2 10 6 Upgrading MySQL on Windows 87 2 10 7 Windows Postinstallation Procedures 88 2 10 8 Installing MySQL from Source on Windows 90 2 11 Installing MySQL on Mac OS X 95 2 12 Installing MySQL from RPM Packages on Linux 97 2 13 Installing MySQL on Solaris 100 2 14 Installing MySQL on i5 OS 101 2 15 Ins...

Страница 62: ... and administering MySQL by themselves To install MySQL Community Server see Section 2 4 Notes for MySQL Community Server If you plan to upgrade an existing version of MySQL to a newer version rather than install MySQL for the first time see Section 2 19 1 Upgrading MySQL for information about upgrade procedures and about issues that you should consider before upgrading If you are interested in mi...

Страница 63: ...e Current user mc localhost SSL Not in use Current pager usr bin less Using outfile Using delimiter Server version 5 0 27 standard MySQL Community Edition Standard GPL Protocol version 10 Connection Localhost via UNIX socket Server characterset latin1 Db characterset latin1 Client characterset latin1 Conn characterset latin1 UNIX socket tmp mysql sock Uptime 1 day 3 hours 58 min 43 sec Threads 2 Q...

Страница 64: ... Release Notes for details on major changes between revisions of MySQL Enterprise Server You should also review the notes and advice contained within Section 2 19 1 Upgrading MySQL 2 4 Notes for MySQL Community Server 2 4 1 Overview of MySQL Community Server Installation 1 Determine whether MySQL runs and is supported on your platform Not all platforms are equally suitable for running MySQL and no...

Страница 65: ...is section lists the operating systems on which MySQL Community Server is known to run Important Oracle Corporation does not necessarily provide official support for all the platforms listed in this section For information about those platforms that are officially supported see http www mysql com support supportedplatforms html on the MySQL Web site We use GNU Autoconf so it is possible to port My...

Страница 66: ...emendously If this issue is not taken care of adding extra CPUs actually makes MySQL slower File system stability and performance MySQL s stability and performance are directly affected by those of the operating platform s file system In particular where large tables are in use performance is affected by the ability of the file system to deal with large files at all and to deal with them efficient...

Страница 67: ...lopment Source Tree These are not releases as such but are available as previews of the code on which future releases are to be based The naming scheme in MySQL 5 0 uses release names that consist of three numbers and a suffix for example mysql 5 0 14 rc The numbers within the release name are interpreted as follows The first number 5 is the major version and describes the file format All MySQL 5 ...

Страница 68: ...fferent connectors storage engines replication modes backup partitioning stored programs and so forth in various combinations Additional nonfunctional testing is done in areas of performance concurrency stress high volume upgrade and downgrade 2 4 3 2 Choosing a Distribution Format After choosing which version of MySQL to install you should decide whether to use a binary distribution or a source d...

Страница 69: ... Release Notes help you determine whether the new release has something you really want We use the following policy when updating MySQL Enterprise Server releases are meant to appear every 18 months supplemented by quarterly service packs and monthly rapid updates Community Server releases are meant to appear 2 3 times per year Releases are issued within each series For each release the last numbe...

Страница 70: ... you downloaded The correct MD5 checksum is listed on the downloads page for each MySQL product and you will compare it against the MD5 checksum of the file product that you download Each operating system and setup offers its own version of tools for checking the MD5 checksum Typically the command is named md5sum or it may be named md5 and some operating systems do not ship it at all On Linux it i...

Страница 71: ...GCZwwA6YbhGPC7FwCgp8z5TzIw4YQuL5NGJ sy 0oSazqmJASIEEAECAAwFAk53QS4FAwASdQAACgkQlxC4m8pXrXwJ8Qf be UO9mq foc2sMyhwMpN4 fdBWwfLkA12FXQDOQMvwH9HsmEjnfUgYKXschZRi DuHXe1P7l 8G2aQLubhBsQf9ejKvRFTzuWMQkdIq 6Koulxv6ofkCcv3d1xtO2W7nb5yxcpVBP rRfGFGebJvZa58DymCNgyGtAU6AOz4veavNmI2 GIDQsY66 tYDvZ CxwzdYu HD V9HmrJfc6deM0mnBn7SRjqzxJPgoTQhihTav6q R5 2p5NvQ H84OgS6GjosfGc2 duUDzCP kheMRKfzuyKCOHQPtJuIj8 gfpHt...

Страница 72: ... 30 AM CST using DSA key ID 5072E1F5 gpg Good signature from MySQL Release Engineering mysql build oss oracle com The Good signature message indicates that the file signature is valid when compared to the signature listed on our site But you might also see warnings like so shell gpg verify mysql standard 5 0 96 linux i686 tar gz asc gpg Signature made Wed 23 Jan 2013 02 25 45 AM PST using DSA key ...

Страница 73: ...l like Gpg4win You may use a different tool but our examples are based on Gpg4win and utilize its bundled Kleopatra GUI Download and install Gpg4win and then load Kleopatra The dialog should look similar to Figure 2 1 Initial screen after loading Kleopatra Next add the MySQL Release Engineering certificate Do this by clicking File Lookup Certificates on Server Type Mysql Release Engineering into t...

Страница 74: ...he Trust level Next verify the downloaded MySQL package file This requires files for both the packaged file and the signature The signature file must have the same name as the packaged file but with an appended asc extension as shown by the example in the following table The signature is linked to on the downloads page for each MySQL product You must create the asc file with this signature Table 2...

Страница 75: ...Decrypt Verify Files dialog Click Decrypt Verify to check the file The two most common results will look like the following and although the yellow warning looks problematic the following means that the file check passed with success You may now run this installer ...

Страница 76: ...gnature Checking Using Gpg4win for Windows 56 Figure 2 5 The Decrypt Verify Results Good Seeing a red The signature is bad error means the file is invalid Do not execute the MSI file if you see this error ...

Страница 77: ...rpm checksig MySQL server 5 0 96 0 glibc23 i386 rpm MySQL server 5 0 96 0 glibc23 i386 rpm md5 gpg OK Note If you are using RPM 4 1 and it complains about GPG NOT OK MISSING KEYS GPG 5072e1f5 even though you have imported the MySQL public build key into your own GPG keyring you need to import the key into the RPM keyring first RPM 4 1 no longer uses your personal GPG keyring or GPG itself Rather R...

Страница 78: ...ectories remains the same The installation directory has the following subdirectories Table 2 3 MySQL Installation Layout for Windows Directory Contents of Directory bin Client programs and the mysqld server data Log files databases examples Example programs and scripts include Include header files lib Libraries scripts Utility scripts share Miscellaneous support files including error messages cha...

Страница 79: ...d at Section 2 17 3 MySQL Source Configuration Options Table 2 6 MySQL Layout for Installation from Source Directory Contents of Directory bin Client programs and scripts include mysql Include header files Docs Manual in Info format man Unix manual pages lib mysql Libraries libexec The mysqld server share mysql Miscellaneous support files including error messages character set files sample configu...

Страница 80: ...describes the process for installing MySQL on Windows Note If you are upgrading MySQL from an existing installation older than MySQL 4 1 5 you must first perform the procedure described in Section 2 10 6 Upgrading MySQL on Windows To run MySQL on Windows you need the following A Windows operating system such as XP Vista and Server 2003 Newer versions of Windows than these are not supported Windows...

Страница 81: ... updates different files which may be identified as a potential security risk After installing MySQL Server it is recommended that you disable virus scanning on the main directory datadir 446 being used to store your MySQL table data There is usually a system built into the virus scanning software to permit certain directories to be specifically ignored during virus scanning In addition by default...

Страница 82: ...s of MySQL on a single server host and advanced users who want complete control of server configuration 2 10 2 1 Using the MySQL Installation Wizard MySQL Installation Wizard is an installer for the MySQL server that uses the latest installer technologies for Microsoft Windows The MySQL Installation Wizard in combination with the MySQL Configuration Wizard enables a user to install and configure a...

Страница 83: ... 3306 or other port of your choice into the Port number text box Also ensure that the TCP protocol radio button is selected If you wish you can also limit access to the MySQL server by choosing the Change scope button Confirm your choices by clicking the OK button If you do not open a port prior to installation you cannot configure the MySQL server immediately after installation Additionally when ...

Страница 84: ...pe gives you complete control over which packages you wish to install and the installation path that is used See Section 2 10 2 1 3 The Custom Installation Dialog for more information on performing a custom install If you choose the Typical or Complete installation types and click the Next button you advance to the confirmation screen to verify your choices and begin the installation If you choose...

Страница 85: ...new option from the drop down list that appears You can change the default installation path by clicking the Change button to the right of the displayed installation path After choosing your installation components and installation path click the Next button to advance to the confirmation dialog 2 10 2 1 4 The Confirmation Dialog Once you choose an installation type and optionally choose your inst...

Страница 86: ...Wizard Once you click the Install button the MySQL Installation Wizard begins the installation process and makes certain changes to your system which are described in the sections that follow Changes to the Registry The MySQL Installation Wizard creates one Windows registry key in a typical install situation located in HKEY_LOCAL_MACHINE SOFTWARE MySQL AB The MySQL Installation Wizard creates a ke...

Страница 87: ...ySQL server replacing the former default location C mysql By default all MySQL applications are stored in a common directory at C Program Files MySQL where Program Files is the default location for applications in your Windows installation A typical MySQL installation on a developer machine might look like this C Program Files MySQL MySQL Server 5 0 C Program Files MySQL MySQL Workbench 5 1 OSS Th...

Страница 88: ...ally when running the MySQL Server Configuration Wizard on Windows Vista or newer ensure that you are logged in as a user with administrative rights You can launch the MySQL Configuration Wizard by clicking the MySQL Server Instance Config Wizard entry in the MySQL section of the Windows Start menu Alternatively you can navigate to the bin directory of your MySQL installation and launch the MySQLI...

Страница 89: ...ce Configuration Wizard detects an existing configuration file you have the option of either reconfiguring your existing server or removing the server instance by deleting the configuration file and stopping and removing the MySQL service To reconfigure an existing server choose the Re configure Instance option and click the Next button Any existing configuration file is not overwritten but rename...

Страница 90: ...et all configuration options automatically with the exception of Service Options and Security Options The Standard Configuration sets options that may be incompatible with systems where there are existing MySQL installations If you have an existing MySQL installation on your system in addition to the installation you wish to configure the Detailed Configuration option is recommended To complete th...

Страница 91: ...is intended to run only the MySQL server It is assumed that no other applications are running The MySQL server is configured to use all available system resources Note By selecting one of the preconfigured configurations the values and settings of various options in your my cnf or my ini will be altered accordingly The default values and options as described in the reference manual may therefore b...

Страница 92: ... Database Only This option disables the InnoDB storage engine completely and dedicates all server resources to the MyISAM storage engine This option is recommended for users who do not use InnoDB The Configuration Wizard uses a template to generate the server configuration file The Database Usage dialog sets one of the following option strings Multifunctional Database MIXED Transactional Database ...

Страница 93: ...es choose a new drive from the drop down list of drive letters and choose a new path from the drop down list of paths To create a custom path click the button If you are modifying the configuration of an existing server you must click the Modify button before you change the path In this situation you must move the existing tablespace files to the new location manually before starting the server 2 ...

Страница 94: ...oncurrent connections The maximum number of connections is set at 500 Manual Setting Choose this option to set the maximum number of concurrent connections to the server manually Choose the number of concurrent connections from the drop down box provided or enter the maximum number of connections into the drop down box if the number you desire is not listed 2 10 3 8 The Networking and Strict Mode ...

Страница 95: ...erver SQL Mode to either enable or disable strict mode Enabling strict mode default makes MySQL behave more like other database management systems If you run applications that rely on MySQL s old forgiving behavior make sure to either adapt those applications or to disable strict mode For more information about strict mode see Section 5 1 7 Server SQL Modes 2 10 3 9 The Character Set Dialog The My...

Страница 96: ...rver can be installed as a Windows service When installed this way the MySQL server can be started automatically during system startup and even restarted automatically by Windows in the event of a service failure The MySQL Server Instance Configuration Wizard installs the MySQL server as a service by default using the service name MySQL If you do not wish to install the service uncheck the box nex...

Страница 97: ...ons such as MySQL 5 0 56 as mysql50056 To install the MySQL server as a service but not have it started automatically at startup uncheck the box next to the Launch the MySQL Server Automatically option 2 10 3 11 The Security Options Dialog It is strongly recommended that you set a root password for your MySQL server and the MySQL Server Instance Configuration Wizard requires by default that you do...

Страница 98: ...rformed The MySQL Server Instance Configuration Wizard first determines configuration file options based on your choices using a template prepared by MySQL developers and engineers This template is named my template ini and is located in your server installation directory The MySQL Configuration Wizard then writes these options to the corresponding configuration file If you chose to create a servi...

Страница 99: ... may extract the archive to a folder within your chosen installation location If this occurs you can move the contents of the subfolder into the chosen installation location 2 10 4 2 Creating an Option File If you need to specify startup options when you run the server you can indicate them on the command line or place them in an option file For options that are used every time the server starts y...

Страница 100: ...xample if MySQL is installed in C Program Files MySQL MySQL Server 5 0 the data directory is by default in C Program Files MySQL MySQL Server 5 0 data If you want to use E mydata as the data directory instead you must do two things 1 Move the entire data directory and all of its contents from C Program Files MySQL MySQL Server 5 0 data to E mydata 2 Use a datadir 404 option to specify the new data...

Страница 101: ...lients can connect through shared memory by using the protocol MEMORY 231 option For information about which server binary to run see Section 2 10 4 3 Selecting a MySQL Server Type Testing is best done from a command prompt in a console window or DOS window In this way you can have the server display status messages in the window where they are easy to see If something is wrong with your configura...

Страница 102: ... u root shutdown Note If the MySQL root user account has a password you need to invoke mysqladmin with the p option and supply the password when prompted This command invokes the MySQL administrative utility mysqladmin to connect to the server and tell it to shut down The command connects as the MySQL root user which is the default administrative account in the MySQL grant system Note that users i...

Страница 103: ...ATH value can leave you with a malfunctioning or even unusable system 2 10 4 7 Starting MySQL as a Windows Service On Windows the recommended way to run MySQL is to install it as a Windows service whereby MySQL starts and stops automatically when Windows starts and stops A MySQL server installed as a service can also be controlled from the command line using NET commands or with the graphical Serv...

Страница 104: ...our Windows PATH if you are running multiple MySQL servers on the same machine Warning You must exercise great care when editing your system PATH by hand accidental deletion or modification of any portion of the existing PATH value can leave you with a malfunctioning or even unusable system The following additional arguments can be used when installing the service You can specify a service name im...

Страница 105: ...not case sensitive When run as a service mysqld has no access to a console window so no messages can be seen there If mysqld does not start check the error log to see whether the server wrote any messages there to indicate the cause of the problem The error log is located in the MySQL data directory for example C Program Files MySQL MySQL Server 5 0 data It is the file with a suffix of err When a ...

Страница 106: ...s is the console messages displayed when the MySQL service is starting Use the NET START MySQL command from the command line after installing mysqld as a service to see any error messages regarding the starting of the MySQL server as a service See Section 2 10 4 7 Starting MySQL as a Windows Service The following examples show other common error messages you may encounter when installing MySQL and...

Страница 107: ...n using the configuration wizard This enables the new service to be installed correctly but leaves the outdated service in place Although this is harmless it is best to remove old services that are no longer in use To permanently remove the old mysql service execute the following command as a user with administrative privileges on the command line shell sc delete mysql SC DeleteService SUCCESS If ...

Страница 108: ...strator run mysql_upgrade to check your tables attempt to repair them if necessary and update your grant tables if they have changed so that you can take advantage of any new capabilities See Section 4 4 9 mysql_upgrade Check Tables for MySQL Upgrade 11 If you encounter errors see Section 2 10 5 Troubleshooting a MySQL Installation Under Windows 2 10 7 Windows Postinstallation Procedures On Window...

Страница 109: ... the u root and p options if you have already secured the initial MySQL accounts With p you will be prompted for the root password For example C C mysql bin mysqlshow u root p Enter password enter root password here Databases information_schema mysql test If you specify a database name mysqlshow displays a list of the tables within the database C C mysql bin mysqlshow mysql Database mysql Tables c...

Страница 110: ...soft Visual Studio 2005 Professional Edition ENU KB932232 To build from the standard source distribution you will need CMake which can be downloaded from http www cmake org After installing modify your PATH environment variable to include the directory where cmake is located Microsoft Visual C 2005 Express Edition Visual Studio Net 2003 7 1 or Visual Studio 2005 8 0 compiler system If you are usin...

Страница 111: ...ion for example mysql 5 0 96 tar gz You build from the same distribution as used to build MySQL on Unix Linux and other platforms Do not use the Windows Source distributions as they do not contain the necessary configuration script and other files Follow this procedure to build MySQL 1 If you are installing from a packaged source distribution create a work directory for example C workdir and unpac...

Страница 112: ...ent Remember the configuration that you use in this step It is important later when you run the test script because that script needs to know which configuration you used 6 You should test you build before installation See Section 2 10 8 4 Testing a Windows Source Build 7 To install use the instructions in Section 2 10 8 3 Installing MySQL from a Source Build on Windows 2 10 8 2 Building MySQL fro...

Страница 113: ...built executables and support files that you can unpack to your desired installation location It is also possible to install MySQL by copying directories and files manually 1 Create the directories where you want to install MySQL For example to install into C mysql use these commands shell mkdir C mysql shell mkdir C mysql bin shell mkdir C mysql data shell mkdir C mysql share shell mkdir C mysql ...

Страница 114: ...n or ActiveState Perl to run it You may also need to install the modules required by the script To run the test script change location into the mysql test directory under the work directory set the MTR_VS_CONFIG environment variable to the configuration you selected earlier or use the vs config option and invoke mysql test run pl For example using Cygwin and the bash shell shell cd mysql test shel...

Страница 115: ...file double click the package icon This launches the Mac OS X Package Installer which guides you through the installation of MySQL Due to a bug in the Mac OS X package installer you may see this error message in the destination disk selection dialog You cannot install this software on this disk null If this error occurs simply click the Go Back button once to return to the previous screen Then cli...

Страница 116: ... to install it The Startup Item need be installed only once There is no need to install it each time you upgrade the MySQL package later The Startup Item for MySQL is installed into Library StartupItems MySQLCOM Before MySQL 4 1 2 the location was Library StartupItems MySQL but that collided with the MySQL Startup Item installed by Mac OS X Server Startup Item installation adds a variable MYSQLCOM...

Страница 117: ...eipt directories located in Library Receipts mysql VERSION pkg 2 12 Installing MySQL from RPM Packages on Linux The recommended way to install MySQL on RPM based Linux distributions is by using the RPM packages The RPMs that we provide to the community should work on all versions of Linux that support RPM packages and use glibc 2 3 We also provide RPMs with binaries that are statically linked to a...

Страница 118: ...Server builds available from MySQL 5 0 27 on MySQL server VERSION glibc23 i386 rpm MySQL server community VERSION glibc23 i386 rpm The MySQL server You need this unless you only want to connect to a MySQL server running on another machine MySQL client VERSION glibc23 i386 rpm MySQL client community VERSION glibc23 i386 rpm The standard MySQL client programs You probably always want to install this...

Страница 119: ...nity VERSION glibc23 i386 rpm This package includes the MySQL test suite MySQL VERSION src rpm This contains the source code for all of the previous packages It can also be used to rebuild the RPMs on other architectures for example Alpha or SPARC The suffix of RPM package names following the VERSION value has the following syntax PLATFORM CPU rpm The PLATFORM and CPU values indicate the type of s...

Страница 120: ...nary installation section See Section 2 16 Installing MySQL from Generic Binaries on Other Unix Like Systems Note The accounts that are listed in the MySQL grant tables initially have no passwords After starting the server you should set up passwords for them using the instructions in Section 2 18 Postinstallation Setup and Testing During RPM installation a user named mysql and a group named mysql...

Страница 121: ...rary file pkgchk l p file_name For additional information about installing MySQL on Solaris see Section 2 20 3 Solaris Notes 2 14 Installing MySQL on i5 OS The i5 OS POWER MySQL package was created in cooperation with IBM MySQL works within the Portable Application Solution Environment PASE on the System i series of hardware and will also provide database services for the Zend Core for i5 OS MySQL...

Страница 122: ...1 On the System i machine create a save file that will be used to receive the downloaded installation save file The file should be located within the General Purpose Library QGPL CRTSAVF FILE QGPL MYSQLINST TESXT MySQL Save file 2 Download the MySQL installation save file in 32 bit mysql 5 0 82 i5os power 32bit savf or 64 bit mysql 5 0 82 i5os power 64bit savf from MySQL Downloads 3 You need to FT...

Страница 123: ...te the installation file DLTLIB LIB MYSQLINST Upgrading an existing MySQL instance You need to execute the upgrade command MYSQLINST UPGMYSQL Note You cannot use MYSQLINST UPGMYSQL to upgrade between major versions of MySQL for example from 5 0 to 5 1 For information and advice on migrating between major versions you can use the advice provided in Section 2 19 1 2 Upgrading from MySQL 4 1 to 5 0 Y...

Страница 124: ...qld may be unable to read the files located within the MySQL data directory and the execution will fail 2 Enter the PASE environment using call qp2term 3 Start the MySQL server by changing to the installation directory and running mysqld_safe specifying the user name used to install the server The installer conveniently installs a symbolic link to the installation directory mysql 5 0 42 i5os power...

Страница 125: ... 2 5 How to Get MySQL To host MySQL the NetWare server must meet these requirements The latest Support Pack of NetWare 6 5 must be installed The system must meet Novell s minimum requirements to run the respective version of NetWare MySQL data and the program binaries must be installed on an NSS volume traditional volumes are not supported To install MySQL for NetWare use the following procedure 1...

Страница 126: ...s known to have problems on NetWare 6 0 the problem has been eliminated in NetWare 6 5 Note that the use of MySQL on Netware 6 0 is not officially supported mysqld_safe on NetWare provides a screen presence When you unload shut down the mysqld_safe NLM the screen does not go away by default Instead it prompts for user input NLM has terminated Press any key to close the screen If you want NetWare t...

Страница 127: ...ad and install GNU tar or if available use a preinstalled version of GNU tar Usually this is available as gnutar gtar or as tar within a GNU or Free Software directory such as usr sfw bin or usr local bin GNU tar is available from http www gnu org software tar Warning If you have previously installed MySQL using your operating system native package management system such as yum or apt get you may ...

Страница 128: ...ck the distribution and change location into it The example here unpacks the distribution under usr local The instructions therefore assume that you have permission to create files and directories in usr local If that directory is protected you must perform the installation as root shell cd usr local Obtain a distribution file using the instructions in Section 2 5 How to Get MySQL For a given rele...

Страница 129: ...ndows XP or newer required see Section 2 10 8 Installing MySQL from Source on Windows For information on building from one of our development trees see Section 2 17 2 Installing MySQL from a Development Source Tree For information on using the configure command to specify the source build parameters including links to platform specific parameters that you might need see Section 2 17 3 MySQL Source...

Страница 130: ... file source distribution is similar to the process for installing from a generic binary distribution that is detailed in Section 2 16 Installing MySQL from Generic Binaries on Other Unix Like Systems For a MySQL tar gz source distribution the basic installation command sequence looks like this Preconfiguration setup shell groupadd mysql shell useradd g mysql mysql Beginning of source build specif...

Страница 131: ...e unpacked distribution shell cd mysql VERSION Note that currently you must configure and build MySQL from this top level directory You cannot build it in a different directory 7 Configure the release and compile everything shell configure prefix usr local mysql shell make When you run configure you might want to specify other options For example if you need to debug mysqld or a MySQL client run c...

Страница 132: ...mysql_install_db to create the grant tables for MySQL you must restart the server manually The mysqld_safe command to do this is shown in a later step 12 Most of the MySQL installation can be owned by root if you like The exception is that the data directory must be owned by mysql To accomplish this run the following commands as root in the installation directory shell chown R root shell chown R m...

Страница 133: ...d release distribution either a binary or source distribution See Section 2 5 How to Get MySQL To obtain the source tree you must have Bazaar installed The Bazaar VCS Web site has instructions for downloading and installing Bazaar on different platforms Bazaar is supported on any platform that supports Python and is therefore compatible with any Linux Unix Windows or Mac OS X host MySQL developmen...

Страница 134: ...he branch initially update it using the pull option periodically Use this command in the top level directory of the local copy shell bzr pull You can examine the changeset comments for the tree by using the log option to bzr shell bzr log You can also browse changesets comments and source code online at the Launchpad MySQL Server page If you see diffs changes or code that you have a question about...

Страница 135: ...lation If you already have MySQL installed and do not want to overwrite it run configure with values for the prefix 121 with tcp port 121 and with unix socket path 121 options different from those used by your production server For additional information about preventing multiple servers from interfering with each other see Section 5 3 Running Multiple MySQL Instances on One Machine 5 Play hard wi...

Страница 136: ...rge files disable libtool lock Disable libtool lock disable profiling Build a version without query profiling code 5 0 37 5 0 45 enable FEATURE Enable FEATURE enable assembler Use assembler versions of some string functions if available enable dependency tracking Do not reject slow dependency extractors enable fast install Optimize for fast installation yes enable local infile Enable LOCAL for LOA...

Страница 137: ...ix SUFFIX Append SUFFIX to installed program names program transform name PROGRAM run sed PROGRAM on installed program names q Do not print checking messages quiet sbindir DIR System administrative executables EPREFIX sbin sharedstatedir DIR Modifiable architecture independent data PREFIX com srcdir DIR Find the sources in DIR configure directory or sysconfdir DIR Read only single machine data PRE...

Страница 138: ...ith embedded server 121 Build the embedded server with example storage engine Enable the Example Storage Engine no with extra charsets 122 Use charsets in addition to default with gnu ld Assume the C compiler uses GNU ld no with isam Enable the ISAM table type 5 0 2 with lib ccflags Extra CC options for libraries with libwrap DIR Compile in libwrap tcp_wrappers support with low memory 124 Try to u...

Страница 139: ...r shared memory transporter 5 0 2 with ndb test Include the NDB Cluster ndbapi test programs with ndbcluster Include the NDB Cluster table handler no with openssl DIR Include the OpenSSL support with openssl includes Find OpenSSL headers in DIR with openssl libs Find OpenSSL libraries in DIR with other libc DIR Link against libc and other standard libraries installed in the specified nonstandard l...

Страница 140: ...t readline Use system readline instead of bundled copy without server 120 Only build the client without uca Skip building of the national Unicode collations 5 0 3 Some of the configure options available are described here For options that may be of use if you have difficulties building MySQL see Section 2 17 4 Dealing with Problems Compiling MySQL Many options configure compile time defaults that ...

Страница 141: ... server listens for TCP IP connections The default is port 3306 To listen on a different port use a configure command like this shell configure with tcp port 3307 On Unix if you want the MySQL socket file location to be somewhere other than the default location normally in the directory tmp or var run use a configure command like this shell configure with unix socket path usr local mysql tmp mysql...

Страница 142: ...ult set use the with charset 122 option shell configure with charset CHARSET CHARSET may be one of binary armscii8 ascii big5 cp1250 cp1251 cp1256 cp1257 cp850 cp852 cp866 cp932 dec8 eucjpms euckr gb2312 gbk geostd8 greek hebrew hp8 keybcs2 koi8r koi8u latin1 latin2 latin5 latin7 macce macroman sjis swe7 tis620 ucs2 ujis utf8 Additional character sets might be available Check the output from confi...

Страница 143: ...ong rather than unsigned long This enables tables to hold up to approximately 1 844E 19 2 32 2 rows rather than 2 32 4 295E 09 rows Previously it was necessary to pass DBIG_TABLES to the compiler manually in order to enable this feature Run configure with the disable grant options 123 option to cause the bootstrap 402 skip grant tables 420 and init file 409 options for mysqld to be disabled For Wi...

Страница 144: ... you have so much memory and swap space that you think you can t possibly have run out This problem has been observed to occur even on systems with generous hardware configurations and the with low memory 124 option usually fixes it By default configure picks c as the compiler name and GNU c links with lg If you are using gcc that behavior can cause problems during configuration such as this confi...

Страница 145: ... of make to GNU make make Fatal error in reader Makefile line 18 Badly formed macro assignment Or make file Makefile line 18 Must be a separator Or pthread h No such file or directory Solaris and FreeBSD are known to have troublesome make programs GNU make 3 75 is known to work The sql_yacc cc file is generated from sql_yacc yy Normally the build process does not need to create sql_yacc cc because...

Страница 146: ... enable MySQL to be compiled with optimizations enabled The standard MySQL binary distributions are compiled with support for all character sets When you compile MySQL yourself you should include support only for the character sets that you are going to use This is controlled by the with charset 122 option to configure Here is a list of some measurements that we have made If you link dynamically w...

Страница 147: ...SQL Access Privilege System and Section 6 3 MySQL User Account Management 2 18 1 Unix Postinstallation Procedures After installing MySQL on Unix you must initialize the grant tables start the server and make sure that the server works satisfactorily You may also wish to arrange for the server to be started and stopped automatically when your system starts and stops You should also assign passwords...

Страница 148: ...ribute of the files to the mysql user The second changes the group attribute to the mysql group 3 If necessary run the mysql_install_db program to set up the initial MySQL grant tables containing the privileges that determine how users are permitted to connect to the server You will need to do this if you used a distribution type for which the installation procedure does not run the program for yo...

Страница 149: ...plugin directory the directory named by the plugin_dir 481 system variable is writable by the server it may be possible for a user to write executable code to a file in the directory using SELECT INTO DUMPFILE This can be prevented by making plugin_dir 481 read only to the server or by setting secure file priv 419 to a directory where SELECT writes can be made safely 6 If you installed MySQL using...

Страница 150: ... version shell bin mysqladmin variables The output from mysqladmin version varies slightly depending on your platform and version of MySQL but should be similar to that shown here shell bin mysqladmin version mysqladmin Ver 14 12 Distrib 5 0 96 for pc linux gnu on i686 Server version 5 0 96 Protocol version 10 Connection Localhost via UNIX socket UNIX socket var lib mysql mysql sock Uptime 14 days...

Страница 151: ...inst different databases and platforms To run all tests execute these commands shell cd sql bench shell perl run all tests If you do not have the sql bench directory you probably installed MySQL using RPM files other than the source RPM The source RPM includes the sql bench benchmark directory In this case you must first install the benchmark suite before you can use it There are separate benchmar...

Страница 152: ...sql_install_db is located in the bin directory and the data directory is named data To rename the mysql database and re run mysql_install_db use these commands shell mv data mysql data mysql old shell bin mysql_install_db user mysql When you run mysql_install_db you might encounter the following problems mysql_install_db fails to install the grant tables You may find that mysql_install_db fails to...

Страница 153: ...lts you can modify mysql_install_db before you run it However it is preferable to use GRANT and REVOKE to change the privileges after the grant tables have been set up In other words you can run mysql_install_db and then use mysql u root mysql to connect to the server as the MySQL root user so that you can issue the necessary GRANT and REVOKE statements If you want to install MySQL on several mach...

Страница 154: ...p the server To start or stop the server manually using the mysql server script invoke it with start or stop arguments shell mysql server start shell mysql server stop Before mysql server starts the server it changes location to the MySQL installation directory and then invokes mysqld_safe If you want the server to run as some specific user add an appropriate user option to the mysqld group of the...

Страница 155: ...es present within the directory are silently ignored In other words on FreeBSD you should install the mysql server script as usr local etc rc d mysql server sh to enable automatic startup As an alternative to the preceding setup some operating systems also use etc rc local or etc init d boot local to start additional services on startup To start up MySQL using this method you could append a comman...

Страница 156: ...ate a my cnf file and specify startup options for the engines that you plan to use If you are going to use storage engines that support transactional tables InnoDB BDB NDB be sure that you have them configured the way you want before starting the server If you are using InnoDB tables see Section 14 2 1 InnoDB Configuration If you are using BDB Berkeley DB tables see Section 14 5 3 BDB Startup Opti...

Страница 157: ...e if the data directory is usr local mysql var use this command shell ls la usr local mysql var If the data directory or its files or subdirectories are not owned by the login account that you use for running the server change their ownership to that account If the account is named mysql use these commands shell chown R mysql usr local mysql var shell chgrp R mysql usr local mysql var If it possib...

Страница 158: ...port that mysqld is trying to use You will need to track down what program this is and disable it or else tell mysqld to listen to a different port with the port 417 option In this case you will also need to specify the port number for client programs when connecting to the server using TCP IP Another reason the port might be inaccessible is that you have a firewall running that blocks connections...

Страница 159: ... differ on your system but the presence of accounts with empty passwords means that your MySQL installation is unprotected until you do something about it You should assign a password to each MySQL root account If you want to prevent clients from connecting as anonymous users without a password you should either assign a password to each anonymous account or else remove the accounts In addition th...

Страница 160: ... FOR root localhost PASSWORD newpwd mysql SET PASSWORD FOR root 127 0 0 1 PASSWORD newpwd mysql SET PASSWORD FOR root host_name PASSWORD newpwd You can also use a single statement that assigns a password to all root accounts by using UPDATE to modify the mysql user table directly This method works on any platform shell mysql u root mysql UPDATE mysql user SET Password PASSWORD newpwd WHERE User ro...

Страница 161: ... root p Enter password enter root password here mysql UPDATE mysql user SET Password PASSWORD newpwd WHERE User mysql FLUSH PRIVILEGES The FLUSH statement causes the server to reread the grant tables Without it the password change remains unnoticed by the server until you restart it Removing Anonymous Accounts If you prefer to remove any anonymous accounts rather than assigning them passwords do s...

Страница 162: ...the following checklist as a guide Before any upgrade back up your databases including the mysql database that contains the grant tables See Section 7 2 Database Backup Methods Read all the notes in Section 2 19 1 2 Upgrading from MySQL 4 1 to 5 0 These notes enable you to identify upgrade issues that apply to your current MySQL installation Some incompatibilities discussed in that section require...

Страница 163: ...ands out of sync or unexpected core dumps you probably have used old header or library files when compiling your programs In this case you should check the date for your mysql h file and libmysqlclient a library to verify that they are from the new MySQL distribution If not recompile your programs with the new headers and libraries Recompilation might also be necessary for programs compiled agains...

Страница 164: ...upgrading may damage the table See Section 13 7 2 6 REPAIR TABLE Syntax Before upgrading to a new version of MySQL Section 2 19 3 Checking Whether Tables or Indexes Must Be Rebuilt to see whether changes to table formats or to character sets or collations were made between your current version of MySQL and the version to which you are upgrading If so and these changes result in an incompatibility ...

Страница 165: ...s ignored or the comparison could be performed as a string comparison To mimic the old behavior use the CAST 948 function to cause the comparison operands to be treated as previously For example date_col CAST NOW AS DATE Incompatible change For ENUM columns that had enumeration values containing commas the commas were mapped to 0xff internally However this rendered the commas indistinguishable fro...

Страница 166: ...run OPTIMIZE TABLE or REPAIR TABLE if it is a MyISAM table Incompatible change As of MySQL 5 0 3 trailing spaces no longer are removed from values stored in VARCHAR and VARBINARY columns The maximum lengths for VARCHAR and VARBINARY columns in MySQL 5 0 3 and later are 65 535 characters and 65 535 bytes respectively When a binary upgrade file system level copy of data files to MySQL 5 0 is perform...

Страница 167: ...columns For example ALTER TABLE tbl_name MODIFY col_name DECIMAL 4 1 The behavior used by the server for DECIMAL columns in a table depends on the version of MySQL used to create the table If your server is from MySQL 5 0 3 or higher but you have DECIMAL columns in tables that were created before 5 0 3 the old behavior still applies to those columns To convert the tables to the newer DECIMAL forma...

Страница 168: ...es were passed as REAL_RESULT values prior to MySQL 5 0 3 As of 5 0 3 they are passed as strings with a type of DECIMAL_RESULT If you upgrade to 5 0 3 and find that your UDF now receives string values use the initialization function to coerce the arguments to numbers as described in Section 21 2 2 3 UDF Argument Processing Incompatible change As of MySQL 5 0 3 the server by default no longer loads...

Страница 169: ... are invalid even if they appear to function as you expect and should be rewritten To find affected handlers use mysqldump to dump all stored procedures and functions triggers and events Then attempt to reload them into an upgraded server Handlers that contain illegal label references will be rejected For more information about condition handlers and writing them to avoid invalid jumps see Section...

Страница 170: ...omparison you can produce a result string in a nonbinary character set by adding a USING clause or converting the result mysql SELECT CHAR ORD A USING latin1 a CHAR ORD A USING latin1 a 1 mysql SELECT CONVERT CHAR ORD A USING latin1 a CONVERT CHAR ORD A USING latin1 a 1 Incompatible change Beginning with MySQL 5 0 12 natural joins and joins with USING including outer join variants are processed ac...

Страница 171: ...As of MySQL 5 0 13 the expression is evaluated and retains its unsigned attribute for the assignment The value of 18446744073709551615 is clipped to the nearest endpoint of the column range resulting in a value of 255 mysql UPDATE t SET i i 1 SELECT i FROM t i 255 To get the older behavior use CAST 948 to convert the expression result to a signed value UPDATE t SET i CAST i 1 AS SIGNED Alternative...

Страница 172: ...ction 9 3 Reserved Words The LOAD DATA FROM MASTER and LOAD TABLE FROM MASTER statements are deprecated See Section 13 4 2 2 LOAD DATA FROM MASTER Syntax for recommended alternatives As of MySQL 5 0 25 TIMESTAMP columns that are NOT NULL now are reported that way by SHOW COLUMNS and INFORMATION_SCHEMA rather than as NULL Comparisons made between FLOAT or DOUBLE values that happened to work in MySQ...

Страница 173: ...r you perform a downgrade Read the upgrading section for the release series from which you are downgrading to be sure that it does not have any features you really need See Section 2 19 1 Upgrading MySQL If there is a downgrading section for that version you should read that as well To see which new features were added between the version to which you are downgrading and your current version see t...

Страница 174: ...red routines or triggers If your databases contain stored routines or triggers prevent them from being dumped when you use mysqldump by using the skip routines 304 and skip triggers 305 options See Section 4 5 4 mysqldump A Database Backup Program MySQL 4 1 does not support views If your databases contain views remove them with DROP VIEW before using mysqldump See Section 13 1 19 DROP VIEW Syntax ...

Страница 175: ...character sort order which causes the ordering of entries in any index that uses an affected character set or collation to be incorrect Such changes result in several possible problems Comparison results that differ from previous results Inability to find some index values due to misordered index entries Misordered ORDER BY results Tables that CHECK TABLE reports as being in need of repair The sol...

Страница 176: ...e Bug 39585 MySQL 5 0 48 5 1 21 Bug 29461 Affects indexes for columns that use any of these character sets eucjpms euc_kr gb2312 latin7 macce ujis Affected tables can be detected by CHECK TABLE FOR UPGRADE as of MySQL 5 1 29 5 4 0 see Bug 39585 2 19 4 Rebuilding or Repairing Tables or Indexes This section describes how to rebuild a table This can be necessitated by changes to MySQL such as how dat...

Страница 177: ...ut which storage engines REPAIR TABLE supports see Section 13 7 2 6 REPAIR TABLE Syntax mysqlcheck repair provides command line access to the REPAIR TABLE statement This can be a more convenient means of repairing tables because you can use the databases 291 or all databases 290 option to repair all tables in specific databases or all databases respectively shell mysqlcheck repair databases db_nam...

Страница 178: ...ss db_name mysql db_name You can also store the dump in a file transfer the file to the target machine and then load the file into the database there For example you can dump a database to a compressed file on the source machine like this shell mysqldump quick db_name gzip db_name gz Transfer the file containing the database contents to the target machine and run these commands there shell mysqlad...

Страница 179: ...the fastest stable compiler available The binary release is linked with static which means you do not normally need to worry about which version of the system libraries you have You need not install LinuxThreads either A program linked with static is slightly larger than a dynamically linked program but also slightly faster 3 to 5 However one problem with a statically linked program is that you ca...

Страница 180: ... choice in most cases After reading the following text if you are in doubt about what to do try our binary first to determine whether it meets your needs If you discover that it is not good enough you may want to try your own build In that case we would appreciate a note about it so that we can build a better binary next time MySQL uses LinuxThreads on Linux If you are using an old Linux version t...

Страница 181: ...r library or compiler related If this is the case using our binary resolves them If you link your own MySQL client programs you may see the following error at runtime ld so 1 fatal libmysqlclient so open failed No such file or directory This problem can be avoided by one of the following methods Link clients with the Wl r full path to libmysqlclient so flag rather than with Lpath Copy libmysqclien...

Страница 182: ...ild MySQL yourself you can patch LinuxThreads for better stack use See Section 2 20 1 3 Linux Source Distribution Notes If you do not want to patch LinuxThreads you should set max_connections 467 to a value no higher than 500 It should be even less if you have a large key buffer large heap tables or some other things that make mysqld allocate a lot of memory or if you are running a 2 2 kernel with...

Страница 183: ...ould also work There have been some problems with the glibc RPMs from Red Hat so if you have problems check whether there are any updates The glibc 2 0 7 19 and 2 0 7 29 RPMs are known to work If you are using Red Hat 8 0 or a new glibc 2 2 x library you may see mysqld die in gethostbyaddr This happens because the new glibc library requires a stack size greater than 128KB for this call To fix the ...

Страница 184: ...ly to avoid library problems The configure command looks like this CC ccc CFLAGS fast arch generic CXX cxx CXXFLAGS fast arch generic noexceptions nortti configure prefix usr local mysql disable shared with extra charsets complex enable thread safe client with mysqld ldflags non_shared with client ldflags non_shared Some known problems when running MySQL on Linux Alpha Debugging threaded applicati...

Страница 185: ...t major problems on Mac OS X 10 x Darwin Known issues If you have problems with performance under heavy load try using the skip thread priority 422 option to mysqld This runs all threads with the same priority On Mac OS X this gives better performance at least until Apple fixes its thread scheduler The connection times wait_timeout 506 interactive_timeout 457 and net_read_timeout 478 values are no...

Страница 186: ...stem you can get 4 better performance by adding mcpu v8 Wa xarch v8plusa to the CFLAGS and CXXFLAGS environment variables If you have Sun s Forte 5 0 or newer compiler you can run configure like this CC cc CFLAGS Xa fast native xstrconst mt CXX CC CXXFLAGS noex mt configure prefix usr local mysql enable assembler To create a 64 bit binary with Sun s Forte compiler use the following configuration o...

Страница 187: ...compile it with your current gcc compiler At least for Solaris 2 5 almost all binary versions of gcc have old unusable include files that break all programs that use threads and possibly other programs as well Solaris does not provide static versions of all system libraries libpthreads and libdl so you cannot compile MySQL with static If you try to do so you get one of the following errors ld fata...

Страница 188: ... You may see the following error when you use gcc usr include widec h 42 warning getwc redefined usr include wchar h 326 warning this is the location of the previous definition If this occurs you can fix the problem by copying usr include widec h to lib gcc lib os gcc version include and changing line 41 from this if defined lint defined __lint To this if defined lint defined __lint defined getwc ...

Страница 189: ...client ports available at http www freebsd org Using these ports gives you the following benefits A working MySQL with all optimizations enabled that are known to work on your version of FreeBSD Automatic configuration and build Startup scripts installed in usr local etc rc d The ability to use pkg_info L to see which files are installed The ability to use pkg_delete to remove MySQL if you no long...

Страница 190: ...ction C 5 2 18 File Not Found and Similar Errors Start the server by using the open files limit 248 option for mysqld_safe or raise the limits for the mysqld user in etc login conf and rebuild it with cap_mkdb etc login conf Also be sure that you set the appropriate class for this user in the password file if you are not using the default use chpass mysqld user name See Section 4 3 2 mysqld_safe M...

Страница 191: ...ix usr local mysql with unix socket path var mysql mysql sock You can change the directory locations if you wish or just use the defaults by not specifying any locations If you have problems with performance under heavy load try using the skip thread priority 422 option to mysqld This runs all threads with the same priority On BSDI 3 1 this gives better performance at least until BSDI fixes its th...

Страница 192: ...ce include felide constructors fno exceptions fno rtti CXX gcc configure with pthread with named thread libs ldce prefix usr local mysql disable shared The following configure line should work with gcc 3 1 CFLAGS DHPUX I opt dce include O3 fPIC CXX gcc CXXFLAGS DHPUX I opt dce include felide constructors fno exceptions fno rtti O3 fPIC configure prefix usr local mysql with extra charsets complex e...

Страница 193: ...gure with extra character set complex You can ignore any errors of the following type aCC warning 901 unknown option 3 use help for online documentation If you get the following error from configure verify that you do not have the path to the K R compiler before the path to the HP UX C and C compiler checking for cc option to accept ANSI C no configure error MySQL requires an ANSI C compiler and a...

Страница 194: ...er2 power or powerpc may need to be used Alternatively you might need to use 604 or 604e We are not positive but suspect that power would likely be safe most of the time even on a power2 machine If you do not know what your CPU is execute a uname m command It produces a string that looks like 000514676700 with a format of xxyyyyyymmss where xx and ss are always 00 yyyyyy is a unique system ID and ...

Страница 195: ... gcc 3 3 2 are similar to those for using gcc 2 95 in particular the need to edit config h and my_config h after running configure However before running configure you should also patch the curses h file as follows opt freeware lib gcc lib powerpc ibm aix5 2 0 0 3 3 2 include curses h ORIG Mon Dec 26 02 17 28 2005 opt freeware lib gcc lib powerpc ibm aix5 2 0 0 3 3 2 include curses h Mon Dec 26 02...

Страница 196: ... this nohup mysqld options nohup causes the command following it to ignore any SIGHUP signal sent from the terminal Alternatively start the server by running mysqld_safe which invokes mysqld using nohup for you See Section 4 3 2 mysqld_safe MySQL Server Startup Script If you get a problem when compiling mysys get_opt c just remove the define _NO_PROTO line from the start of that file If you are us...

Страница 197: ...pthread CFLAGS O4 ansi_alias ansi_args fast inline speed speculate all arch host CXX cxx pthread CXXFLAGS O4 ansi_alias ansi_args fast inline speed speculate all arch host noexceptions nortti export CC CFLAGS CXX CXXFLAGS configure prefix usr mysql mysql with mysqld ldflags all static disable shared with named thread libs lmach lexc lc In some versions of OSF 1 the alloca function is broken Fix th...

Страница 198: ...ove the HAVE_TERM_H line as well SGI recommends that you install all the patches on this page as a set http support sgi com surfzone patches patchset 6 2_indigo rps html At the very minimum you should install the latest kernel rollup the latest rld rollup and the latest libc rollup You definitely need all the POSIX patches on this page for pthreads support http support sgi com surfzone patches pat...

Страница 199: ...sco com pub openserver5 for OpenServer 5 0 0 6 and ftp ftp sco com pub openserverv5 507 for OpenServer 5 0 7 SCO provides information about security fixes at ftp ftp sco com pub security OpenServer for OpenServer 5 0 x The maximum file size on an OpenServer 5 0 x system is 2GB The total memory which can be allocated for streams buffers clists and lock records cannot exceed 60MB on OpenServer 5 0 x...

Страница 200: ...88 NSTRPAGES 500 0 8000 STRSPLITFRAC 80 50 100 NLOG 3 3 3 NUMSP 64 1 256 NUMTIM 16 1 8192 NUMTRW 16 1 8192 Semaphore Parameters SEMMAP 10 10 8192 SEMMNI 10 10 8192 SEMMNS 60 60 8192 SEMMNU 30 10 8192 SEMMSL 25 25 150 SEMOPM 10 10 1024 SEMUME 10 10 25 SEMVMX 32767 32767 32767 SEMAEM 16384 16384 16384 Shared Memory Parameters SHMMAX 524288 131072 2147483647 SHMMIN 1 1 1 SHMMNI 100 100 2000 FILE 0 10...

Страница 201: ...tar gz You can also get a precompiled package from ftp ftp zenez com pub zenez prgms FSU threads 3 14 tar gz FSU Pthreads can be compiled with SCO Unix 4 2 with tcpip or using OpenServer 3 0 or Open Desktop 3 0 OS 3 0 ODT 3 0 with the SCO Development System installed using a good port of GCC 2 5 x For ODT or OS 3 0 you need a good port of GCC 2 5 x There are a lot of problems without a good port T...

Страница 202: ...sted in custom as erg711905 dscr_remap security patch version 2 0 0 breaks FSU threads and makes mysqld unstable You have to remove this one if you want to run mysqld on an OpenServer 5 0 6 machine If you use SCO OpenServer 5 you may need to recompile FSU pthreads with DDRAFT7 in CFLAGS Otherwise InnoDB may hang at a mysqld startup SCO provides operating system patches at ftp ftp sco com pub opens...

Страница 203: ...L Select whichever distribution you wish to install and after download extract the tar archive into an empty directory For example shell mkdir tmp mysql pro shell cd tmp mysql pro shell tar xf tmp mysql pro cert 5 0 96 sco osr6 i686 VOLS tar Prior to installation back up your data in accordance with the procedures outlined in Section 2 19 1 Upgrading MySQL Remove any previously installed pkgadd ve...

Страница 204: ...d work SCO provides OpenServer 6 operating system patches at ftp ftp sco com pub openserver6 SCO provides information about security fixes at ftp ftp sco com pub security OpenServer By default the maximum file size on a OpenServer 6 0 0 system is 1TB Some operating system utilities have a limitation of 2GB The maximum possible file size on UnixWare 7 is 1TB with VXFS or HTFS OpenServer 6 can be co...

Страница 205: ...are 7 1 x and OpenUNIX 8 0 0 Notes Use the latest production release of MySQL Should you choose to use an older release of MySQL on UnixWare 7 1 x you must use a version of MySQL at least as recent as 3 22 13 to get fixes for some portability and OS problems We have been able to compile MySQL with the following configure command on UnixWare 7 1 x CC cc CFLAGS I usr local include CXX CC CXXFLAGS I ...

Страница 206: ...nel use the idtune name parameter command idtune modifies the etc conf cf d stune file for you To set the kernel values execute the following commands as root etc conf bin idtune SDATLIM 0x7FFFFFFF etc conf bin idtune HDATLIM 0x7FFFFFFF etc conf bin idtune SVMMLIM 0x7FFFFFFF etc conf bin idtune HVMMLIM 0x7FFFFFFF etc conf bin idtune SFNOLIM 2048 etc conf bin idtune HFNOLIM 2048 Then rebuild and re...

Страница 207: ...hell icons for MySQL Dynamic module support is compiled in but not fully tested Dynamic modules should be compiled using the Pthreads runtime library gcc Zdll Zmt Zcrtdll pthrdrtl I include I regex I o example udf_example c L lib lmysqlclient udf_example def mv example dll example udf Note Due to limitations in OS 2 UDF module name stems must not exceed eight characters Modules are stored in the m...

Страница 208: ...t using this is insecure See Section 6 1 2 1 End User Guidelines for Password Security MYSQL_TCP_PORT The default TCP IP port number MYSQL_UNIX_PORT The default Unix socket file name used for connections to localhost PATH Used by the shell to find MySQL programs TMPDIR The directory where temporary files are created TZ This should be set to your local time zone See Section C 5 4 6 Time Zone Proble...

Страница 209: ...tall the necessary files If you install MySQL from RPM files on Linux be sure to install the developer RPM as well The client programs are in the client RPM but client programming support is in the developer RPM The files you need for Perl support can be obtained from the CPAN Comprehensive Perl Archive Network at http search cpan org The easiest way to install Perl modules on Unix is to use the C...

Страница 210: ...iveState Perl 1 Get ActiveState Perl from http www activestate com Products ActivePerl and install it 2 Open a console window 3 If necessary set the HTTP_proxy variable For example you might try a setting like this C set HTTP_proxy my proxy com 3128 4 Start the PPM program C C perl bin ppm pl 5 If you have not previously done so install DBI ppm install DBI 6 If this succeeds run the following comm...

Страница 211: ...may be that Perl and MySQL are not both compiled with gcc In this case you can solve the mismatch by compiling both with gcc You may see the following error from DBD mysql when you run the tests t 00base install_driver mysql failed Can t load blib arch auto DBD mysql mysql so for module DBD mysql blib arch auto DBD mysql mysql so undefined symbol uncompress at usr lib perl5 5 00503 i586 linux Dyna...

Страница 212: ...lib usr progressive lib usr skunk lib MANPATH scohelp usr man usr local1 man usr local man usr skunk man First create a Perl that includes a statically linked DBI module by running these commands in the directory where your DBI distribution is located shell perl Makefile PL static config shell make shell make install shell make perl Then you must install the new Perl The output of make perl indica...

Страница 213: ...beforehand then tell mysql to execute the contents of the file Both ways of using mysql are covered here To see a list of options provided by mysql invoke it with the help 265 option shell mysql help This chapter assumes that mysql is installed on your machine and that a MySQL server is available to which you can connect If this is not true contact your MySQL administrator If you are the administr...

Страница 214: ...em For help with other problems often encountered when trying to log in see Section C 5 2 Common Errors When Using MySQL Programs Some MySQL installations permit users to connect as the anonymous unnamed user to the server running on the local host If this is the case on your machine you should be able to connect to that server by invoking mysql without any options shell mysql After you have conne...

Страница 215: ...ecise because they represent wall clock time not CPU or machine time and because they are affected by factors such as server load and network latency For brevity the rows in set line is sometimes not shown in the remaining examples in this chapter Keywords may be entered in any lettercase The following queries are equivalent mysql SELECT VERSION CURRENT_DATE mysql select version current_date mysql...

Страница 216: ...le line command Waiting for next line waiting for completion of a string that began with a single quote Waiting for next line waiting for completion of a string that began with a double quote Waiting for next line waiting for completion of an identifier that began with a backtick Waiting for next line waiting for completion of a comment that began with In the MySQL 5 0 series the prompt was implem...

Страница 217: ...know what the and prompts signify because if you mistakenly enter an unterminated string any further lines you type appear to be ignored by mysql including a line containing QUIT This can be quite confusing especially if you do not know that you need to supply the terminating quote before you can cancel the current command 3 3 Creating and Using a Database Once you know how to enter commands you a...

Страница 218: ...t_host is the host from which you connect to the server 3 3 1 Creating and Selecting a Database If the administrator creates your database for you when setting up your permissions you can begin using it Otherwise you need to create it yourself mysql CREATE DATABASE menagerie Under Unix database names are case sensitive unlike SQL keywords so you must always refer to your database as menagerie not ...

Страница 219: ...ow about age That might be of interest but it is not a good thing to store in a database Age changes as time passes which means you d have to update your records often Instead it is better to store a fixed value such as date of birth Then whenever you need age you can calculate it as the difference between the current date and the birth date MySQL provides functions for doing date arithmetic so th...

Страница 220: ...YES NULL death date YES NULL You can use DESCRIBE any time for example if you forget the names of the columns in your table or what types they have For more information about MySQL data types see Chapter 11 Data Types 3 3 3 Loading Data into a Table After creating your table you need to populate it The LOAD DATA and INSERT statements are useful for this Suppose that your pet records can be describ...

Страница 221: ...ction 6 1 6 Security Issues with LOAD DATA LOCAL for information on how to change this When you want to add new records one at a time the INSERT statement is useful In its simplest form you supply values for each column in the order in which the columns were listed in the CREATE TABLE statement Suppose that Diane gets a new hamster named Puffball You could add a new record using an INSERT statemen...

Страница 222: ... question and does not require you to reload the table 3 3 4 2 Selecting Particular Rows As shown in the preceding section it is easy to retrieve an entire table Just omit the WHERE clause from the SELECT statement But typically you don t want to see the entire table particularly when it becomes large Instead you re usually more interested in answering a particular question in which case you speci...

Страница 223: ...ood idea to use parentheses to indicate explicitly how conditions should be grouped mysql SELECT FROM pet WHERE species cat AND sex m OR species dog AND sex f name owner species sex birth death Claws Gwen cat m 1994 03 17 NULL Buffy Harold dog f 1989 05 13 NULL 3 3 4 3 Selecting Particular Columns If you do not want to see entire rows from your table just name the columns in which you are interest...

Страница 224: ...isplayed in no particular order It is often easier to examine query output when the rows are sorted in some meaningful way To sort a result use an ORDER BY clause Here are animal birthdays sorted by date mysql SELECT name birth FROM pet ORDER BY birth name birth Buffy 1989 05 13 Bowser 1989 08 31 Fang 1990 08 27 Fluffy 1993 02 04 Claws 1994 03 17 Slim 1996 04 29 Whistler 1997 12 09 Chirpy 1998 09 ...

Страница 225: ...that you can use to perform calculations on dates for example to calculate ages or extract parts of dates To determine how many years old each of your pets is use the TIMESTAMPDIFF 930 function Its arguments are the unit in which you want the result expressed and the two date for which to take the difference The following query shows for each pet the birth date the current date and the age in year...

Страница 226: ... value is NULL Then for those with non NULL values compute the difference between the death and birth values mysql SELECT name birth death TIMESTAMPDIFF YEAR birth death AS age FROM pet WHERE death IS NOT NULL ORDER BY age name birth death age Bowser 1989 08 31 1995 07 29 5 The query uses death IS NOT NULL rather than death NULL because NULL is a special value that cannot be compared using the usu...

Страница 227: ...value to 0 if it is currently 12 mysql SELECT name birth FROM pet WHERE MONTH birth MOD MONTH CURDATE 12 1 MONTH 925 returns a number between 1 and 12 And MOD something 12 911 returns a number between 0 and 11 So the addition has to be after the MOD 911 otherwise we would go from November 11 to January 1 3 3 4 6 Working with NULL Values The NULL value can be surprising until you get used to it Con...

Страница 228: ...matching enables you to use _ to match any single character and to match an arbitrary number of characters including zero characters In MySQL SQL patterns are case insensitive by default Some examples are shown here You do not use or when you use SQL patterns use the LIKE 896 or NOT LIKE 898 comparison operators instead To find names beginning with b mysql SELECT FROM pet WHERE name LIKE b name ow...

Страница 229: ...strate how extended regular expressions work the LIKE 896 queries shown previously are rewritten here to use REGEXP 899 To find names beginning with b use to match the beginning of the name mysql SELECT FROM pet WHERE name REGEXP b name owner species sex birth death Buffy Harold dog f 1989 05 13 NULL Bowser Diane dog m 1989 08 31 1995 07 29 If you really want to force a REGEXP 899 comparison to be...

Страница 230: ...y pets you have or how many pets each owner has or you might want to perform various kinds of census operations on your animals Counting the total number of animals you have is the same question as How many rows are in the pet table because there is one record per pet COUNT 970 counts the number of rows so the query to count your animals looks like this mysql SELECT COUNT FROM pet COUNT 9 Earlier ...

Страница 231: ...performed just on dogs and cats looks like this mysql SELECT species sex COUNT FROM pet WHERE species dog OR species cat GROUP BY species sex species sex COUNT cat f 1 cat m 1 dog f 1 dog m 2 Or if you wanted the number of animals per sex only for animals whose sex is known mysql SELECT species sex COUNT FROM pet WHERE sex IS NOT NULL GROUP BY species sex species sex COUNT bird f 1 cat f 1 cat m 1...

Страница 232: ...e It needs to contain the following information The pet name so that you know which animal each event pertains to A date so that you know when the event occurred A field to describe the event An event type field if you want to be able to categorize events Given these considerations the CREATE TABLE statement for the event table might look like this mysql CREATE TABLE event name VARCHAR 20 date DAT...

Страница 233: ...mits rows from either table to appear in the result if and only if both tables meet the conditions specified in the ON clause In this example the ON clause specifies that the name column in the pet table must match the name column in the event table If a name appears in one table but not the other the row will not appear in the result because the condition in the ON clause fails Because the name c...

Страница 234: ...e YES NULL Field indicates the column name Type is the data type for the column NULL indicates whether the column can contain NULL values Key indicates whether the column is indexed and Default specifies the column s default value Extra displays special information about columns If a column was created with the AUTO_INCREMENT option the value will be auto_increment rather than empty DESC is a shor...

Страница 235: ... correct the error then tell mysql to execute it again If you have a query that produces a lot of output you can run the output through a pager rather than watching it scroll off the top of your screen shell mysql batch file more You can catch the output in a file for further processing shell mysql batch file mysql out You can distribute your script to other people so that they can also run the co...

Страница 236: ...mple table with these statements CREATE TABLE shop article INT 4 UNSIGNED ZEROFILL DEFAULT 0000 NOT NULL dealer CHAR 20 DEFAULT NOT NULL price DOUBLE 16 2 DEFAULT 0 00 NOT NULL PRIMARY KEY article dealer INSERT INTO shop VALUES 1 A 3 45 1 B 3 99 2 A 10 99 3 B 1 45 3 C 1 69 3 D 1 25 4 D 19 95 After issuing the statements the table should have the following contents SELECT FROM shop article dealer p...

Страница 237: ...rice per article SELECT article MAX price AS price FROM shop GROUP BY article article price 0001 3 99 0002 10 99 0003 1 69 0004 19 95 3 6 4 The Rows Holding the Group wise Maximum of a Certain Column Task For each article find the dealer or dealers with the most expensive price This problem can be solved with a subquery like this one SELECT article dealer price FROM shop s1 WHERE price SELECT MAX ...

Страница 238: ...SQL statement however this requires the use of a prepared statement See Section 13 5 SQL Syntax for Prepared Statements for more information 3 6 6 Using Foreign Keys In MySQL InnoDB tables support checking of foreign key constraints See Section 14 2 The InnoDB Storage Engine and Section 1 8 5 4 Foreign Keys A foreign key constraint is not required merely to join two tables For storage engines othe...

Страница 239: ...NSERT INTO person VALUES NULL Lilliana Angelovska SELECT last LAST_INSERT_ID INSERT INTO shirt VALUES NULL dress orange last NULL polo red last NULL dress blue last NULL t shirt white last SELECT FROM person id name 1 Antonio Paz 2 Lilliana Angelovska SELECT FROM shirt id style color owner 1 polo blue 1 2 dress white 1 3 t shirt blue 1 4 dress orange 2 5 polo red 2 6 dress blue 2 7 t shirt white 2...

Страница 240: ...n 13 2 8 4 UNION Syntax Each SELECT searches only one key and can be optimized SELECT field1_index field2_index FROM test_table WHERE field1_index 1 UNION SELECT field1_index field2_index FROM test_table WHERE field2_index 1 3 6 8 Calculating Visits Per Day The following example shows how you can use the bit group functions to calculate the number of days per month a user has visited a Web page CR...

Страница 241: ...eaches the upper limit of the data type the next attempt to generate a sequence number fails For example if you use TINYINT the maximum permissible sequence number is 127 For TINYINT UNSIGNED the maximum is 255 Note For a multiple row insert LAST_INSERT_ID 961 and mysql_insert_id actually return the AUTO_INCREMENT key from the first of the inserted rows This enables multiple row inserts to be repr...

Страница 242: ... 1 4 ALTER TABLE Syntax How AUTO_INCREMENT behaves depending on the NO_AUTO_VALUE_ON_ZERO 536 SQL mode Section 5 1 7 Server SQL Modes How to use the LAST_INSERT_ID 961 function to find the row that contains the most recent AUTO_INCREMENT value Section 12 13 Information Functions Setting the AUTO_INCREMENT value to be used Section 5 1 4 Server System Variables AUTO_INCREMENT and replication Section...

Страница 243: ... Program 293 4 5 5 mysqlimport A Data Import Program 308 4 5 6 mysqlshow Display Database Table and Column Information 312 4 6 MySQL Administrative and Utility Programs 315 4 6 1 innochecksum Offline InnoDB File Checksum Utility 315 4 6 2 myisam_ftdump Display Full Text Index information 316 4 6 3 myisamchk MyISAM Table Maintenance Utility 317 4 6 4 myisamlog Display MyISAM Log File Contents 333 4...

Страница 244: ...hat you have a distribution that does not include all programs and you need to install an additional package Each MySQL program takes many different options Most programs provide a help option that you can use to get a description of the program s different options For example try mysql help You can override default option values for MySQL programs by specifying options on the command line or in a...

Страница 245: ... mysql_install_db Initialize MySQL Data Directory Section 2 18 1 Unix Postinstallation Procedures and Section 4 4 6 mysql_install_db Initialize MySQL Data Directory mysql_secure_installation This program enables you to improve the security of your MySQL installation SQL See Section 4 4 7 mysql_secure_installation Improve MySQL Installation Security mysql_tzinfo_to_sql This program loads the time z...

Страница 246: ...QL administrative and utility programs innochecksum An offline InnoDB offline file checksum utility See Section 4 6 1 innochecksum Offline InnoDB File Checksum Utility myisam_ftdump A utility that displays information about full text indexes in MyISAM tables See Section 4 6 2 myisam_ftdump Display Full Text Index information myisamchk A utility to describe check optimize and repair MyISAM tables S...

Страница 247: ...ery Log mysql_find_rows A utility that reads files containing SQL statements such as update logs and extracts statements that match a given regular expression See Section 4 6 13 mysql_find_rows Extract SQL Statements from Files mysql_fix_extensions A utility that converts the extensions for MyISAM table files to lowercase This can be useful after transferring the files from a system with case inse...

Страница 248: ... Section 4 8 2 replace A String Replacement Utility resolveip A utility program that resolves a host name to an IP address or vice versa See Section 4 8 3 resolveip Resolve Host name to IP Address or Vice Versa Oracle Corporation also provides the MySQL Workbench GUI tool which is used to administer MySQL servers and databases to create execute and evaluate queries and to migrate schemas and data ...

Страница 249: ...ch server to connect to and the account to use on that server Other connection options are port 231 or P to specify a TCP IP port number and socket 232 or S to specify a Unix socket file on Unix or named pipe name on Windows For more information on options that specify connection options see Section 4 2 2 Connecting to the MySQL Server You may find it necessary to invoke MySQL programs using the p...

Страница 250: ...sword option has no password value the client program prints a prompt and waits for you to enter the password In these examples mydb is not interpreted as a password because it is separated from the preceding password option by a space On some systems the library routine that MySQL uses to prompt for a password automatically limits the password to eight characters That is a problem with the system...

Страница 251: ...ocalhost password pass_val 231 p pass_val The password of the MySQL account As described earlier the password value is optional but if given there must be no space between p or password 231 and the password following it The default is to send no password pipe 231 W On Windows connect to the server using a named pipe The server must be started with the enable named pipe 407 option to enable named p...

Страница 252: ... establishing a secure connection to the server using SSL if the server is configured with SSL support For details see Section 6 3 6 4 SSL Command Options user user_name 232 u user_name The user name of the MySQL account you want to use The default user name is ODBC on Windows or your Unix login name on Unix It is possible to specify different default values to be used when you make a connection s...

Страница 253: ...ogram in an option file That enables you to avoid typing them each time you run the program while enabling you to override the defaults if necessary by using command line options An option can be specified by writing it in full or as any unambiguous prefix For example the compress 299 option can be given to mysqldump as compr but not as comp because the latter is ambiguous shell mysqldump comp mys...

Страница 254: ...server 1024 times sleeping 10 seconds between each ping mysql mysqladmin count 1K sleep 10 ping Option values that contain spaces must be quoted when given on the command line For example the execute 266 or e option can be used with mysql to pass SQL statements to the server When this option is used mysql executes the statements in the option value and exits The statements must be enclosed by quot...

Страница 255: ...ose no such option mysql WARNING unknown option no such option The loose prefix can be useful when you run programs from multiple installations of MySQL on the same machine and list options in an option file An option that may not be recognized by all versions of a program can be given using the loose prefix or loose in an option file Versions of the program that recognize the option process it no...

Страница 256: ...items are used first File Name Purpose etc my cnf Global options SYSCONFDIR my cnf Global options MYSQL_HOME my cnf Server specific options defaults extra file The file specified with defaults extra file path 239 if any my cnf User specific options represents the current user s home directory the value of HOME SYSCONFDIR represents the directory specified with the sysconfdir option to configure wh...

Страница 257: ...nly one option per line For example quick and host localhost on the command line should be specified as quick and host localhost on separate lines in an option file To specify an option of the form loose opt_name in an option file write it as loose opt_name Empty lines in option files are ignored Nonempty lines can take any of the following forms comment comment Comment lines start with or A comme...

Страница 258: ... the mysqld server and the mysql client program respectively The client option group is read by all client programs but not by mysqld This enables you to specify options that apply to all clients For example client is the perfect group to use to specify the password that you use to connect to the server But make sure that the option file is readable and writable only by yourself so that other peop...

Страница 259: ...s like this mysqladmin force mysqld key_buffer_size 16M If my cnf is processed by mysqld only the mysqld group in home mydir myopt cnf is used If the file is processed by mysqladmin only the mysqladmin group is used If the file is processed by any other program no options in home mydir myopt cnf are used The includedir directive is processed similarly except that all option files in the named dire...

Страница 260: ...sing the same syntax that applies to specifying program options For example mysql has a max_allowed_packet variable that controls the maximum size of its communication buffer To set the max_allowed_packet variable for mysql to a value of 16MB use either of the following commands shell mysql max_allowed_packet 16777216 shell mysql max_allowed_packet 16M The first command specifies the value in byte...

Страница 261: ...xpecting Values and the Sign By convention long forms of options that assign a value are written with an equals sign like this shell mysql host tonfisk user jon For options that require a value that is not having a default value the equal sign is not required and so the following is also valid shell mysql host tonfisk user jon In both cases the mysql client attempts to connect to a MySQL server ru...

Страница 262: ...log errors to a file named my errors err You might try starting the server with log error my errors but this does not have the intended effect as shown here shell mysqld_safe log error my errors 1 31357 shell 080111 22 53 31 mysqld_safe Logging to usr local mysql var tonfisk err 080111 22 53 32 mysqld_safe Starting mysqld daemon with databases from usr local mysql var 080111 22 53 34 mysqld_safe m...

Страница 263: ... must use the equals sign mysql user jon Now the login attempt succeeds shell mysql Welcome to the MySQL monitor Commands end with or g Your MySQL connection id is 5 Server version 5 0 96 Source distribution Type help or h for help Type c to clear the buffer mysql SELECT USER USER jon localhost 1 row in set 0 00 sec This is not the same behavior as with the command line where the equals sign is no...

Страница 264: ...startup file that your command interpreter reads each time it starts On Windows you can set environment variables using the System Control Panel under Advanced On Unix typical shell startup files are bashrc or bash_profile for bash or tcshrc for tcsh Suppose that your MySQL programs are installed in usr local mysql bin and that you want to make it easy to invoke these programs To do this set the v...

Страница 265: ...ymbolic link to mysqld_safe However you should not rely on this because it is removed as of MySQL 5 1 By default mysqld_safe before MySQL 5 0 27 tries to start an executable named mysqld max if it exists and mysqld otherwise Be aware of the implications of this behavior On Linux the MySQL Max RPM relies on this mysqld_safe behavior The RPM installs an executable named mysqld max which causes mysql...

Страница 266: ...Use this option to indicate the path name to the directory where the server is located log error file_name 247 log error 247 Write the error log to the given file mysqld prog_name 247 mysqld 247 The name of the server program in the ledir directory that you want to start mysqld version suffix 247 mysqld version 247 This option is similar to the mysqld option but you specify only the suffix for the...

Страница 267: ...th an error defaults file file_name 247 The name of an option file to be read instead of the usual option files This must be the first option on the command line if it is used ledir path 247 If mysqld_safe cannot find the server use this option to indicate the path name to the directory where the server is located log error file_name 247 Write the error log to the given file See Section 5 2 1 The ...

Страница 268: ...t tables If you execute mysqld_safe with the defaults file 247 or defaults extra file 247 option to name an option file the option must be the first one given on the command line or the option file will not be used For example this command will not use the named option file mysql mysqld_safe port port_num defaults file file_name Instead use the following command mysql mysqld_safe defaults file fil...

Страница 269: ...ver 4 Starts mysqld monitors it and restarts it if it terminates in error 5 Sends error messages from mysqld to the host_name err file in the data directory 6 Sends mysqld_safe screen output to the host_name safe file in the data directory 4 3 3 mysql server MySQL Server Startup Script MySQL distributions on Unix include a script named mysql server It can be used on systems such as Linux and Solar...

Страница 270: ...red to in the following discussion as the option group number or GNR Group numbers distinguish option groups from one another and are used as arguments to mysqld_multi to specify which servers you want to start stop or obtain a status report for Options listed in these groups are the same that you would use in the mysqld group used for starting mysqld See for example Section 2 18 1 2 Starting and ...

Страница 271: ...o mysqld_multi itself mysqldN groups can be used for options passed to specific mysqld instances As of MySQL 5 0 82 the mysqld or mysqld_safe groups can be used for common options read by all instances of mysqld or mysqld_safe You can specify a defaults file file_name 240 option to use a different configuration file for that instance in which case the mysqld or mysqld_safe groups from that file wi...

Страница 272: ...IP port instead of the Unix socket file If a socket file is missing the server might still be running but accessible only through the TCP IP port By default connections are made using the Unix socket file This option affects stop and report operations user user_name 252 The user name of the MySQL account to use when invoking mysqladmin verbose 252 Be more verbose version 252 Display version inform...

Страница 273: ...t if the process terminates due to a signal sent using kill 9 or for other reasons such as a segmentation fault Please note that the mysqld_safe script might require that you start it from a certain place This means that you might have to change location to a certain directory before running mysqld_multi If you have problems starting please see the mysqld_safe script Check especially the lines MY_...

Страница 274: ... 4 1 comp_err Compile MySQL Error Message File comp_err creates the errmsg sys file that is used by mysqld to determine the error messages to display for different error codes comp_err normally is run automatically when MySQL is built It compiles the errmsg sys file from the plaintext file located at sql share errmsg txt in MySQL source distributions comp_err also generates mysqld_error h mysqld_e...

Страница 275: ...t files into a Zip archive that can be unpacked at the location where you want to install MySQL make_win_bin_dist is a shell script so you must have Cygwin installed to use it This program s use is subject to change Currently you invoke it as follows from the root directory of your source distribution shell make_win_bin_dist options package_basename copy_def The package_basename argument provides ...

Страница 276: ...re and build the source distribution on a Unix or Unix like system so that you have a server binary to work with See the instructions at Section 2 10 8 5 Creating a Windows Source Package from the Bazaar Repository Invoke make_win_src_distribution like this from the top level directory of a MySQL source distribution shell make_win_src_distribution options make_win_src_distribution understands the ...

Страница 277: ...duce changes to the structure of the system tables in the mysql database to add new privileges or support new features When you update to a new version of MySQL you should update your system tables as well to make sure that their structure is up to date Otherwise there might be capabilities that you cannot take advantage of mysql_fix_privilege_tables is an older script that previously was used to ...

Страница 278: ...later you should either run mysql_install_db from the same system account that will be used for running mysqld or run it as root and use the user 259 option to indicate the user name that mysqld will run as It might be necessary to specify other options such as basedir 258 or datadir 258 if mysql_install_db does not use the correct locations for the installation directory or data directory For exa...

Страница 279: ... default mysqld runs using your current login name and files and directories that it creates will be owned by you verbose 259 Verbose mode Print more information about what the program does windows 259 For internal use This option is used for creating Windows distributions 4 4 7 mysql_secure_installation Improve MySQL Installation Security This program enables you to improve the security of your M...

Страница 280: ..._tzinfo_to_sql using the third syntax which initializes the leap second information tz_file is the name of your time zone file shell mysql_tzinfo_to_sql leap tz_file mysql u root mysql After running mysql_tzinfo_to_sql it is best to restart the server so that it does not continue to use any previously cached time zone data 4 4 9 mysql_upgrade Check Tables for MySQL Upgrade mysql_upgrade examines a...

Страница 281: ...n a file named mysql_upgrade_info in the data directory This is used to quickly check whether all tables have been checked for this release so that table checking can be skipped To ignore this file and perform the check regardless use the force 261 option If you install MySQL from RPM packages on Linux you must install the server and client RPMs mysql_upgrade is included in the server RPM but requ...

Страница 282: ...ysql to retrieve results from the server a row at a time rather than retrieving the entire result set and buffering it in memory before displaying it This is done by returning the result set using the mysql_use_result C API function in the client server library rather than mysql_store_result Using mysql is very easy Invoke it from the prompt of your command interpreter as follows shell mysql db_na...

Страница 283: ...efault character set charset_name 266 default character set 266 Use charset_name as the default character set delimiter str 266 delimiter 266 Set the statement delimiter execute statement 266 execute 266 Execute the statement and quit force 266 force 266 Continue even if an SQL error occurs help 265 Display help message and exit host host_name 266 host 266 Connect to the MySQL server on the given ...

Страница 284: ...sult raw 269 raw 269 Write column values without escape conversion reconnect 269 reconnect 269 If the connection to the server is lost automatically try to reconnect safe updates 269 safe updates 269 Allow only UPDATE and DELETE statements that specify key values secure auth 269 secure auth 269 Do not send passwords to the server in old pre 4 1 1 format select_limit value 271 select_limit 271 The ...

Страница 285: ...0 user 270 MySQL user name to use when connecting to server verbose 270 Verbose mode version 270 Display version information and exit vertical 270 vertical 270 Print query output rows vertically one line per column value wait 270 wait 270 If the connection cannot be established wait and retry instead of aborting xml 270 xml 270 Produce XML output help 265 Display a help message and exit auto rehas...

Страница 286: ...ommon issue that can occur when the operating system uses utf8 or another multi byte character set is that output from the mysql client is formatted incorrectly due to the fact that the MySQL client uses the latin1 character set by default You can usually fix such issues by using this option to force the client to use the system character set instead See Section 10 5 Character Set Configuration fo...

Страница 287: ...sql Commands no auto rehash 265 A This has the same effect as skip auto rehash See the description for auto rehash 265 no beep 267 b Do not beep when errors occur no named commands 267 g Deprecated use disable named commands 266 instead no named commands 267 is removed in MySQL 5 5 no pager 267 Deprecated form of skip pager 268 See the pager 268 option no pager 267 is removed in MySQL 5 5 no tee 2...

Страница 288: ... password The password to use when connecting to the server If you use the short option form p you cannot have a space between the option and the password If you omit the password value following the password 268 or p option on the command line mysql prompts for one Specifying a password on the command line should be considered insecure See Section 6 1 2 1 End User Guidelines for Password Security...

Страница 289: ...se skip reconnect 269 safe updates 269 i am a dummy 269 U Permit only those UPDATE and DELETE statements that specify which rows to modify by using key values If you have set this option in an option file you can override it by using safe updates 269 on the command line See Section 4 5 1 6 mysql Tips for more information about this option secure auth 269 Do not send passwords to the server in old ...

Страница 290: ...tion 4 5 1 2 mysql Commands discusses tee files further unbuffered 270 n Flush the buffer after each query user user_name 270 u user_name The MySQL user name to use when connecting to the server verbose 270 v Verbose mode Produce more output about what the program does This option can be given multiple times to produce more and more output For example v v v produces table output format even in bat...

Страница 291: ...able_name version_compile_machine field field name Value i686 field row row field name Variable_name version_compile_os field field name Value suse linux gnu field row resultset See Bug 25946 You can also set the following variables by using var_name value The set variable format is deprecated connect_timeout The number of seconds before connection timeout Default value is 0 max_allowed_packet The...

Страница 292: ...nother database Takes database name as argument charset C Switch to another charset Might be needed for processing binlog with multi byte charsets warnings W Show warnings after every statement nowarning w Don t show warnings after every statement For server side help type help contents Each command has both a long and short form The long form is not case sensitive the short form is The long form ...

Страница 293: ... will be unable to use the word INDEX in statements mysql interprets this as INDE followed by the delimiter X When the delimiter recognized by mysql is set to something other than the default of instances of that character are sent to the server without interpretation However the server itself still interprets as a statement delimiter and processes statements accordingly This behavior on the serve...

Страница 294: ...uting it prompt str R str Reconfigure the mysql prompt to the given string The special character sequences that can be used in the prompt are described later in this section If you specify the prompt command with no argument mysql resets the prompt to the default of mysql quit q Exit mysql rehash Rebuild the completion hash that enables database table and column name completion while you are enter...

Страница 295: ...if output fits on one screen which is convenient when no scrolling is necessary mysql pager less n i S F X You can specify very complex pager commands for handling query output mysql pager cat tee dr1 tmp res txt tee dr2 tmp res2 txt less n i S In this example the command would send query results to two files in two different directories on two different file systems mounted on dr1 and dr2 yet sti...

Страница 296: ...d above You can set the prompt in several ways Use an environment variable You can set the MYSQL_PS1 environment variable to a prompt string For example shell export MYSQL_PS1 u h d Use a command line option You can set the prompt 268 option on the command line to mysql For example shell mysql prompt u h d user host database Use an option file You can set the prompt option in the mysql group of an...

Страница 297: ...o suppress statement logging by using the batch 265 or execute 266 option mysql logs each nonempty statement line individually If a statement spans multiple lines not including the terminating delimiter mysql concatenates the lines to form the complete statement maps newlines to spaces and logs the result plus a delimiter Consequently an input statement that spans multiple lines can be logged twic...

Страница 298: ...ntents to see a list of the help categories mysql help contents You asked for help about help category Contents For more information type help item where item is one of the following categories Account Management Administration Data Definition Data Manipulation Data Types Functions Functions and Modifiers for Use with GROUP BY Geographic Features Language Structure Storage Engines Stored Routines ...

Страница 299: ...n invoke mysql as shown here shell mysql db_name text_file If you place a USE db_name statement as the first statement in the file it is unnecessary to specify the database name on the command line shell mysql text_file If you are already running mysql you can execute an SQL script file using the source command or command mysql source file_name mysql file_name Sometimes you may want your script to...

Страница 300: ... Control U deletes the entire line In readline Control W deletes the word before the cursor and Control U deletes everything before the current cursor position If mysql was built using libedit a user who prefers the readline behavior for these two keys can put the following lines in the editrc file creating the file if necessary bind W ed delete prev word bind U vi kill line prev To see the curren...

Страница 301: ... row combinations To specify limits different from 1 000 and 1 000 000 you can override the defaults by using the select_limit and max_join_size options shell mysql safe updates select_limit 500 max_join_size 10000 4 5 1 6 4 Disabling mysql Auto Reconnect If the mysql client loses its connection to the server while sending a statement it immediately and automatically tries to reconnect once to the...

Страница 302: ...command name create db_name Create a new database named db_name debug Tell the server to write debug information to the error log Format and content of this information is subject to change drop db_name Delete the database named db_name and all its tables extended status Display the server status variables and their values flush hosts Flush all information in the host cache flush logs Flush all lo...

Страница 303: ...and with flush privileges on the same command line to re enable the grant tables because the flush operation occurs after you connect However you can use mysqladmin flush privileges to re enable the grant table and then use a separate mysqladmin password command to change the password ping Check whether the server is available The return status from mysqladmin is 0 if the server is running 1 if it...

Страница 304: ..._time 465 seconds See Section 5 2 4 The Slow Query Log Opens The number of tables the server has opened Flush tables The number of flush refresh and reload commands the server has executed Open tables The number of tables that currently are open Memory in use The amount of memory allocated directly by mysqld This value is displayed only when MySQL has been compiled with with debug full 122 Maximum...

Страница 305: ...port number to use for the connection protocol type 287 protocol 287 The connection protocol to use relative 287 relative 287 Show the difference between the current and previous values when used with the sleep option shutdown_timeout seconds 287 shutdown_timeout 287 The maximum number of seconds to wait for server shutdown silent 287 silent 287 Silent mode sleep delay 287 sleep 287 Execute comman...

Страница 306: ..._options string is d t o file_name The default is d t o tmp mysqladmin trace default character set charset_name 286 Use charset_name as the default character set See Section 10 5 Character Set Configuration force 286 f Do not ask for confirmation for the drop db_name command With multiple commands continue even if an error occurs host host_name 286 h host_name Connect to the MySQL server on the gi...

Страница 307: ...y until interrupted socket path 287 S path For connections to localhost the Unix socket file to use or on Windows the name of the named pipe to use ssl Options that begin with ssl 607 specify whether to connect to the server using SSL and indicate where to find SSL keys and certificates See Section 6 3 6 4 SSL Command Options user user_name 287 u user_name The MySQL user name to use when connectin...

Страница 308: ...ant to perform and then sends the statements to the server to be executed For details about which storage engines each statement works with see the descriptions for those statements in Section 13 7 2 Table Maintenance Statements The MyISAM storage engine supports all four maintenance operations so mysqlcheck can be used to perform any of them on MyISAM tables Other storage engines do not necessari...

Страница 309: ... auto repair 291 auto repair 291 If a checked table is corrupted automatically fix it character sets dir path 291 character sets dir 291 The directory where character sets are installed check 291 check 291 Check the tables for errors check only changed 291 check only changed 291 Check only tables that have changed since the last check check upgrade 291 check upgrade 291 Invoke CHECK TABLE with the...

Страница 310: ... file to use for establishing a secure connection ssl cipher cipher_list 292 ssl cipher 292 A list of allowable ciphers to use for SSL encryption ssl key file_name 292 ssl key 292 The name of the SSL key file to use for establishing a secure connection ssl verify server cert 292 ssl verify server cert 292 The server s Common Name value in its certificate is verified against the host name used when...

Страница 311: ...91 B Process all tables in the named databases Normally mysqlcheck treats the first name argument on the command line as a database name and following names as table names With this option it treats all name arguments as database names debug debug_options 291 debug_options Write a debugging log A typical debug_options string is d t o file_name The default is d t o default character set charset_nam...

Страница 312: ...CKET PIPE MEMORY 292 The connection protocol to use for connecting to the server It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want For details on the permissible values see Section 4 2 2 Connecting to the MySQL Server quick 292 q If you are using this option to check tables it prevents the check from scanning the rows to check ...

Страница 313: ...st have the same privileges needed to create each of the dumped objects by issuing CREATE statements manually If you are doing a backup on the server and your tables all are MyISAM tables consider using the mysqlhotcopy instead because it can accomplish faster backups and faster restores See Section 4 6 9 mysqlhotcopy A Database Backup Program There are three general ways to invoke mysqldump shell...

Страница 314: ...nables quick 304 The opt 303 option and hence quick 304 is enabled by default so to enable memory buffering use skip quick 304 If you are using a recent version of mysqldump to generate a dump to be reloaded into a very old MySQL server you should not use the opt 303 or extended insert 300 option Use skip opt 305 instead Before MySQL 4 1 2 out of range numeric values such as inf and inf as well as...

Страница 315: ...ebugging log debug info 299 debug info 299 Print debugging information memory and CPU statistics when the program exits 5 0 32 default character set charset_name 300 default character set 300 Use charset_name as the default character set delayed insert 300 delayed insert 300 Write INSERT DELAYED statements rather than INSERT statements delete master logs 300 delete master logs 300 On a master repl...

Страница 316: ... for LOAD DATA INFILE lock all tables 301 lock all tables 301 Lock all tables across all databases lock tables 301 lock tables 301 Lock all tables before dumping them log error file_name 301 log error 301 Append warnings and errors to the named file 5 0 42 master data value 302 master data 302 Write the binary log file name and position to the output max_allowed_packet value max_allowed_packet The...

Страница 317: ...before each CREATE TABLE statement skip add locks 298 skip add locks 298 Do not add locks skip comments 305 skip comments 305 Do not add comments to the dump file skip compact 299 skip compact 299 Do not produce more compact output skip disable keys 300 skip disable keys 300 Do not disable keys skip extended insert 300 skip extended insert 300 Turn off extended insert skip opt 305 skip opt 305 Tur...

Страница 318: ...only rows selected by the given WHERE condition xml 306 xml 306 Produce XML output help 298 Display a help message and exit add drop database 298 Add a DROP DATABASE statement before each CREATE DATABASE statement This option is typically used in conjunction with the all databases 298 or databases 299 option because no CREATE DATABASE statements are written unless one of those options is specified...

Страница 319: ...for setting the server SQL mode See Section 5 1 7 Server SQL Modes This option does not guarantee compatibility with other servers It only enables those SQL mode values that are currently available for making dump output more compatible For example compatible oracle 299 does not map data types to Oracle types or use Oracle comment syntax This option requires a server version of 4 1 0 or higher Wit...

Страница 320: ...ed on DATE However the date causes dump files taken at different times to appear to be different even if the data are otherwise identical dump date 300 and skip dump date 300 control whether the date is added to the comment The default is dump date 300 include the date in the comment skip dump date 300 suppresses date printing This option was added in MySQL 5 0 52 extended insert 300 e Use multipl...

Страница 321: ...f MySQL 5 0 13 BIT columns are affected as well ignore table db_name tbl_name 301 Do not dump the given table which must be specified using both the database and table names To ignore multiple tables use this option multiple times This option also can be used to ignore views insert ignore 301 Write INSERT IGNORE statements rather than INSERT statements lines terminated by 301 This option is used w...

Страница 322: ...r single transaction 304 In all cases any action on logs happens at the exact moment of the dump It is also possible to set up a slave by dumping an existing slave of the master To do this use the following procedure on the existing slave 1 Stop the slave s SQL thread and get its current status mysql STOP SLAVE SQL_THREAD mysql SHOW SLAVE STATUS 2 From the output of the SHOW SLAVE STATUS statement...

Страница 323: ...ly The opt 303 option is enabled by default Use skip opt 305 to disable it See the discussion at the beginning of this section for information about selectively enabling or disabling a subset of the options affected by opt 303 order by primary 303 Dump each table s rows sorted by its primary key or by its first unique index if such an index exists This is useful when dumping a MyISAM table to be l...

Страница 324: ...e attributes such as the routine creation and modification timestamps This means that when the routines are reloaded they will be created with the timestamps equal to the reload time If you require routines to be re created with their original timestamp attributes do not use routines 304 Instead dump and reload the contents of the mysql proc table directly using a MySQL account that has appropriat...

Страница 325: ...pecify whether to connect to the server using SSL and indicate where to find SSL keys and certificates See Section 6 3 6 4 SSL Command Options tab path 305 T path Produce tab separated text format data files For each dumped table mysqldump creates a tbl_name sql file that contains the CREATE TABLE statement that creates the table and the server writes a tbl_name txt file that contains its data The...

Страница 326: ...ormation about what the program does version 306 V Display version information and exit where where_condition 306 w where_condition Dump only rows selected by the given WHERE condition Quotes around the condition are mandatory if it contains spaces or other characters that are special to your command interpreter Examples where user jimf w userid 1 w userid 1 xml 306 X Write dump output as well for...

Страница 327: ...d row row field name ID 4079 field field name Name Rafah field field name CountryCode PSE field field name District Rafah field field name Population 92020 field row table_data database mysqldump You can also set the following variables by using var_name value syntax max_allowed_packet The maximum size of the buffer for client server communication The maximum is 1GB net_buffer_length 477 The initi...

Страница 328: ...ysqldump all databases master data 2 all_databases sql Or shell mysqldump all databases flush logs master data 2 all_databases sql The master data 302 and single transaction 304 options can be used simultaneously which provides a convenient way to make an online backup suitable for use prior to point in time recovery if tables are stored using the InnoDB storage engine For more information on maki...

Страница 329: ...ed by 310 This option has the same meaning as the corresponding clause for LOAD DATA INFILE force 310 force 310 Continue even if an SQL error occurs help 310 Display help message and exit host host_name 311 host 311 Connect to the MySQL server on the given host ignore 311 ignore 311 See the description for the replace option ignore lines 311 ignore lines 311 Ignore the first N lines of the data fi...

Страница 330: ...sion 312 Display version information and exit help 310 Display a help message and exit character sets dir path 310 The directory where character sets are installed See Section 10 5 Character Set Configuration columns column_list 310 c column_list This option takes a comma separated list of column names as its value The order of the column names indicates how to match data file columns with table c...

Страница 331: ...chronized on the server low priority 311 Use LOW_PRIORITY when loading the table This affects only storage engines that use only table level locking such as MyISAM MEMORY and MERGE password password 311 p password The password to use when connecting to the server If you use the short option form p you cannot have a space between the option and the password If you omit the password value following ...

Страница 332: ...icates See Section 6 3 6 4 SSL Command Options user user_name 312 u user_name The MySQL user name to use when connecting to the server verbose 312 v Verbose mode Print more information about what the program does version 312 V Display version information and exit Some options such as opt 303 automatically enable lock tables If you want to override this use skip lock tables at the end of the option...

Страница 333: ...e because in this case mysqlshow shows you only the table names that match the pattern This is easily fixed by adding an extra last on the command line as a separate argument mysqlshow supports the following options which can be specified on the command line or in the mysqlshow and client groups of an option file mysqlshow also supports the options for processing option files described at Section ...

Страница 334: ...en connecting to the server status 315 status 315 Display extra information about each table user user_name 315 user 315 MySQL user name to use when connecting to server verbose 315 Verbose mode version 315 Display version information and exit help 314 Display a help message and exit character sets dir path 314 The directory where character sets are installed See Section 10 5 Character Set Configu...

Страница 335: ...han the one you want For details on the permissible values see Section 4 2 2 Connecting to the MySQL Server show table type 315 t Show a column indicating the table type as in SHOW FULL TABLES The type is BASE TABLE or VIEW This option was added in MySQL 5 0 4 socket path 315 S path For connections to localhost the Unix socket file to use or on Windows the name of the named pipe to use ssl Options...

Страница 336: ...ge numbers the numbers are zero based c Print a count of the number of pages in the file d Debug mode prints checksums for each page e num End at this page number p num Check only this page number s num Start at this page number v Verbose mode print a progress indicator every five seconds 4 6 2 myisam_ftdump Display Full Text Index information myisam_ftdump displays information about FULLTEXT inde...

Страница 337: ...ssage and exit count 317 c Calculate per word statistics counts and global weights dump 317 d Dump the index including data offsets and word weights length 317 l Report the length distribution stats 317 s Report global index statistics This is the default operation if no other operation is specified verbose 317 v Verbose mode Print more output about what the program does 4 6 3 myisamchk MyISAM Tab...

Страница 338: ...chk MYI If you are not in the database directory you can check all the tables there by specifying the path to the directory shell myisamchk path to database_dir MYI You can even check all tables in all databases by specifying a wildcard with the path to the MySQL data directory shell myisamchk path to datadir MYI The recommended way to quickly check all MyISAM tables is shell myisamchk silent fast...

Страница 339: ... tables that have changed since the last check correct checksum 324 correct checksum 324 Correct the checksum information for the table data file length len 324 data file length 324 Maximum length of the data file when re creating data file when it is full debug debug_options 321 debug 321 Write a debugging log decode_bits decode_bits Decode_bits description 325 description 325 Print some descript...

Страница 340: ...set used by the table indexes set collation name 325 set collation 325 Specify the collation to use for sorting table indexes silent 321 silent 321 Silent mode sort_buffer_size sort_buffer_size The buffer that is allocated when sorting the index when doing a REPAIR or when creating indexes with CREATE INDEX or ALTER TABLE sort index 326 sort index 326 Sort the index tree blocks in high low order s...

Страница 341: ...th an error if the table is locked wait until the table is unlocked before continuing If you are running mysqld with external locking disabled the table can be locked only by another myisamchk command You can also set the following variables by using var_name value syntax Variable Default Value decode_bits 9 ft_max_word_len version dependent ft_min_word_len 4 ft_stopword_file built in list key_buf...

Страница 342: ... was added in MySQL 5 0 14 For older versions the statistics collection method is equivalent to nulls_equal ft_min_word_len and ft_max_word_len indicate the minimum and maximum word length for FULLTEXT indexes ft_stopword_file names the stopword file These need to be set under the following circumstances If you use myisamchk to perform an operation that modifies table indexes such as repair or ana...

Страница 343: ...ny errors in the table The repair type is the same as that specified with the recover 324 or r option information 323 i Print informational statistics about the table that is checked medium check 323 m Do a check that is faster than an extend check 323 operation This finds only 99 99 of all errors which should be good enough in most cases read only 323 T Do not mark the table as checked This is us...

Страница 344: ...nserts Deactivated indexes can be reactivated by using myisamchk r no symlinks 324 l Do not follow symbolic links Normally myisamchk repairs the table that a symlink points to This option does not exist as of MySQL 4 0 because versions from 4 0 on do not remove symlinks during repair operations max record length len 324 Skip rows larger than the given length if myisamchk cannot allocate memory to ...

Страница 345: ...can be set to a list of directory paths that are used successively in round robin fashion for creating temporary files The separator character between directory names is the colon on Unix and the semicolon on Windows NetWare and OS 2 unpack 325 u Unpack a table that was packed with myisampack 4 6 3 4 Other myisamchk Options myisamchk supports the following options for actions other than table chec...

Страница 346: ...this section myisamchk d tbl_name Runs myisamchk in describe mode to produce a description of your table If you start the MySQL server with external locking disabled myisamchk may report an error for a table that is updated while it runs However because myisamchk does not change the table in describe mode there is no risk of destroying data myisamchk dv tbl_name Adding v runs myisamchk in verbose ...

Страница 347: ...ey Root Blocksize 1 2 4 unique long 1 99328 1024 2 6 20 multip varchar prefix 512 3563520 1024 27 20 varchar 512 3 48 3 multip uint24 NULL 306688 6065152 1024 Field Start Length Nullpos Nullbit Type 1 1 1 2 2 4 no zeros 3 6 21 varchar 4 27 21 varchar 5 48 3 1 1 no zeros 6 51 3 1 2 no zeros Explanations for the types of information myisamchk produces are given here Keyfile refers to the index file ...

Страница 348: ... pointer in bytes It is usually 2 3 4 or 5 bytes Most tables manage with 2 bytes but this cannot be controlled from MySQL yet For fixed tables this is a row address For dynamic tables this is a byte address Keyfile pointer The size of the index file pointer in bytes It is usually 1 2 or 3 bytes Most tables manage with 2 bytes but this is calculated automatically by MySQL It is always a block addre...

Страница 349: ...t tells how many rows there are per value for this index A unique index always has a value of 1 This may be updated after a table is loaded or greatly changed with myisamchk a If this is not updated at all a default value of 30 is given The last part of the output provides information about each column Field The column number Start The byte position of the column within table rows Length The lengt...

Страница 350: ... Section 4 6 5 myisampack Generate Compressed Read Only MyISAM Tables for an example of this information Example of myisamchk eiv output Checking MyISAM file person Data records 306688 Deleted blocks 0 check file size check record delete chain No recordlinks check key delete chain block_size 1024 check index reference check data record references index 1 Key 1 Keyblocks used 98 Packed 0 Max levels...

Страница 351: ...an only be used for indexes on CHAR and VARCHAR columns For long indexed strings that have similar leftmost parts this can significantly reduce the space used In the preceding example the second key is 40 bytes long and a 97 reduction in space is achieved Max levels How deep the B tree for this key is Large tables with long key values get high values Records How many rows are in the table M record...

Страница 352: ...myisamchk sort_buffer_size 256M key_buffer_size 512M read_buffer_size 64M write_buffer_size 64M Using sort_buffer_size 16M is probably enough for most cases Be aware that myisamchk uses temporary files in TMPDIR If TMPDIR points to a memory file system out of memory errors can easily occur If this happens run myisamchk with the tmpdir path 325 option to specify a directory located on a file system...

Страница 353: ...ile Contents myisamlog processes the contents of a MyISAM log file To create such a file start the server with a log isam log_file 411 option Invoke myisamlog like this shell myisamlog options file_name tbl_name The default operation is update u If a recovery is done r all writes and possibly updates and deletes are done and errors are only counted The default log file name is myisam log if no log...

Страница 354: ...be updated by the server during the packing process It is safest to compress tables with the server stopped After packing a table it becomes read only This is generally intended such as when accessing packed tables on a CD Invoke myisampack like this shell myisampack options file_name Each file name argument should be the name of an index MYI file If you are not in the database directory you shoul...

Страница 355: ...rom one of the source tables and name it big_tbl_name frm silent 335 s Silent mode Write output only when errors occur test 335 t Do not actually pack the table just test packing it tmpdir path 335 T path Use the named directory as the location where myisampack creates temporary files verbose 335 v Verbose mode Write information about the progress of the packing operation and its result version 33...

Страница 356: ...0 332 4 21 336 4 22 340 1 23 341 8 24 349 8 25 357 8 26 365 2 27 367 2 28 369 4 29 373 4 30 377 1 31 378 2 32 380 8 33 388 4 34 392 4 35 396 4 36 400 4 37 404 1 38 405 4 39 409 4 40 413 4 41 417 4 42 421 4 43 425 4 44 429 20 45 449 30 46 479 1 47 480 1 48 481 79 49 560 79 50 639 79 51 718 79 52 797 8 53 805 1 54 806 1 55 807 20 56 827 4 57 831 4 shell myisampack station MYI Compressing station MYI...

Страница 357: ... 31 1 3 9 7 32 30 no endspace not_always 5 9 8 62 35 no endspace not_always no empty 6 9 9 97 35 no empty 7 9 10 132 35 no endspace not_always no empty 6 9 11 167 4 zerofill 1 2 9 12 171 16 no endspace not_always no empty 5 9 13 187 35 no endspace not_always no empty 6 9 14 222 4 zerofill 1 2 9 15 226 16 no endspace not_always no empty 5 9 16 242 20 no endspace not_always 8 9 17 262 20 no endspace...

Страница 358: ...ler type For example a BIGINT column eight bytes can be stored as a TINYINT column one byte if all its values are in the range from 128 to 127 pre space The number of decimal columns that are stored with leading spaces In this case each value contains a count for the number of leading spaces end space The number of columns that have a lot of trailing spaces In this case each value contains a count...

Страница 359: ...time you can also sort the index blocks and create statistics needed for the MySQL optimizer to work more efficiently shell myisamchk rq sort index analyze tbl_name MYI After you have installed the packed table into the MySQL database directory you should execute mysqladmin flush tables to force mysqld to start using the new table To unpack a packed table use the unpack 325 option to myisamchk 4 6...

Страница 360: ...lan 341 Display suggestions and ideas for future releases preview 341 preview 341 Show the privilege differences after making changes to the temporary grant tables relnotes 341 relnotes 341 Display the release notes rhost host_name 341 rhost 341 Connect to the MySQL server on the given host rollback 341 rollback 341 Undo the most recent changes to the temporary grant tables spassword password 341 ...

Страница 361: ...ing a password on the command line should be considered insecure See Section 6 1 2 1 End User Guidelines for Password Security plan 341 Display suggestions and ideas for future releases preview 341 Show the privilege differences after making changes to the temporary grant tables relnotes 341 Display the release notes rhost host_name 341 H host_name Connect to the MySQL server on the given host rol...

Страница 362: ...binary log file named binlog 000003 use this command shell mysqlbinlog binlog 0000003 The output includes events contained in binlog 000003 Event information includes the SQL statement the ID of the server on which it was executed the timestamp when the statement was executed how much time it took and so forth Events are preceded by header comments that provide additional information For example a...

Страница 363: ...s are installed database db_name 344 database 344 List entries for just this database debug debug_options 345 debug 345 Write a debugging log disable log bin 345 disable log bin 345 Disable binary logging force read 345 force read 345 If mysqlbinlog reads a binary log event that it does not recognize it prints a warning help 344 Display help message and exit hexdump 345 hexdump 345 Display a hex d...

Страница 364: ...cter sets are installed See Section 10 5 Character Set Configuration database db_name 344 d db_name This option causes mysqlbinlog to output entries from the binary log local log only that occur while db_name is been selected as the default database by USE The database 344 option for mysqlbinlog is similar to the binlog do db 1469 option for mysqld but can be used to specify only one database If d...

Страница 365: ...aining output The SET statement is ineffective unless you have the SUPER 578 privilege force read 345 f With this option if mysqlbinlog reads a binary log event that it does not recognize it prints a warning ignores the event and continues Without this option mysqlbinlog stops if it reads such an event hexdump 345 H Display a hex dump of the log in comments The hex output can be helpful for replic...

Страница 366: ...346 Add a SET NAMES charset_name statement to the output to specify the character set to be used for processing log files This option was added in MySQL 5 0 23 short form 346 s Display only the statements contained in the log without any extra information This is for testing only and should not be used in production systems socket path 346 S path For connections to localhost the Unix socket file t...

Страница 367: ...isplay version information and exit In MySQL 5 0 the version number shown for mysqlbinlog is always 3 2 You can also set the following variable by using var_name value syntax open_files_limit Specify the number of open file descriptors to reserve It is also possible to set variables by using set variable var_name value or O var_name value syntax This syntax is deprecated You can pipe the output of...

Страница 368: ... reproduces a LOAD DATA INFILE operation without the original data file mysqlbinlog copies the data to a temporary file and writes a LOAD DATA LOCAL INFILE statement that refers to the file The default location of the directory where these files are written is system specific To specify a directory explicitly use the local load 345 option Because mysqlbinlog converts LOAD DATA INFILE statements to...

Страница 369: ...E_EVENT Used for LOAD DATA INFILE statements This indicates the start of execution of such a statement A temporary file is created on the slave Used in MySQL 4 only 09 APPEND_BLOCK_EVENT Contains data for use in a LOAD DATA INFILE statement The data is stored in the temporary file on the slave 0a EXEC_LOAD_EVENTUsed for LOAD DATA INFILE statements The contents of the temporary file is stored in th...

Страница 370: ...time to execute see Section 5 2 4 The Slow Query Log mysqldumpslow parses MySQL slow query log files and prints a summary of their contents Normally mysqldumpslow groups queries that are similar except for the particular values of number and string data values It abstracts these values to N and S when displaying summary output The a and n options can be used to modify value abstracting behavior In...

Страница 371: ...ld be chosen from the following list t at Sort by query time or average query time l al Sort by lock time or average lock time r ar Sort by rows sent or average rows sent c Sort by count By default mysqldumpslow sorts by average query time equivalent to s at t N Display only the first N queries in the output verbose 351 v Verbose mode Print more information about what the program does Example of u...

Страница 372: ...which can be specified on the command line or in the mysqlhotcopy and client groups of an option file For information about option files see Section 4 2 3 3 Using Option Files Table 4 12 mysqlhotcopy Options Format Option File Description addtodest 353 addtodest 353 Do not rename target directory if it exists merely add files to it allowold 353 allowold 353 Do not abort if a target exists rename i...

Страница 373: ...o the specified database db_name and table tbl_name chroot path 353 Base directory of the chroot jail in which mysqld operates The path value should match that of the chroot 403 option given to mysqld debug 353 Enable debug output dryrun 353 n Report actions without performing them flushlog 353 Flush logs after all tables are locked host host_name 353 h host_name The host name of the local host to...

Страница 374: ...e 354 Reset the master info file after locking all the tables socket path 354 S path The Unix socket file to use for connections to localhost suffix str 354 The suffix to use for names of copied databases tmpdir path 354 The temporary directory The default is tmp user user_name 354 u user_name The MySQL user name to use when connecting to the server Use perldoc for additional mysqlhotcopy document...

Страница 375: ...SQL Server instances but you can connect to it from a remote host to perform instance management operations The following sections describe MySQL Instance Manager operation in more detail 4 6 10 1 MySQL Instance Manager Command Options Important MySQL Instance Manager is been deprecated in MySQL 5 1 and is removed in MySQL 5 5 The MySQL Instance Manager supports a number of command options For a b...

Страница 376: ...anager is started To ensure that the file is created in a specific directory specify it as a full path name If run as service 357 is given without log 356 the log file is mysqlmanager log in the data directory If run as service 357 is not given log messages go to the standard output To capture log output you can redirect Instance Manager output to a file mysqlmanager im log monitoring interval sec...

Страница 377: ...indows service This assumes that Instance Manager has been run with install 356 previously This option was added in MySQL 5 0 11 run as service 357 On Unix daemonize and start an angel process The angel process monitors Instance Manager and restarts it if it crashes The angel process itself is simple and unlikely to crash socket path 357 On Unix the socket file to use for incoming connections The ...

Страница 378: ...d monitoring interval 2 port 1999 bind address 192 168 1 5 Each mysqld or mysqldN instance section specifies options given by Instance Manager to a server instance at startup These are mainly common MySQL Server options see Section 5 1 3 Server Command Options In addition a mysqldN section can contain the options in the following list which are specific to Instance Manager These options are interp...

Страница 379: ... In prior versions of MySQL the mysqld_safe script is used for this purpose Starting from MySQL 5 0 4 the behavior of the startup script was changed again to incorporate both setup schemes In version 5 0 4 the startup script uses the old scheme invoking mysqld_safe by default but one can set the use_mysqld_safe variable in the script to 0 zero to use the MySQL Instance Manager to start a server St...

Страница 380: ...mysql stop command it shuts down all server instances 4 6 10 4 Instance Manager User and Password Management Important MySQL Instance Manager is been deprecated in MySQL 5 1 and is removed in MySQL 5 5 The Instance Manager stores its user information in a password file On Windows the default is mysqlmanager passwd in the directory where Instance Manager is installed On Unix the default file is etc...

Страница 381: ...erate the password entry shell mysql B skip column name e SELECT CONCAT user_name PASSWORD pass_val The output from the command can be used an entry in the etc mysqlmanager passwd file 4 6 10 5 MySQL Server Instance Status Monitoring Important MySQL Instance Manager is been deprecated in MySQL 5 1 and is removed in MySQL 5 5 To monitor the status of each guarded server instance the MySQL Instance ...

Страница 382: ...es from the configuration file if it exists but some commands change the configuration of an instance Commands that modify the configuration file fail if the file does not exist or is not accessible to Instance Manager On Windows the standard file is my ini in the directory where Instance Manager is installed On Unix the standard configuration file is etc my cnf To specify a different configuratio...

Страница 383: ...Instance Manager tries to guess its placement If Instance Manager is unable to guess the log file placement you should specify the log file location explicitly by using a log option in the appropriate instance section of the configuration file mysql SHOW mysqld LOG FILES Logfile Path Filesize ERROR LOG home cps var mysql owlet err 9186 GENERAL LOG home cps var mysql owlet log 471503 SLOW LOG home ...

Страница 384: ...l a FLUSH INSTANCES command is executed FLUSH INSTANCES This command forces Instance Manager reread the configuration file and to refresh internal structures This command should be performed after editing the configuration file The command does not restart instances mysql FLUSH INSTANCES Query OK 0 rows affected 0 04 sec FLUSH INSTANCES is deprecated and will be removed in MySQL 5 2 4 6 11 mysql_c...

Страница 385: ...on about what the program does version 365 Display version information and exit 4 6 12 mysql_explain_log Use EXPLAIN on Statements in Query Log mysql_explain_log reads its standard input for query log contents It uses EXPLAIN to analyze SELECT statements found in the input UPDATE statements are rewritten to SELECT statements and also analyzed with EXPLAIN mysql_explain_log then displays a summary ...

Страница 386: ... SQL statements as long as statements are terminated with semicolons Invoke mysql_find_rows like this shell mysql_find_rows options file_name Each file_name argument should be the name of file containing SQL statements If no file names are given mysql_find_rows reads the standard input Examples mysql_find_rows regexp problem_table rows 20 update log mysql_find_rows regexp problem_table update log ...

Страница 387: ...ons you have when attempting to modify existing permissions in the grant tables mysql_setpermissions also reads options from the client and perl groups in the my cnf file in your home directory if the file exists mysql_setpermission supports the following options help 367 Display a help message and exit host host_name 367 Connect to the MySQL server on the given host password password 367 The pass...

Страница 388: ...rd stores information for tables in the mydb database that have names matching the pattern tmp mysql_tableinfo supports the following options Table 4 13 mysql_tableinfo Options Format Option File Description clear 368 clear 368 Before populating each metadata table drop it if it exists clear only 369 clear only 369 Similar to clear but exits after dropping the metadata tables to be populated col 3...

Страница 389: ...r Password Security port port_num 369 P port_num The TCP IP port number to use for the connection prefix prefix_str 369 Add prefix_str at the beginning of each metadata table name quiet 369 q Be silent except for errors socket path 369 S path The Unix socket file to use for the connection tbl status 369 Use SHOW TABLE STATUS instead of SHOW TABLES This provides more complete information but is slo...

Страница 390: ...mation for each process Respond y to kill the process or q to exit mysql_zap For any other response mysql_zap does not attempt to kill the process If the signal option is given it specifies the name or number of the signal to send to each process Otherwise mysql_zap tries first with TERM signal 15 and then with KILL signal 9 mysql_zap supports the following additional options help 370 I Display a ...

Страница 391: ... converts the input file in place so make a copy of the original before converting it For example use msql2mysql like this shell cp client prog c client prog c orig shell msql2mysql client prog c client prog c converted Then examine client prog c and make any post conversion revisions that may be necessary msql2mysql uses the replace utility to make the function name substitutions See Section 4 8 ...

Страница 392: ...ample to compile and link a MySQL client program use mysql_config as follows shell gcc c mysql_config cflags progname c shell gcc o progname progname o mysql_config libs 4 7 3 my_print_defaults Display Options from Option Files my_print_defaults displays the options that are present in option groups of option files The output indicates what options will be used by programs that read the specified ...

Страница 393: ...ke resolve_stack_dump like this shell resolve_stack_dump options symbols_file numeric_dump_file The symbols file should include the output from the nm numeric sort mysqld command The numeric dump file should contain a numeric stack track from mysqld If no numeric dump file is named on the command line the stack trace is read from the standard input resolve_stack_dump supports the following options...

Страница 394: ... the error message for a MySQL Cluster error code silent 374 s Silent mode Print only the error message verbose 374 v Verbose mode Print error code and message This is the default behavior version 374 V Display version information and exit 4 8 2 replace A String Replacement Utility The replace utility program changes strings in place in files or on the standard input Invoke replace in one of the f...

Страница 395: ...ns I Display a help message and exit debug_options Enable debugging s Silent mode Print less information what the program does v Verbose mode Print more information about what the program does V Display version information and exit 4 8 3 resolveip Resolve Host name to IP Address or Vice Versa The resolveip utility resolves host names to IP addresses and vice versa Invoke resolveip like this shell ...

Страница 396: ...376 ...

Страница 397: ...ient Programs in a Multiple Server Environment 556 End of Product Lifecycle Active development for MySQL Database Server version 5 0 has ended Oracle offers various support offerings which may be of interest For details and more information see the MySQL section of the Lifetime Support Policy for Oracle Technology Products http www oracle com us support lifetime support index html Please consider ...

Страница 398: ...ly below the corresponding option For status variables the scope of the variable is shown Scope as either global session or both Please see the corresponding sections for details on setting and using the options and variables Where appropriate a direct link to further information on the item as available For a version of this table that is specific to MySQL Cluster see Section 17 3 4 1 MySQL Clust...

Страница 399: ...Session Yes bind address 401 Yes Yes Yes Global No Binlog_cache_disk_use 523 Yes Global No binlog_cache_size 440 Yes Yes Yes Global Yes Binlog_cache_use 523 Yes Global No binlog do db 1469 Yes Yes binlog ignore db 1470 Yes Yes bootstrap 402 Yes Yes bulk_insert_buffer_size 441 Yes Yes Yes Both Yes Bytes_received 523 Yes Both No Bytes_sent 523 Yes Both No character_set_client 441 Yes Both Yes charac...

Страница 400: ...ble 523 Yes Both No Com_analyze 523 Yes Both No Com_backup_table 523 Yes Both No Com_begin 523 Yes Both No Com_call_procedure 523 Yes Both No Com_change_db 523 Yes Both No Com_change_master 523 Yes Both No Com_check 523 Yes Both No Com_checksum 523 Yes Both No Com_commit 523 Yes Both No Com_create_db 523 Yes Both No Com_create_event 523 Yes Both No Com_create_function 523 Yes Both No Com_create_in...

Страница 401: ...Com_purge_before_date 523 Yes Both No Com_rename_table 523 Yes Both No Com_repair 523 Yes Both No Com_replace 523 Yes Both No Com_replace_select 523 Yes Both No Com_reset 523 Yes Both No Com_restore_table 523 Yes Both No Com_revoke 523 Yes Both No Com_revoke_all 523 Yes Both No Com_rollback 523 Yes Both No Com_savepoint 523 Yes Both No Com_select 523 Yes Both No Com_set_option 523 Yes Both No Com_...

Страница 402: ...slave_hosts 523 Yes Both No Com_show_slave_status 523 Yes Both No Com_show_status 523 Yes Both No Com_show_storage_engines 523 Yes Both No Com_show_tables 523 Yes Both No Com_show_triggers 523 Yes Both No Com_show_variables 523 Yes Both No Com_show_warnings 523 Yes Both No Com_slave_start 523 Yes Both No Com_slave_stop 523 Yes Both No Com_stmt_close 523 Yes Both No Com_stmt_execute 523 Yes Both No...

Страница 403: ... debug 405 Yes Yes Yes Both Yes default character set 405 Yes Yes default storage engine 405 Yes Yes Yes Both Yes default table type 406 Yes Yes default time zone 406 Yes Yes default_week_format 446 Yes Yes Yes Both Yes defaults extra file 239 Yes defaults file 240 Yes defaults group suffix 240 Yes delay key write 406 Yes Yes Global Yes Variable delay_key_write Yes Global Yes Delayed_errors 525 Ye...

Страница 404: ...foreign_key_checks 451 Yes Session Yes ft_boolean_syntax 451 Yes Yes Yes Global Yes ft_max_word_len 452 Yes Yes Yes Global No ft_min_word_len 452 Yes Yes Yes Global No ft_query_expansion_limit 453 Yes Yes Yes Global No ft_stopword_file 453 Yes Yes Yes Global No gdb 408 Yes Yes group_concat_max_len 453 Yes Yes Yes Both Yes Handler_commit 525 Yes Both No Handler_delete 525 Yes Both No Handler_discov...

Страница 405: ...have_profiling 455 Yes Global No have_query_cache 455 Yes Global No have_raid 455 Yes Global No have_rtree_keys 455 Yes Global No have_ssl 455 Yes Global No have_symlink 455 Yes Global No help 400 Yes Yes hostname 455 Yes Global No identity 456 Yes Session Yes init_connect 456 Yes Yes Yes Global Yes init file 409 Yes Yes Global No Variable init_file Yes Global No init rpl role Yes Yes init_slave 1...

Страница 406: ...Yes Global No Innodb_data_pending_reads 527 Yes Global No Innodb_data_pending_writes 527 Yes Global No Innodb_data_read 527 Yes Global No Innodb_data_reads 527 Yes Global No Innodb_data_writes 527 Yes Global No Innodb_data_written 527 Yes Global No Innodb_dblwr_pages_written 527 Yes Global No Innodb_dblwr_writes 527 Yes Global No innodb_doublewrite 1240 Yes Yes Yes Global No innodb_fast_shutdown 1...

Страница 407: ...ow_lock_current_waits 528 Yes Global No Innodb_row_lock_time 528 Yes Global No Innodb_row_lock_time_avg 528 Yes Global No Innodb_row_lock_time_max 528 Yes Global No Innodb_row_lock_waits 528 Yes Global No Innodb_rows_deleted 528 Yes Global No Innodb_rows_inserted 528 Yes Global No Innodb_rows_read 529 Yes Global No Innodb_rows_updated 529 Yes Global No innodb safe binlog 409 Yes Yes innodb status ...

Страница 408: ...support 461 Yes Global No large_page_size 461 Yes Global No large pages 410 Yes Yes Global No Variable large_pages Yes Global No last_insert_id 462 Yes Session Yes Last_query_cost 529 Yes Session No lc_time_names 462 Yes Both Yes license 462 Yes Global No local_infile 462 Yes Global Yes locked_in_memory 463 Yes Global No log 411 Yes Yes Yes Global No log_bin 1471 Yes Global No log bin 1467 Yes Yes...

Страница 409: ...g slow queries 412 Yes Yes Global No Variable log_slow_queries Yes Global No log tc 413 Yes Yes log tc size 413 Yes Yes log warnings 414 Yes Yes Both Yes Variable log_warnings Yes Both Yes long_query_time 465 Yes Yes Yes Both Yes low priority updates 414 Yes Yes Both Yes Variable low_priority_updates Yes Both Yes lower_case_file_system 465 Yes Yes Yes Global No lower_case_table_names 466 Yes Yes Y...

Страница 410: ...e 468 Yes Yes Yes Both Yes max_insert_delayed_threads 469 Yes Both Yes max_join_size 469 Yes Yes Yes Both Yes max_length_for_sort_data 470 Yes Yes Yes Both Yes max_prepared_stmt_count 470 Yes Yes Yes Global Yes max_relay_log_size 470 Yes Yes Yes Global Yes max_seeks_for_key 471 Yes Yes Yes Both Yes max_sort_length 471 Yes Yes Yes Both Yes max_sp_recursion_depth 472 Yes Yes Yes Both Yes Max_used_co...

Страница 411: ...es ndb_index_stat_cache_entries 1613 Yes Yes ndb_index_stat_enable 1613 Yes Yes ndb_index_stat_update_freq 1614 Yes Yes ndb mgmd host 1610 Yes Yes ndb nodeid 1610 Yes Yes Yes Global No ndb_optimized_node_selection 1614 Yes Yes ndb_report_thresh_binlog_epoch_slip 1614 Yes Yes ndb_report_thresh_binlog_mem_usage 1614 Yes Yes ndb_use_exact_count 1615 Yes Both Yes ndb_use_transactions 1615 Yes Yes Yes ...

Страница 412: ...l No print defaults 240 Yes profiling 483 Yes Session Yes profiling_history_size 483 Yes Yes Yes Both Yes protocol_version 483 Yes Global No pseudo_thread_id 483 Yes Session Yes Qcache_free_blocks 530 Yes Global No Qcache_free_memory 530 Yes Global No Qcache_hits 530 Yes Global No Qcache_inserts 530 Yes Global No Qcache_lowmem_prunes 530 Yes Global No Qcache_not_cached 530 Yes Global No Qcache_que...

Страница 413: ..._index Yes Global No relay_log_index 1464 Yes Yes Yes Global No relay log info file 1456 Yes Yes Variable relay_log_info_file relay_log_info_file 1465 Yes Yes Yes Global No relay_log_purge 489 Yes Yes Yes Global Yes relay_log_space_limit 490 Yes Yes Yes Global No remove 418 Yes replicate do db 1457 Yes Yes replicate do table 1458 Yes Yes replicate ignore db 1457 Yes Yes replicate ignore table 1458...

Страница 414: ...er create 419 Yes Yes safemalloc mem limit Yes Yes secure auth 419 Yes Yes Global Yes Variable secure_auth Yes Global Yes secure file priv 419 Yes Yes Global No Variable secure_file_priv Yes Global No Select_full_join 531 Yes Both No Select_full_range_join 531 Yes Both No Select_range 531 Yes Both No Select_range_check 531 Yes Both No Select_scan 531 Yes Both No server id 1442 Yes Yes Global Yes V...

Страница 415: ...merge 420 Yes Yes Variable skip name resolve 420 Yes Yes Global No Variable skip_name_resolve Yes Global No skip networking 421 Yes Yes Global No Variable skip_networking Yes Global No skip new Yes Yes skip safemalloc 421 Yes Yes skip show database 421 Yes Yes Global No Variable skip_show_database Yes Global No skip slave start 1462 Yes Yes skip ssl 607 Yes Yes skip stack trace 422 Yes Yes skip sy...

Страница 416: ...es Global Yes Slow_queries 531 Yes Both No socket 422 Yes Yes Yes Global No sort_buffer_size 493 Yes Yes Yes Both Yes Sort_merge_passes 531 Yes Both No Sort_range 532 Yes Both No Sort_rows 532 Yes Both No Sort_scan 532 Yes Both No sporadic binlog dump fail 1471 Yes Yes sql_auto_is_null 493 Yes Session Yes sql_big_selects 493 Yes Session Yes sql_big_tables 401 Yes Session Yes sql_buffer_result 494 ...

Страница 417: ...st 532 Yes Both No Ssl_client_connects 532 Yes Global No Ssl_connect_renegotiates 532 Yes Global No Ssl_ctx_verify_depth 532 Yes Global No Ssl_ctx_verify_mode 532 Yes Global No Ssl_default_timeout 532 Yes Both No Ssl_finished_accepts 532 Yes Global No Ssl_finished_connects 532 Yes Global No ssl key 608 Yes Yes Global No Variable ssl_key Yes Global No Ssl_session_cache_hits 532 Yes Global No Ssl_se...

Страница 418: ...s Yes Tc_log_max_pages_used 533 Yes Global No Tc_log_page_size 533 Yes Global No Tc_log_page_waits 534 Yes Global No temp pool 423 Yes Yes thread_cache_size 499 Yes Yes Yes Global Yes thread_concurrency 499 Yes Yes Yes Global No thread_stack 500 Yes Yes Yes Global No Threads_cached 534 Yes Global No Threads_connected 534 Yes Global No Threads_created 534 Yes Global No Threads_running 534 Yes Globa...

Страница 419: ...my large cnf and my huge cnf which are sample option files for small medium large and very large systems On Windows the extension is ini rather than cnf Note On Windows the ini or cnf option file extension might not be displayed For a binary distribution look for the sample files in or under your installation directory If you have a source distribution look in the support files directory To use a ...

Страница 420: ...hat when you assign a value to an option that controls a buffer size the amount of space actually available might differ from the value assigned In some cases the amount might be less than the value assigned It is also possible that the server will adjust a value upward For example if you assign a value of 0 to an option for which the minimal value is 1024 the server will set the value to 1024 Val...

Страница 421: ...able Scope Global Dynamic Variable No Permitted Values Type file name The path to the MySQL installation directory All paths are usually resolved relative to this directory big tables 401 Command Line Format big tables Option File Format big tables Option Sets Variable Yes big_tables 440 Variable Name big tables Variable Scope Session Dynamic Variable Yes Permitted Values Type boolean Enable large...

Страница 422: ...ple if you bind to 0 0 0 0 you can connect to the server using all existing accounts But if you bind to 127 0 0 1 the server accepts connections only on that address In this case first make sure that the root 127 0 0 1 account is present in the mysql user table so that you can still connect to the server to shut it down bootstrap 402 Command Line Format bootstrap Option File Format bootstrap This ...

Страница 423: ...03 C charset_name Command Line Format character set server Option File Format character set server Option Sets Variable Yes character_set_server 443 Variable Name character_set_server Variable Scope Global Session Dynamic Variable Yes Permitted Values Type string Use charset_name as the default server character set See Section 10 5 Character Set Configuration If you use this option to specify a no...

Страница 424: ...is written to the current working directory of the process which for mysqld is the data directory pid represents the process ID of the server process On Mac OS X a core file named core pid is written to the cores directory On Solaris use the coreadm command to specify where to write the core file and how to name it For some systems to get a core file you must also specify the core file size 247 op...

Страница 425: ...s to dump a parser trace to the server s standard error output Typically this output is written to the error log default character set charset_name 405 Version Deprecated 5 0 Command Line Format default character set name C name Option File Format default character set name Deprecated 5 0 Permitted Values Type string Use charset_name as the default character set This option is deprecated in favor ...

Страница 426: ... option sets the global time_zone 500 system variable If this option is not given the default time zone is the same as the system time zone given by the value of the system_time_zone 498 system variable delay key write OFF ON ALL 406 Command Line Format delay key write name Option File Format delay key write Option Sets Variable Yes delay_key_write 447 Variable Name delay key write Variable Scope ...

Страница 427: ...s named_pipe 477 Platform Specific windows Enable support for named pipes This option can be used only with the mysqld nt and mysqld debug servers that support named pipe connections enable pstack 407 Command Line Format enable pstack Option File Format enable pstack Deprecated 5 1 54 Permitted Values Type boolean Default FALSE Print a symbolic stack trace on failure This capability is available o...

Страница 428: ... Type boolean Default FALSE Enable external locking system locking which is disabled by default as of MySQL 4 0 Note that if you use this option on a system on which lockd does not fully work such as Linux it is easy for mysqld to deadlock This option previously was named enable locking External locking affects only MyISAM table access For more information including conditions under which it can a...

Страница 429: ...ured with the disable grant options 123 option See Section 2 17 3 MySQL Source Configuration Options innodb safe binlog 409 Version Removed 5 0 3 Version Deprecated 5 0 3 Command Line Format innodb safe binlog Option File Format innodb safe binlog Deprecated 5 0 3 Permitted Values Type boolean If this option is given then after a crash recovery by InnoDB mysqld truncates the binary log after the l...

Страница 430: ...iable Scope Global Dynamic Variable No Deprecated 5 6 1 Permitted Values Type directory name Default usr local mysql share mysql english The language to use for error messages lang_name can be given as the language name or as the full path name to the directory where the language files are installed See Section 10 2 Setting the Error Message Language large pages 410 Version Introduced 5 0 3 Comman...

Страница 431: ...See Section 5 2 2 The General Query Log If you omit the file name MySQL uses host_name log as the file name log error file_name 411 Command Line Format log error name Option File Format log error Option Sets Variable Yes log_error 463 Variable Name log_error Variable Scope Global Dynamic Variable No Permitted Values Type file name Log errors and startup messages to this file See Section 5 2 1 The ...

Страница 432: ...fault OFF If you are using this option with the slow query log enabled queries that are expected to retrieve all rows are logged See Section 5 2 4 The Slow Query Log This option does not necessarily mean that no index is used For example a query that uses a full index scan uses an index but would be logged because the index would not limit the number of rows log short format 412 Command Line Forma...

Страница 433: ...13 Version Introduced 5 0 3 Command Line Format log tc name Option File Format log tc Permitted Values Type file name Default tc log The name of the memory mapped transaction coordinator log file for XA transactions that affect multiple storage engines when the binary log is disabled The default name is tc log The file is created under the data directory if not given as a full path name Currently ...

Страница 434: ...tions are written to the error log See Section C 5 2 11 Communication Errors and Aborted Connections If a slave server was started with log warnings 414 enabled the slave prints messages to the error log to provide information about its status such as the binary log and relay log coordinates where it starts its job when it is switching to another relay log when it reconnects after a disconnect and...

Страница 435: ...see in the output of the previous command something like the following extern int mlockall int __flags __THROW Important Use of this option may require you to run the server as root which for reasons of security is normally not a good idea See Section 6 1 5 How to Run MySQL as a Normal User On Linux and perhaps other systems you can avoid the need to run the server as root by changing the limits c...

Страница 436: ...f the data file was changed during recovery save a backup of the tbl_name MYD file as tbl_name datetime BAK FORCE Run recovery even if we would lose more than one row from the MYD file QUICK Do not check the rows in the table if there are not any delete blocks Before the server automatically repairs a table it writes a note about the repair to the error log If you want to be able to recover from m...

Страница 437: ... the error log mysqld may attempt to allocate more than the requested number of descriptors if they are available using the values of max_connections 467 and table_cache 498 to estimate whether more descriptors will be needed On Unix the value cannot be set less than ulimit n pid file path 417 Command Line Format pid file file_name Option File Format pid file file_name Option Sets Variable Yes pid...

Страница 438: ... 5 0 19 remove service_name 418 Command Line Format remove service_name Windows only Remove a MySQL Windows service The default service name is MySQL if no service_name value is given For more information see Section 2 10 4 7 Starting MySQL as a Windows Service safe mode 418 Command Line Format safe mode Option File Format safe mode Deprecated 5 5 26 Skip some optimization stages This option is de...

Страница 439: ...mic Variable Yes This option causes the server to block connections by clients that attempt to use accounts that have passwords stored in the old pre 4 1 format Use it to prevent all use of passwords employing the old format and hence insecure communication over the network Server startup fails with an error if this option is enabled and the privilege tables are in pre 4 1 format See Section C 5 2...

Страница 440: ...he grant tables again by executing mysqladmin flush privileges or mysqladmin reload command from a system shell or by issuing a MySQL FLUSH PRIVILEGES statement after connecting to the server This option also suppresses loading of user defined functions UDFs Note that FLUSH PRIVILEGES might be executed implicitly by other actions performed after startup For example mysql_upgrade flushes the privil...

Страница 441: ...nable or disable symbolic link support This option has different effects on Windows and Unix On Windows enabling symbolic links enables you to establish a symbolic link to a database directory by creating a db_name sym file that contains the path to the real directory See Section 8 9 6 3 Using Symbolic Links for Databases on Windows On Unix enabling symbolic links means that you can link a MyISAM ...

Страница 442: ...t may be a source of noise for debugging tools For example they can overwhelm other information of more interest in kernel logs To avoid these calls start the server with the skip thread priority 422 option socket path 422 Command Line Format socket name Option File Format socket Option Sets Variable Yes socket 492 Variable Name socket Variable Scope Global Dynamic Variable No Permitted Values Typ...

Страница 443: ...QL 5 0 20 tc heuristic recover COMMIT ROLLBACK 423 Version Introduced 5 0 3 Command Line Format tc heuristic recover name Option File Format tc heuristic recover Permitted Values Type enumeration Valid Values COMMIT RECOVER The type of decision to use in the heuristic recovery process Currently this option is unused Added in MySQL 5 0 3 temp pool 423 Command Line Format temp pool Option File Forma...

Страница 444: ...old temporary tables This option accepts several paths that are used in round robin fashion Paths should be separated by colon characters on Unix and semicolon characters on Windows NetWare and OS 2 If the MySQL server is acting as a replication slave you should not set tmpdir 424 to point to a directory on a memory based file system or to a directory that is cleared when the server host restarts ...

Страница 445: ...he value to stay within a given range or adjust the value to the closest permissible value if only certain values are permitted If you want to restrict the maximum value to which a variable can be set at runtime with SET you can define this by using the maximum var_name value command line option It is also possible to set variables by using set variable var_name value or O var_name value syntax Th...

Страница 446: ...es auto_increment_offset 1449 Yes Yes Yes Both Yes autocommit 436 Yes Yes Yes Session Yes automatic_sp_privileges 437 Yes Global Yes back_log 437 Yes Yes Yes Global No basedir 401 Yes Yes Yes Global No bdb_cache_size 438 Yes Yes Yes Global No bdb home 1309 Yes Yes No Variable bdb_home Yes Global No bdb lock detect 1309 Yes Yes No Variable bdb_lock_detect Yes Global No bdb_log_buffer_size 438 Yes Y...

Страница 447: ... Both Yes completion_type 444 Yes Yes Yes Both Yes concurrent_insert 445 Yes Yes Yes Global Yes connect_timeout 445 Yes Yes Yes Global Yes datadir 404 Yes Yes Yes Global No date_format 446 Yes Both No datetime_format 446 Yes Both No debug 405 Yes Yes Yes Both Yes default storage engine 405 Yes Yes Yes Both Yes default_week_format 446 Yes Yes Yes Both Yes delay key write 406 Yes Yes Yes Variable de...

Страница 448: ...e 454 Yes Global No have_federated_engine 455 Yes Global No have_geometry 455 Yes Global No have_innodb 455 Yes Global No have_isam 455 Yes Global No have_merge_engine 455 Yes Global No have_ndbcluster 1611 Yes Global No have_openssl 455 Yes Global No have_profiling 455 Yes Global No have_query_cache 455 Yes Global No have_raid 455 Yes Global No have_rtree_keys 455 Yes Global No have_ssl 455 Yes G...

Страница 449: ..._file_size 1247 Yes Yes Yes Global No innodb_log_files_in_group 1247 Yes Yes Yes Global No innodb_log_group_home_dir 1248 Yes Yes Yes Global No innodb_max_dirty_pages_pct 1248 Yes Yes Yes Global Yes innodb_max_purge_lag 1248 Yes Yes Yes Global Yes innodb_mirrored_log_groups 1249 Yes Yes Yes Global No innodb_open_files 1249 Yes Yes Yes Global No innodb_rollback_on_timeout 1249 Yes Yes Yes Global No...

Страница 450: ...le log_bin_trust_function_creators Yes Global Yes log bin trust routine creators 1468 Yes Yes Yes Variable log_bin_trust_routine_creators Yes Global Yes log error 411 Yes Yes No Variable log_error Yes Global No log queries not using indexes 412 Yes Yes Yes Variable log_queries_not_using_indexes Yes Global Yes log slave updates 1451 Yes Yes No Variable log_slave_updates Yes Global No log_slave_upda...

Страница 451: ...sp_recursion_depth 472 Yes Yes Yes Both Yes max_user_connections 472 Yes Yes Yes Both Yes max_write_lock_count 473 Yes Yes Yes Global Yes memlock 415 Yes Yes Yes Global No multi_range_count 1611 Yes Yes Yes Both Yes myisam_data_pointer_size 473 Yes Yes Yes Global Yes myisam_max_extra_sort_file_size 474 Yes Yes Yes Global No myisam_max_sort_file_size 474 Yes Yes Yes Global Yes myisam_mmap_size 474 ...

Страница 452: ...es Yes Both Yes query_cache_limit 484 Yes Yes Yes Global Yes query_cache_min_res_unit 484 Yes Yes Yes Global Yes query_cache_size 485 Yes Yes Yes Global Yes query_cache_type 485 Yes Yes Yes Both Yes query_cache_wlock_invalidate 486 Yes Yes Yes Both Yes query_prealloc_size 486 Yes Yes Yes Both Yes rand_seed1 487 Yes Session Yes rand_seed2 487 Yes Session Yes range_alloc_block_size 487 Yes Yes Yes B...

Страница 453: ... secure_auth Yes Global Yes secure file priv 419 Yes Yes No Variable secure_file_priv Yes Global No server id 1442 Yes Yes Yes Variable server_id Yes Global Yes shared_memory 491 Yes Global No shared_memory_base_name 491 Yes Global No skip external locking 420 Yes Yes No Variable skip_external_locking Yes Global No skip name resolve 420 Yes Yes No Variable skip_name_resolve Yes Global No skip netw...

Страница 454: ...es sql_big_tables 401 Yes Session Yes sql_buffer_result 494 Yes Session Yes sql_log_bin 494 Yes Session Yes sql_log_off 494 Yes Session Yes sql_log_update 494 Yes Session Yes sql_low_priority_updates 465 Yes Both Yes sql_max_join_size 469 Yes Both Yes sql mode 422 Yes Yes Yes Variable sql_mode Yes Both Yes sql_notes 495 Yes Session Yes sql_quote_show_create 495 Yes Session Yes sql_safe_updates 495...

Страница 455: ...ion_prealloc_size 503 Yes Yes Yes Both Yes tx_isolation 504 Yes Both Yes unique_checks 504 Yes Session Yes updatable_views_with_limit 504 Yes Yes Yes Both Yes version 505 Yes Global No version_comment 505 Yes Global No version_compile_machine 506 Yes Global No version_compile_os 506 Yes Global No wait_timeout 506 Yes Yes Yes Both Yes warning_count 507 Yes Session No a This option is dynamic but on...

Страница 456: ...is 1024 the server will set the value to 1024 Values for buffer sizes lengths and stack sizes are given in bytes unless otherwise specified Some system variables take file name values Unless otherwise specified the default file location is the data directory if the value is a relative path name To specify the location explicitly use an absolute path name Suppose that the data directory is var mysq...

Страница 457: ...e also Section 18 2 2 Stored Routines and MySQL Privileges This variable was added in MySQL 5 0 3 back_log 437 Command Line Format back_log Option File Format back_log Option Sets Variable Yes back_log 437 Variable Name back_log Variable Scope Global Dynamic Variable No The number of outstanding connection requests MySQL can have This comes into play when the main MySQL thread gets very many conne...

Страница 458: ...namic Variable No Permitted Values Type numeric Min Value 20480 The size of the buffer that is allocated for caching indexes and rows for BDB tables If you do not use BDB tables you should start mysqld with skip bdb 420 to not allocate memory for this cache bdb_home 438 Command Line Format bdb home name Option File Format bdb home name Option Sets Variable Yes bdb_home 438 Variable Name bdb_home V...

Страница 459: ...ine writes its log files This variable can be set with the bdb logdir 1309 option bdb_max_lock 439 Command Line Format bdb_max_lock Option File Format bdb_max_lock Option Sets Variable Yes bdb_max_lock 439 Variable Name bdb_max_lock Variable Scope Global Dynamic Variable No Permitted Values Type numeric Default 10000 The maximum number of locks that can be active for a BDB table 10 000 by default ...

Страница 460: ...rror The table tbl_name is full does not occur for SELECT operations that require a large temporary table The default value for a new connection is 0 use in memory temporary tables Normally you should never need to set this variable because in memory tables are automatically converted to disk based tables as required Note This variable was formerly named sql_big_tables binlog_cache_size 440 Comman...

Страница 461: ...ype numeric Default 8388608 Range 0 18446744073709547520 MyISAM uses a special tree like cache to make bulk inserts faster for INSERT SELECT INSERT VALUES and LOAD DATA INFILE when adding data to nonempty tables This variable limits the size of the cache tree in bytes per thread Setting it to 0 disables this optimization The default value is 8MB character_set_client 441 Variable Name character_set...

Страница 462: ...Global Session Dynamic Variable Yes Footnote This option is dynamic but only the server should set this information You should not set the value of this variable manually Permitted Values Type string The character set used by the default database The server sets this variable whenever the default database changes If there is no default database the variable has the same value as character_set_serv...

Страница 463: ... File Format character set server Option Sets Variable Yes character_set_server 443 Variable Name character_set_server Variable Scope Global Session Dynamic Variable Yes Permitted Values Type string The server s default character set character_set_system 443 Variable Name character_set_system Variable Scope Global Dynamic Variable No Permitted Values Type string The character set used by the serve...

Страница 464: ...e is no default database the variable has the same value as collation_server 444 collation_server 444 Command Line Format collation server Option File Format collation server Option Sets Variable Yes collation_server 444 Variable Name collation_server Variable Scope Global Session Dynamic Variable Yes Permitted Values Type string The server s default collation completion_type 444 Version Introduce...

Страница 465: ...urrent_insert 445 Variable Name concurrent_insert Variable Scope Global Dynamic Variable Yes Permitted Values 5 0 5 Type boolean Default TRUE If 1 the default MySQL permits INSERT and SELECT statements to run concurrently for MyISAM tables that have no free blocks in the middle of the data file If you start mysqld with skip new 479 this variable is set to 0 In MySQL 5 0 6 this variable was changed...

Страница 466: ... Option File Format datadir Option Sets Variable Yes datadir 446 Variable Name datadir Variable Scope Global Dynamic Variable No Permitted Values Type file name The MySQL data directory This variable can be set with the datadir 404 option date_format 446 This variable is unused datetime_format 446 This variable is unused default_week_format 446 Command Line Format default_week_format Option File F...

Страница 467: ...e DELAY_KEY_WRITE option enabled If DELAY_KEY_WRITE is enabled for a table the key buffer is not flushed for the table on every index update but only when the table is closed This speeds up writes on keys a lot but if you use this feature you should add automatic checking of all MyISAM tables by starting the server with the myisam recover 415 option for example myisam recover BACKUP FORCE 415 See ...

Страница 468: ...Format delayed_insert_timeout Option Sets Variable Yes delayed_insert_timeout 448 Variable Name delayed_insert_timeout Variable Scope Global Dynamic Variable Yes Deprecated 5 6 7 Permitted Values Type numeric Default 300 How many seconds an INSERT DELAYED handler thread should wait for INSERT statements before terminating delayed_queue_size 448 Command Line Format delayed_queue_size Option File Fo...

Страница 469: ...riable Yes Permitted Values Type numeric Default 4 Range 0 30 This variable indicates the number of digits by which to increase the scale of the result of division operations performed with the 906 operator The default value is 4 The minimum and maximum values are 0 and 30 respectively The following example illustrates the effect of increasing the default value mysql SELECT 1 7 1 7 0 1429 mysql SE...

Страница 470: ...engine condition pushdown is enabled By default this variable is OFF 0 Setting it to ON 1 enables pushdown This variable was added in MySQL 5 0 3 error_count 450 The number of errors that resulted from the last statement that generated messages This variable is read only See Section 13 7 5 14 SHOW ERRORS Syntax expire_logs_days 450 Command Line Format expire_logs_days Option File Format expire_log...

Страница 471: ... resources foreign_key_checks 451 If set to 1 the default foreign key constraints for InnoDB tables are checked If set to 0 they are ignored Disabling foreign key checking can be useful for reloading InnoDB tables in an order different from that required by their parent child relationships See Section 14 2 3 4 InnoDB and FOREIGN KEY Constraints Setting foreign_key_checks 451 to 0 also affects data...

Страница 472: ...e the same but they are the only two that may be Positions 10 13 and 14 which by default are set to and are reserved for future extensions ft_max_word_len 452 Command Line Format ft_max_word_len Option File Format ft_max_word_len Option Sets Variable Yes ft_max_word_len 452 Variable Name ft_max_word_len Variable Scope Global Dynamic Variable No Permitted Values Type numeric Min Value 10 The maximu...

Страница 473: ...le_name Option Sets Variable Yes ft_stopword_file 453 Variable Name ft_stopword_file Variable Scope Global Dynamic Variable No Permitted Values Type file name The file from which to read the list of stopwords for full text searches The server looks for the file in the data directory unless an absolute path name is given to specify a different directory All the words from the file are used comments...

Страница 474: ...ole_engine 454 YES if mysqld supports BLACKHOLE tables NO if not have_community_features 454 YES if statement profiling capability is present NO if not If present the profiling system variable controls whether this capability is enabled or disabled See Section 13 7 5 29 SHOW PROFILES Syntax This variable was added in MySQL 5 0 82 have_compress 454 YES if the zlib compression library is available t...

Страница 475: ...bled or disabled See Section 13 7 5 29 SHOW PROFILES Syntax This variable was added in MySQL 5 0 82 have_query_cache 455 YES if mysqld supports the query cache NO if not have_raid 455 In MySQL 5 0 this variable appears only for reasons of backward compatibility It is always NO because RAID tables are no longer supported have_rtree_keys 455 YES if RTREE indexes are available NO if not These are use...

Страница 476: ...h client session begins by default with autocommit mode enabled There is no global autocommit 436 system variable to specify that autocommit should be disabled by default but init_connect 456 can be used to achieve the same effect SET GLOBAL init_connect SET autocommit 0 The init_connect 456 variable can also be set on the command line or in an option file To set the variable as just shown using a...

Страница 477: ...d System Variables insert_id 457 The value to be used by the following INSERT or ALTER TABLE statement when inserting an AUTO_INCREMENT value This is mainly used with the binary log interactive_timeout 457 Command Line Format interactive_timeout Option File Format interactive_timeout Option Sets Variable Yes interactive_timeout 457 Variable Name interactive_timeout Variable Scope Global Session Dy...

Страница 478: ... Introduced 5 0 48 Command Line Format keep_files_on_create Option File Format keep_files_on_create Option Sets Variable Yes keep_files_on_create 458 Variable Name keep_files_on_create Variable Scope Global Session Dynamic Variable Yes Permitted Values Type boolean Default OFF If a MyISAM table is created with no DATA DIRECTORY option the MYD file is created in the database directory By default if...

Страница 479: ...ning the Key_read_requests 529 Key_reads 529 Key_write_requests 529 and Key_writes 529 status variables See Section 13 7 5 SHOW Syntax The Key_reads Key_read_requests ratio should normally be less than 0 01 The Key_writes Key_write_requests ratio is usually near 1 if you are using mostly updates and deletes but might be much smaller if you tend to do updates that affect many rows at the same time ...

Страница 480: ...ize Variable Scope Global Dynamic Variable Yes Permitted Values Type numeric Default 1024 Range 512 16384 The size in bytes of blocks in the key cache The default value is 1024 See Section 8 6 1 The MyISAM Key Cache key_cache_division_limit 460 Command Line Format key_cache_division_limit Option File Format key_cache_division_limit Option Sets Variable Yes key_cache_division_limit 460 Variable Nam...

Страница 481: ...able No Whether mysqld was compiled with options for large file support large_pages 461 Version Introduced 5 0 3 Command Line Format large pages Option File Format large pages Option Sets Variable Yes large_pages 461 Variable Name large_pages Variable Scope Global Dynamic Variable No Platform Specific linux Permitted Values Type linux boolean Default FALSE Whether large page support is enabled via...

Страница 482: ...e_names 462 Version Introduced 5 0 25 Variable Name lc_time_names Variable Scope Global Session Dynamic Variable Yes Permitted Values Type string This variable specifies the locale that controls the language used to display day and month names and abbreviations This variable affects the output from the DATE_FORMAT 921 DAYNAME 923 and MONTHNAME 926 functions Locale names are POSIX style values such...

Страница 483: ...to create stored functions that will cause unsafe events to be written to the binary log If set to 0 the default users are not permitted to create or alter stored functions unless they have the SUPER 578 privilege in addition to the CREATE ROUTINE 576 or ALTER ROUTINE 576 privilege A setting of 0 also enforces the restriction that a function must be declared with the DETERMINISTIC characteristic o...

Страница 484: ...ry log See Section 5 2 4 The Slow Query Log This variable was added in MySQL 5 0 23 log_slow_queries 464 Command Line Format log slow queries name Option File Format log slow queries Option Sets Variable Yes log_slow_queries 464 Variable Name log_slow_queries Variable Scope Global Dynamic Variable No Deprecated 5 1 29 by slow query log Permitted Values Type boolean Whether slow queries should be l...

Страница 485: ...e query is logged to the slow query log file This value is measured in real time not CPU time so a query that is under the threshold on a lightly loaded system might be above the threshold on a heavily loaded one The minimum value is 1 The default is 10 See Section 5 2 4 The Slow Query Log low_priority_updates 465 Command Line Format low priority updates Option File Format low priority updates Opt...

Страница 486: ...given but compared in lowercase This option also applies to database names and table aliases For additional information see Section 9 2 2 Identifier Case Sensitivity You should not set this variable to 0 if you are running MySQL on a system that has case insensitive file names such as Windows or Mac OS X If you set this variable to 0 on such a system and access MyISAM tablenames using different le...

Страница 487: ...ion value is permitted but has no effect max_connect_errors 467 Command Line Format max_connect_errors Option File Format max_connect_errors Option Sets Variable Yes max_connect_errors 467 Variable Name max_connect_errors Variable Scope Global Dynamic Variable Yes If more than this many successive connection requests from a host are interrupted without a successful connection the server blocks tha...

Страница 488: ...to handle DELAYED rows in effect this disables DELAYED entirely For the SESSION value of this variable the only valid values are 0 or the GLOBAL value max_error_count 468 Command Line Format max_error_count Option File Format max_error_count Option Sets Variable Yes max_error_count 468 Variable Name max_error_count Variable Scope Global Session Dynamic Variable Yes Permitted Values Type numeric De...

Страница 489: ... How MySQL Uses Internal Temporary Tables max_heap_table_size is not replicated See Section 16 4 1 14 Replication and MEMORY Tables and Section 16 4 1 28 Replication and Variables for more information max_insert_delayed_threads 469 Variable Name max_insert_delayed_threads Variable Scope Global Session Dynamic Variable Yes Deprecated 5 6 7 Permitted Values Type numeric This variable is a synonym fo...

Страница 490: ...f on the size of index values that determines which filesort algorithm to use See Section 8 3 1 11 ORDER BY Optimization max_prepared_stmt_count 470 Version Introduced 5 0 21 Command Line Format max_prepared_stmt_count Option File Format max_prepared_stmt_count Option Sets Variable Yes max_prepared_stmt_count 470 Variable Name max_prepared_stmt_count Variable Scope Global Dynamic Variable Yes Perm...

Страница 491: ...between 4096 bytes and 1GB inclusive or to 0 The default value is 0 See Section 16 2 1 Replication Implementation Details max_seeks_for_key 471 Command Line Format max_seeks_for_key Option File Format max_seeks_for_key Option Sets Variable Yes max_seeks_for_key 471 Variable Name max_seeks_for_key Variable Scope Global Session Dynamic Variable Yes Permitted Values Platform Bit Size 32 Type numeric ...

Страница 492: ..._recursion_depth Variable Scope Global Session Dynamic Variable Yes Permitted Values Type numeric Default 0 Max Value 255 The number of times that any given stored procedure may be called recursively The default value for this option is 0 which completely disables recursion in stored procedures The maximum value is 255 Stored procedure recursion increases the demand on thread stack space If you in...

Страница 493: ... value is set to that limit Otherwise the session max_user_connections 472 value is set to the global value Account resource limits are specified using the GRANT statement See Section 6 3 4 Setting Account Resource Limits and Section 13 7 1 3 GRANT Syntax max_write_lock_count 473 Command Line Format max_write_lock_count Option File Format max_write_lock_count Option Sets Variable Yes max_write_loc...

Страница 494: ...ption File Format myisam_max_sort_file_size Option Sets Variable Yes myisam_max_sort_file_size 474 Variable Name myisam_max_sort_file_size Variable Scope Global Dynamic Variable Yes Permitted Values Platform Bit Size 32 Type numeric Default 2147483648 Permitted Values Platform Bit Size 64 Type numeric Default 9223372036854775807 The maximum size of the temporary file that MySQL is permitted to use...

Страница 495: ...ompressed MyISAM files If many compressed MyISAM tables are used the value can be decreased to reduce the likelihood of memory swapping problems This variable was added in MySQL 5 0 90 myisam_recover_options 475 Variable Name myisam_recover_options Variable Scope Global Dynamic Variable No The value of the myisam recover 415 option See Section 5 1 3 Server Command Options myisam_repair_threads 475...

Страница 496: ...yisam_sort_buffer_size Variable Scope Global Session Dynamic Variable Yes Permitted Values Platform Bit Size 32 Type numeric Default 8388608 Range 4 4294967295 Permitted Values Platform Bit Size 64 Type numeric Default 8388608 Range 4 18446744073709547520 The size of the buffer that is allocated when sorting MyISAM indexes during a REPAIR TABLE or when creating indexes with CREATE INDEX or ALTER T...

Страница 497: ...as described in Section 8 5 4 MyISAM Index Statistics Collection Any unique prefix of a valid value may be used to set the value of this variable This variable was added in MySQL 5 0 14 For older versions the statistics collection method is equivalent to nulls_equal named_pipe 477 Variable Name named_pipe Variable Scope Global Dynamic Variable No Platform Specific windows Permitted Values Type win...

Страница 498: ...ynamic Variable Yes Permitted Values Type numeric Default 30 Min Value 1 The number of seconds to wait for more data from a connection before aborting the read This timeout applies only to TCP IP connections not to connections made through Unix socket files named pipes or shared memory When the server is reading from the client net_read_timeout 478 is the timeout value controlling when to abort Wh...

Страница 499: ...e_timeout 479 Command Line Format net_write_timeout Option File Format net_write_timeout Option Sets Variable Yes net_write_timeout 479 Variable Name net_write_timeout Variable Scope Global Session Dynamic Variable Yes Permitted Values Type numeric Default 60 Min Value 1 The number of seconds to wait for a block to be written to a connection before aborting the write This timeout applies only to T...

Страница 500: ...ection 6 1 2 4 Password Hashing in MySQL one_shot 480 This is not a variable but it can be used when setting some variables It is described in Section 13 7 4 SET Syntax open_files_limit 480 Command Line Format open files limit Option File Format open files limit Option Sets Variable Yes open_files_limit 480 Variable Name open_files_limit Variable Scope Global Dynamic Variable No The number of file...

Страница 501: ...relations in a query result in better query plans but take longer to generate an execution plan for a query Values smaller than the number of relations in a query return an execution plan quicker but the resulting plan may be far from being optimal If set to 0 the system automatically picks a reasonable value If set to 63 the optimizer switches to the algorithm used in MySQL 5 0 0 and previous ver...

Страница 502: ... can be made safely port 482 Command Line Format port P Option File Format port Option Sets Variable Yes port 482 Variable Name port Variable Scope Global Dynamic Variable No Permitted Values Type numeric Default 3306 Range 0 65535 The number of the port on which the server listens for TCP IP connections This variable can be set with the port 417 option preload_buffer_size 482 Command Line Format ...

Страница 503: ...rofiling information if profiling 483 is enabled The default value is 15 The maximum value is 100 Setting the value to 0 effectively disables profiling See Section 13 7 5 29 SHOW PROFILES Syntax This variable was added in MySQL 5 0 37 Note This option does not apply to MySQL Enterprise Server users protocol_version 483 Variable Name protocol_version Variable Scope Global Dynamic Variable No Permit...

Страница 504: ...ion File Format query_cache_limit Option Sets Variable Yes query_cache_limit 484 Variable Name query_cache_limit Variable Scope Global Dynamic Variable Yes Permitted Values Platform Bit Size 32 Type numeric Default 1048576 Range 0 4294967295 Permitted Values Platform Bit Size 64 Type numeric Default 1048576 Range 0 18446744073709547520 Do not cache results that are larger than this number of bytes...

Страница 505: ...are multiples of 1024 other values are rounded down to the nearest multiple Note that query_cache_size 485 bytes of memory are allocated even if query_cache_type 485 is set to 0 See Section 8 6 3 3 Query Cache Configuration for more information The query cache needs a minimum size of about 40KB to allocate its structures The exact size depends on system architecture If you set the value of query_c...

Страница 506: ... Name query_cache_wlock_invalidate Variable Scope Global Session Dynamic Variable Yes Permitted Values Type boolean Default FALSE Normally when one client acquires a WRITE lock on a MyISAM table other clients are not blocked from issuing statements that read from the table if the query results are present in the query cache Setting this variable to 1 causes acquisition of a WRITE lock for a table ...

Страница 507: ...les is to support replication of the RAND 912 function For statements that invoke RAND 912 the master passes two values to the slave where they are used to seed the random number generator The slave uses these values to set the session variables rand_seed1 487 and rand_seed2 487 so that RAND 912 on the slave generates the same value as on the master rand_seed2 487 See the description for rand_seed...

Страница 508: ... any storage engine and apply in a general manner for optimization See Section 8 9 4 How MySQL Uses Memory for example read_only 488 Command Line Format read only Option File Format read_only Option Sets Variable Yes read_only 488 Variable Name read_only Variable Scope Global Dynamic Variable Yes Permitted Values Type boolean Default false This variable is off by default When it is enabled the ser...

Страница 509: ...ad_rnd_buffer_size 489 Variable Name read_rnd_buffer_size Variable Scope Global Session Dynamic Variable Yes Permitted Values Type numeric Default 262144 Range 8200 4294967295 When reading rows in sorted order following a key sorting operation the rows are read through this buffer to avoid disk seeks See Section 8 3 1 11 ORDER BY Optimization Setting the variable to a large value can improve ORDER...

Страница 510: ... for all relay logs secure_auth 490 Command Line Format secure auth Option File Format secure auth Option Sets Variable Yes secure_auth 490 Variable Name secure_auth Variable Scope Global Dynamic Variable Yes If this variable is enabled the server blocks connections by clients that attempt to use accounts that have passwords stored in the old pre 4 1 format Enable this variable to prevent all use ...

Страница 511: ...ult 0 Range 0 4294967295 The server ID used in replication to give each master and slave a unique identity This variable is set by the server id 1442 option For each server participating in replication you should pick a positive integer in the range from 1 to 2 32 1 to act as that server s ID shared_memory 491 Variable Name shared_memory Variable Scope Global Dynamic Variable No Platform Specific ...

Страница 512: ...e and the statement displays all database names If the value is OFF SHOW DATABASES is permitted to all users but displays the names of only those databases for which the user has the SHOW DATABASES 578 or other privilege Note that any global privilege is considered a privilege for the database slow_launch_time 492 Command Line Format slow_launch_time Option File Format slow_launch_time Option Sets...

Страница 513: ...esholds of 256KB and 2MB where larger values may significantly slow down memory allocation so you should consider staying below one of those values Experiment to find the best value for your workload See Section C 5 4 4 Where MySQL Stores Temporary Files The maximum permissible setting for sort_buffer_size 493 is 4GB sql_auto_is_null 493 Variable Name sql_auto_is_null Variable Scope Session Dynami...

Страница 514: ...ffer_result 494 forces results from SELECT statements to be put into temporary tables This helps MySQL free the table locks early and can be beneficial in cases where it takes a long time to send results to the client The default value is 0 sql_log_bin 494 Variable Name sql_log_bin Variable Scope Session Dynamic Variable Yes Permitted Values Type boolean If set to 0 no logging is done to the binar...

Страница 515: ...tes identifiers for SHOW CREATE TABLE and SHOW CREATE DATABASE statements If set to 0 quoting is disabled This option is enabled by default so that replication works for identifiers that require quoting See Section 13 7 5 9 SHOW CREATE TABLE Syntax and Section 13 7 5 6 SHOW CREATE DATABASE Syntax sql_safe_updates 495 If set to 1 MySQL aborts UPDATE or DELETE statements that do not use a key in the...

Страница 516: ...ed Values Type file name The path to a file with a list of trusted SSL CAs This variable was added in MySQL 5 0 23 ssl_capath 496 Version Introduced 5 0 23 Command Line Format ssl capath name Option File Format ssl capath Option Sets Variable Yes ssl_capath 496 Variable Name ssl capath Variable Scope Global Dynamic Variable No Permitted Values Type directory name The path to a directory that conta...

Страница 517: ...nd Line Format ssl key name Option File Format ssl key Option Sets Variable Yes ssl_key 497 Variable Name ssl key Variable Scope Global Dynamic Variable No Permitted Values Type string The name of the SSL key file to use for establishing a secure connection This variable was added in MySQL 5 0 23 storage_engine 497 Variable Name storage_engine Variable Scope Global Session Dynamic Variable Yes The...

Страница 518: ...e is used to initialize the time zone for each client that connects See Section 10 6 MySQL Server Time Zone Support table_cache 498 Command Line Format table_cache Option File Format table_cache Option Sets Variable Yes table_cache 498 Variable Name table_cache Variable Scope Global Dynamic Variable Yes Deprecated 5 1 3 by table_open_cache Permitted Values Type numeric Default 64 Range 1 524288 Th...

Страница 519: ... When a client disconnects the client s threads are put in the cache if there are fewer than thread_cache_size 499 threads there Requests for threads are satisfied by reusing threads taken from the cache if possible and only when the cache is empty is a new thread created This variable can be increased to improve performance if you have a lot of new connections Normally this does not provide a not...

Страница 520: ...tted Values Platform Bit Size 32 Type numeric Default 196608 Range 131072 4294967295 Block Size 1024 Permitted Values Platform Bit Size 64 Type numeric Default 262144 Range 131072 18446744073709547520 Block Size 1024 The stack size for each thread Many of the limits detected by the crash me test are dependent on this value See Section 8 1 3 The MySQL Benchmark Suite The default of 192KB 256KB for ...

Страница 521: ... is set to 1 or ON mutex timing is enabled With timing enabled the os_wait_times value in the output from SHOW ENGINE INNODB MUTEX indicates the amount of time in ms spent in operating system waits Otherwise the value is 0 This variable was added in MySQL 5 0 3 timestamp timestamp_value DEFAULT 501 Set the time for this client This is used to get the original timestamp if you use the binary log to...

Страница 522: ...his variable can be set to a list of several paths that are used in round robin fashion Paths should be separated by colon characters on Unix and semicolon characters on Windows NetWare and OS 2 The multiple directory feature can be used to spread the load between several physical disks If the MySQL server is acting as a replication slave you should not set tmpdir 502 to point to a directory on a ...

Страница 523: ...ble Yes Permitted Values Platform Bit Size 32 Type numeric Default 4096 Range 1024 4294967295 Block Size 1024 Permitted Values Platform Bit Size 64 Type numeric Default 4096 Range 1024 18446744073709547520 Block Size 1024 There is a per transaction memory pool from which various transaction related allocations take memory The initial size of the pool in bytes is transaction_prealloc_size 503 For e...

Страница 524: ...vel can also be set at startup using the transaction isolation 423 server option unique_checks 504 Variable Name unique_checks Variable Scope Session Dynamic Variable Yes Permitted Values Type boolean Default 1 If set to 1 the default uniqueness checks for secondary indexes in InnoDB tables are performed If set to 0 storage engines are permitted to assume that duplicate keys are not present in inp...

Страница 525: ...ng server build or configuration information log indicates that one or more of the general log slow query log or binary log are enabled debug indicates that the server was built with debugging support enabled Variable Name version Variable Scope Global Dynamic Variable No Starting with MySQL 5 0 24 the version number will also indicate whether the server is a standard release Community or Enterpri...

Страница 526: ...t wait_timeout 506 Command Line Format wait_timeout Option File Format wait_timeout Option Sets Variable Yes wait_timeout 506 Variable Name wait_timeout Variable Scope Global Session Dynamic Variable Yes Permitted Values Type numeric Default 28800 Range 1 31536000 Permitted Values Type windows numeric Default 28800 Range 1 2147483 The number of seconds the server waits for activity on a noninterac...

Страница 527: ...he client connects to the value of the global sql_mode 495 value System variable values can be set globally at server startup by using options on the command line or in an option file When you use a startup option to set a variable that takes a numeric value the value can be given with a suffix of K M or G either uppercase or lowercase to indicate a multiplier of 1024 1024 2 or 1024 3 that is unit...

Страница 528: ... SET GLOBAL with a variable that can only be used with SET SESSION or if you do not specify GLOBAL or global when setting a global variable To set a SESSION variable to the GLOBAL value or a GLOBAL value to the compiled in MySQL default value use the DEFAULT keyword For example the following two statements are identical in setting the session value of max_join_size 469 to the global value SET max_...

Страница 529: ...cache_size 32768 bulk_insert_buffer_size 8388608 character_set_client latin1 character_set_connection latin1 character_set_database latin1 character_set_results latin1 character_set_server latin1 character_set_system utf8 character_sets_dir usr share mysql charsets collation_connection latin1_swedish_ci collation_database latin1_swedish_ci collation_server latin1_swedish_ci innodb_additional_mem_p...

Страница 530: ...ey caches A key cache structured variable has these components key_buffer_size 458 key_cache_block_size 460 key_cache_division_limit 460 key_cache_age_threshold 459 This section describes the syntax for referring to structured variables Key cache variables are used for syntax examples but specific details about how key caches operate are found elsewhere in Section 8 6 1 The MyISAM Key Cache To ref...

Страница 531: ...extra_cache key_cache_block_size 2048 In this case the server sets the size of the default key cache to 256KB You could also have written default key_buffer_size 256K In addition the server creates a second key cache named extra_cache that has a size of 128KB with the size of block buffers for caching table index blocks set to 2048 bytes The following example starts the server with three different...

Страница 532: ..._offset 1449 numeric GLOBAL SESSION autocommit 436 boolean SESSION automatic_sp_privileges 437 boolean GLOBAL big_tables 401 boolean SESSION binlog_cache_size 440 numeric GLOBAL bulk_insert_buffer_size 441 numeric GLOBAL SESSION character_set_client 441 string GLOBAL SESSION character_set_connection 442 string GLOBAL SESSION character_set_database 442 string GLOBAL SESSION character_set_filesystem...

Страница 533: ...e_legacy_cardinality_algorithm 1252 boolean GLOBAL insert_id 457 numeric SESSION interactive_timeout 457 numeric GLOBAL SESSION join_buffer_size 457 numeric GLOBAL SESSION keep_files_on_create 458 boolean GLOBAL SESSION key_buffer_size 458 numeric GLOBAL key_cache_age_threshold 459 numeric GLOBAL key_cache_block_size 460 numeric GLOBAL key_cache_division_limit 460 numeric GLOBAL last_insert_id 462...

Страница 534: ...s_method 476 enumeration GLOBAL SESSION ndb_autoincrement_prefetch_sz 1612 numeric GLOBAL SESSION ndb_cache_check_time 1612 numeric GLOBAL ndb_force_send 1613 boolean GLOBAL SESSION ndb_use_exact_count 1615 boolean GLOBAL SESSION ndb_use_transactions 1615 boolean GLOBAL SESSION net_buffer_length 477 numeric GLOBAL SESSION net_read_timeout 478 numeric GLOBAL SESSION net_retry_count 478 numeric GLOB...

Страница 535: ...ic GLOBAL SESSION sql_auto_is_null 493 boolean SESSION sql_big_selects 493 boolean SESSION sql_big_tables 401 boolean SESSION sql_buffer_result 494 boolean SESSION sql_log_bin 494 boolean SESSION sql_log_off 494 boolean SESSION sql_log_update 494 boolean SESSION sql_low_priority_updates 465 boolean GLOBAL SESSION sql_max_join_size 469 numeric GLOBAL SESSION sql_mode 422 set GLOBAL SESSION sql_note...

Страница 536: ...ues for the current connection mysql SHOW GLOBAL STATUS Variable_name Value Aborted_clients 0 Aborted_connects 0 Bytes_received 155372598 Bytes_sent 1176560426 Connections 30023 Created_tmp_disk_tables 0 Created_tmp_files 3 Created_tmp_tables 2 Threads_created 217 Threads_running 88 Uptime 1389872 Note Before MySQL 5 0 2 SHOW STATUS returned global status values Because the default as of 5 0 2 is ...

Страница 537: ...SESSION Com_create_index 523 numeric GLOBAL SESSION Com_create_table 523 numeric GLOBAL SESSION Com_create_user 523 numeric GLOBAL SESSION Com_dealloc_sql 523 numeric GLOBAL SESSION Com_delete 523 numeric GLOBAL SESSION Com_delete_multi 523 numeric GLOBAL SESSION Com_do 523 numeric GLOBAL SESSION Com_drop_db 523 numeric GLOBAL SESSION Com_drop_event 523 numeric GLOBAL SESSION Com_drop_function 523...

Страница 538: ...23 numeric GLOBAL SESSION Com_show_binlogs 523 numeric GLOBAL SESSION Com_show_charsets 523 numeric GLOBAL SESSION Com_show_collations 523 numeric GLOBAL SESSION Com_show_column_types 523 numeric GLOBAL SESSION Com_show_create_db 523 numeric GLOBAL SESSION Com_show_create_event 523 numeric GLOBAL SESSION Com_show_create_table 523 numeric GLOBAL SESSION Com_show_databases 523 numeric GLOBAL SESSION...

Страница 539: ...pare 523 numeric GLOBAL SESSION Com_stmt_reset 523 numeric GLOBAL SESSION Com_stmt_send_long_data 523 numeric GLOBAL SESSION Com_truncate 523 numeric GLOBAL SESSION Com_unlock_tables 523 numeric GLOBAL SESSION Com_update 523 numeric GLOBAL SESSION Com_update_multi 523 numeric GLOBAL SESSION Com_xa_commit 523 numeric GLOBAL SESSION Com_xa_end 523 numeric GLOBAL SESSION Com_xa_prepare 523 numeric GL...

Страница 540: ... Innodb_buffer_pool_pages_misc 526 numeric GLOBAL Innodb_buffer_pool_pages_total 526 numeric GLOBAL Innodb_buffer_pool_read_ahead_rnd 526 numeric GLOBAL Innodb_buffer_pool_read_ahead_seq 526 numeric GLOBAL Innodb_buffer_pool_read_requests 526 numeric GLOBAL Innodb_buffer_pool_reads 527 numeric GLOBAL Innodb_buffer_pool_wait_free 527 numeric GLOBAL Innodb_buffer_pool_write_requests 527 numeric GLOB...

Страница 541: ...d 529 numeric GLOBAL Key_read_requests 529 numeric GLOBAL Key_reads 529 numeric GLOBAL Key_write_requests 529 numeric GLOBAL Key_writes 529 numeric GLOBAL Last_query_cost 529 numeric SESSION Max_used_connections 529 numeric GLOBAL Ndb_cluster_node_id 1615 numeric GLOBAL SESSION Ndb_config_from_host 1616 numeric GLOBAL SESSION Ndb_config_from_port 1616 numeric GLOBAL SESSION ndb nodeid 1610 numeric...

Страница 542: ...2 numeric GLOBAL Ssl_accepts 532 numeric GLOBAL Ssl_callback_cache_hits 532 numeric GLOBAL Ssl_cipher 532 string GLOBAL SESSION Ssl_cipher_list 532 string GLOBAL SESSION Ssl_client_connects 532 numeric GLOBAL Ssl_connect_renegotiates 532 numeric GLOBAL Ssl_ctx_verify_depth 532 numeric GLOBAL Ssl_ctx_verify_mode 532 numeric GLOBAL Ssl_default_timeout 532 numeric GLOBAL SESSION Ssl_finished_accepts ...

Страница 543: ... binary log cache but that exceeded the value of binlog_cache_size 440 and used a temporary file to store statements from the transaction Binlog_cache_use 523 The number of transactions that used the temporary binary log cache Bytes_received 523 The number of bytes received from all clients Bytes_sent 523 The number of bytes sent to all clients Com_xxx The Com_xxx statement counter variables indic...

Страница 544: ...reated by the server while executing statements If an internal temporary table is created initially as an in memory table but becomes too large MySQL automatically converts it to an on disk table The maximum size for in memory temporary tables is the minimum of the tmp_table_size 501 and max_heap_table_size 468 values If Created_tmp_disk_tables 524 is large you may want to increase the tmp_table_s...

Страница 545: ... the server is doing a lot of full index scans for example SELECT col1 FROM foo assuming that col1 is indexed Handler_read_key 525 The number of requests to read a row based on a key If this value is high it is a good indication that your tables are properly indexed for your queries Handler_read_next 525 The number of requests to read the next row in key order This value is incremented if you are ...

Страница 546: ...d pages in InnoDB buffer pool These are pages currently being read or written or that cannot be flushed or removed for some other reason Added in MySQL 5 0 2 Calculation of this variable is expensive so as of MySQL 5 0 68 it is available only when the UNIV_DEBUG system is defined at server build time Innodb_buffer_pool_pages_misc 526 The number of pages that are busy because they have been allocat...

Страница 547: ...cs 527 The current number of pending fsync operations Added in MySQL 5 0 2 Innodb_data_pending_reads 527 The current number of pending reads Added in MySQL 5 0 2 Innodb_data_pending_writes 527 The current number of pending writes Added in MySQL 5 0 2 Innodb_data_read 527 The amount of data read since the server was started Added in MySQL 5 0 2 Innodb_data_reads 527 The total number of data reads A...

Страница 548: ...m to be easily converted to bytes Added in MySQL 5 0 2 Innodb_pages_created 528 The number of pages created Added in MySQL 5 0 2 Innodb_pages_read 528 The number of pages read Added in MySQL 5 0 2 Innodb_pages_written 528 The number of pages written Added in MySQL 5 0 2 Innodb_row_lock_current_waits 528 The number of row locks currently being waited for Added in MySQL 5 0 3 Innodb_row_lock_time 52...

Страница 549: ...458 value is probably too small The cache miss rate can be calculated as Key_reads 529 Key_read_requests 529 Key_write_requests 529 The number of requests to write a key block to the cache Key_writes 529 The number of physical writes of a key block to disk Last_query_cost 529 The total cost of the last compiled query as computed by the query optimizer This is useful for comparing the cost of diffe...

Страница 550: ...stem variable This variable was added in MySQL 5 0 32 Qcache_free_blocks 530 The number of free memory blocks in the query cache Qcache_free_memory 530 The amount of free memory for the query cache Qcache_hits 530 The number of query cache hits Qcache_inserts 530 The number of queries added to the query cache Qcache_lowmem_prunes 530 The number of queries that were deleted from the query cache bec...

Страница 551: ...heck the indexes of your tables Select_scan 531 The number of joins that did a full scan of the first table Slave_open_temp_tables 531 The number of temporary tables that the slave SQL thread currently has open If the value is greater than zero it is not safe to shut down the slave see Section 16 4 1 15 Replication and Temporary Tables Slave_retried_transactions 531 The total number of times since...

Страница 552: ... of possible SSL ciphers Ssl_client_connects 532 The number of SSL connection attempts to an SSL enabled master Ssl_connect_renegotiates 532 The number of negotiates needed to establish the connection to an SSL enabled master Ssl_ctx_verify_depth 532 The SSL context verification depth how many certificates in the chain are tested Ssl_ctx_verify_mode 532 The SSL context verification mode Ssl_defaul...

Страница 553: ...times that a request for a table lock could not be granted immediately and a wait was needed If this is high and you have performance problems you should first optimize your queries and then either split your table or tables or use replication Tc_log_max_pages_used 533 For the memory mapped implementation of the log that is used by mysqld when it acts as the transaction coordinator for recovery of...

Страница 554: ...are not sleeping Uptime 534 The number of seconds that the server has been up Uptime_since_flush_status 534 The number of seconds since the most recent FLUSH STATUS statement This variable was added in 5 0 35 MySQL Community only 5 1 7 Server SQL Modes The MySQL server can operate in different SQL modes and can apply these modes differently for different clients This capability enables each applic...

Страница 555: ...ed back resulting in a partially done update Added in MySQL 5 0 2 When this manual refers to strict mode it means a mode where at least one of STRICT_TRANS_TABLES 539 or STRICT_ALL_TABLES 539 is enabled The following list describes all supported modes ALLOW_INVALID_DATES 535 Do not perform full checking of dates Check only that the month is in the range from 1 to 12 and the day is in the range fro...

Страница 556: ...1064 42000 You have an error in your SQL syntax The table name should be quoted mysql CREATE TABLE count i INT Query OK 0 rows affected 0 00 sec The IGNORE_SPACE 536 SQL mode applies to built in functions not to user defined functions or stored functions It is always permissible to have spaces after a UDF or stored function name regardless of whether IGNORE_SPACE 536 is enabled For further discuss...

Страница 557: ... unavailable for any reason whether disabled or invalid NO_FIELD_OPTIONS 537 Do not print MySQL specific column options in the output of SHOW CREATE TABLE This mode is used by mysqldump in portability mode NO_KEY_OPTIONS 537 Do not print MySQL specific index options in the output of SHOW CREATE TABLE This mode is used by mysqldump in portability mode NO_TABLE_OPTIONS 537 Do not print MySQL specifi...

Страница 558: ...ist or as of MySQL 5 0 23 HAVING list refers to nonaggregated columns that are not named in the GROUP BY clause The following queries are invalid with ONLY_FULL_GROUP_BY 538 enabled The first is invalid because address in the select list is not named in the GROUP BY clause and the second because max_age in the HAVING clause is not named in the GROUP BY clause mysql SELECT name address MAX age FROM...

Страница 559: ...ct option is enabled For STRICT_ALL_TABLES 539 MySQL returns an error and ignores the rest of the rows However in this case the earlier rows still have been inserted or updated This means that you might get a partial update which might not be what you want To avoid this it is best to use single row statements because these can be aborted without changing the table For STRICT_TRANS_TABLES 539 MySQL...

Страница 560: ...ay that it would interpret S const as was always done prior to 5 0 40 See Section 1 8 3 Running MySQL in ANSI Mode DB2 540 Equivalent to PIPES_AS_CONCAT 539 ANSI_QUOTES 535 IGNORE_SPACE 536 NO_KEY_OPTIONS 537 NO_TABLE_OPTIONS 537 NO_FIELD_OPTIONS 537 MAXDB 540 Equivalent to PIPES_AS_CONCAT 539 ANSI_QUOTES 535 IGNORE_SPACE 536 NO_KEY_OPTIONS 537 NO_TABLE_OPTIONS 537 NO_FIELD_OPTIONS 537 NO_AUTO_CRE...

Страница 561: ...You can also obtain the latest fill_help_tables sql at any time to upgrade your help tables Download the proper file for your version of MySQL from http dev mysql com doc index other html After downloading and uncompressing the file process it with mysql as described previously If you are working with Bazaar and a MySQL development source tree you will need to download the fill_help_tables sql fil...

Страница 562: ...e TCP IP port the Unix socket file the Windows named pipe and shared memory on Windows 4 The server terminates current activity For each thread associated with a client connection the server breaks the connection to the client and marks the thread as killed Threads die when they notice that they are so marked Threads for idle connections die quickly Threads that currently are processing statements...

Страница 563: ...d reopen the log files or in some cases switch to a new log file by flushing the logs Log flushing occurs when you issue a FLUSH LOGS statement execute mysqladmin with a flush logs or refresh argument or execute mysqldump with a flush logs 300 or master data 302 option See Section 13 7 6 2 FLUSH Syntax Section 4 5 2 mysqladmin Client for Administering a MySQL Server and Section 4 5 4 mysqldump A D...

Страница 564: ...qld and mysqld dies unexpectedly mysqld_safe notices that it needs to restart mysqld and writes a restarted mysqld message to the error log The log warnings 414 option or log_warnings 464 system variable can be used to control warning logging to the error log The default value is enabled 1 Warning logging can be disabled using a value of 0 If the value is greater than 1 aborted connections are wri...

Страница 565: ...d the old update log which is no longer available as of MySQL 5 0 The binary log contains all information that is available in the update log in a more efficient format and in a manner that is transaction safe If you are using transactions you must use the MySQL binary log for backups instead of the old update log The binary log is not used for statements such as SELECT or SHOW that do not modify ...

Страница 566: ...ignore db 1457 options For information about how this is done see Section 16 2 3 1 Evaluation of Database Level Replication and Binary Logging Options A replication slave server by default does not write to its own binary log any data modifications that are received from the replication master To log these modifications start the slave with the log slave updates 1451 option in addition to the log ...

Страница 567: ...e 1471 system variable default 4GB which is also the maximum can be used to restrict the total size used to cache a multiple statement transaction If a transaction is larger than this many bytes it fails and rolls back The minimum value is 4096 If you are using the binary log and row based logging concurrent inserts are converted to normal inserts for CREATE SELECT or INSERT SELECT statements This...

Страница 568: ...ot so the server prints an error message The binary log file_name is shorter than its expected size In this case this binary log is not correct and replication should be restarted from a fresh snapshot of the master s data For MySQL 5 0 46 the session values of the following system variables are written to the binary log and honored by the replication slave when parsing the binary log sql_mode 495...

Страница 569: ...rocess a slow query log file using the mysqldumpslow command to summarize the queries that appear in the log See Section 4 6 8 mysqldumpslow Summarize Slow Query Log Files 5 2 5 Server Log Maintenance As described in Section 5 2 MySQL Server Logs MySQL Server can create several different log files to help you see what activity is taking place However you must clean up these files regularly to ensu...

Страница 570: ...eate a new log file From 5 0 18 on the restriction applies only to the error log file To rename the error log file a stop and restart can be avoided by flushing the logs to cause the server to rename the current log file with the suffix old and create a new empty error log file To disable or enable general query logging for the current connection set the session sql_log_off 494 variable to ON or O...

Страница 571: ...ile_name 411 log bin file_name 1467 log error file_name 411 bdb logdir file_name 1309 For further discussion of log file options see Section 5 2 MySQL Server Logs To achieve better performance you can specify the following options differently for each server to spread the load between several physical disks tmpdir path 424 bdb tmpdir path 1310 Having different temporary directories also makes it e...

Страница 572: ...ent Permitting multiple MySQL servers to access a common data directory over NFS is a very bad idea The primary problem is that NFS is the speed bottleneck It is not meant for such use Another risk with NFS is that you must devise a way to ensure that two or more servers do not interfere with each other Usually NFS file locking is handled by the lockd daemon but at the moment there is no platform ...

Страница 573: ...the options in an option file but it is necessary to make sure that each server gets its own set of options To do this create an option file for each server and tell the server the file name with a defaults file 240 option when you run it Suppose that you want to run mysqld on port 3307 with a data directory of C mydata1 and mysqld debug on port 3308 with a data directory of C mydata2 Use this pro...

Страница 574: ...tests using 5 0 96 To install MySQL as a Windows service use the install or install manual option For information about these options see Section 2 10 4 7 Starting MySQL as a Windows Service Based on the preceding information you have several ways to set up multiple services The following instructions describe some examples Before trying any of them shut down and remove any existing MySQL services...

Страница 575: ...remove for each one specifying a service name following the remove 418 option If the service name is the default MySQL you can omit it 5 3 3 Running Multiple MySQL Instances on Unix One way is to run multiple MySQL instances on Unix is to compile different servers with different default TCP IP ports and Unix socket files so that each one listens on different network interfaces Compiling in differe...

Страница 576: ...QL_TCP_PORT 3307 shell export MYSQL_UNIX_PORT MYSQL_TCP_PORT shell mysql_install_db user mysql shell mysqld_safe datadir path to datadir This is a quick way of starting a second server to use for testing The nice thing about this method is that the environment variable settings apply to any client programs that you invoke from the same shell Thus connections for those clients are automatically dir...

Страница 577: ...tion file For example you can use C my cnf on Windows or the my cnf file in your home directory on Unix See Section 4 2 3 3 Using Option Files In a C program you can specify the socket file or port number arguments in the mysql_real_connect call You can also have the program read option files by calling mysql_options See Section 20 6 6 C API Function Descriptions If you are using the Perl DBD mysq...

Страница 578: ...558 ...

Страница 579: ...se include choosing good passwords not granting unnecessary privileges to users ensuring application security by preventing SQL injections and data corruption and others See Section 6 1 General Security Issues Security of the installation itself The data files log files and the all the application files of your installation should be protected to ensure that they are not readable or writable by un...

Страница 580: ...L root user with full privileges Review the MySQL installation instructions paying particular attention to the information about setting a root password See Section 2 18 2 Securing the Initial MySQL Accounts Use the SHOW GRANTS statement to check which accounts have access to what Then use the REVOKE statement to remove those privileges that are not necessary Do not store cleartext passwords in yo...

Страница 581: ... sections provide guidelines that enable end users and administrators to keep these passwords secure and avoid exposing them There is also a discussion of how MySQL uses password hashing internally 6 1 2 1 End User Guidelines for Password Security MySQL users should use the following guidelines to keep passwords secure When you run a client program to connect to the MySQL server it is inadvisable ...

Страница 582: ...n 4 2 3 3 Using Option Files discusses option files in more detail Store your password in the MYSQL_PWD environment variable See Section 2 21 Environment Variables This method of specifying your MySQL password must be considered extremely insecure and should not be used Some versions of ps include an option to display the environment of running processes On some systems if you set MYSQL_PWD your p...

Страница 583: ...assword but a hash value computed from it MySQL uses passwords in two phases of client server communication When a client attempts to connect to the server there is an initial authentication step in which the client must present a password that has a hash value matching the hash value stored in the user table for the account the client wants to use After the client connects it can if it has suffic...

Страница 584: ...mn in the user table was changed at this point to be 41 bytes its current length A widened Password column can store password hashes in both the pre 4 1 and 4 1 formats The format of any given hash value can be determined two ways The length 4 1 and pre 4 1 hashes are 41 and 16 bytes respectively Password hashes in the 4 1 format always begin with a character whereas passwords in the pre 4 1 forma...

Страница 585: ...t does not support authentication protocol requested by server consider upgrading MySQL client This phenomenon also occurs for attempts to use the older PHP mysql extension after upgrading to MySQL 4 1 or newer See Section 20 7 12 Common Problems with MySQL and PHP The following discussion describes the differences between the pre 4 1 and 4 1 hashing methods and what you should do if you upgrade y...

Страница 586: ...hat have long password hashes but it does prevent creation of a long password hash in the user table as the result of a password changing operation Were that permitted to occur the account could no longer be used by pre 4 1 clients With old_passwords 480 disabled the following undesirable scenario is possible An old pre 4 1 client connects to an account that has a short password hash The client ch...

Страница 587: ...n authenticate for accounts that have short or long hashes Pre 4 1 clients can authenticate only for accounts that have short hashes For connected clients password hash generating operations involving the PASSWORD 956 function or password generating statements use short hashes exclusively Any change to an account s password results in that account having a short password hash In this scenario newl...

Страница 588: ...se accounts with long hashes to revert to short hashes unless you take care to change the session value of old_passwords 480 to 0 first In scenario 3 accounts with short hashes become inaccessible to pre 4 1 clients if you change their passwords without explicitly using OLD_PASSWORD 956 The best way to avoid compatibility problems related to short password hashes is to not use them Upgrade all cli...

Страница 589: ...any user name to the client program For example anyone can use the mysql program to connect as any other person simply by invoking it as mysql u other_user db_name if other_user has no password If all accounts have a password connecting using another user s account becomes much more difficult For a discussion of methods for setting passwords see Section 6 3 5 Assigning Account Passwords Make sure ...

Страница 590: ...on This is especially important if you run mysqld as root because anyone that has write access to the server s data directory then could delete any file in the system See Section 8 9 6 2 Using Symbolic Links for MyISAM Tables on Unix Stored programs and views should be written using the security guidelines discussed in Section 18 5 Access Control for Stored Programs and Views If you do not trust y...

Страница 591: ... and run by any user However you should avoid running the server as the Unix root user for security reasons To change mysqld to run as a normal unprivileged Unix user user_name you must do the following 1 Stop the server if it is running use mysqladmin shutdown 2 Change the database directories and files so that user_name has privileges to read and write files in them you might need to do this as ...

Страница 592: ...ss has read access to assuming that a user could run any command against the SQL server In this environment the client with respect to the MySQL server actually is the Web server not the remote program being run by the user who connects to the Web server To deal with these problems we changed how LOAD DATA LOCAL is handled as of MySQL 3 23 49 and MySQL 4 0 2 4 0 13 on Windows By default all MySQL ...

Страница 593: ...timate users Checklist Enable strict SQL mode to tell the server to be more restrictive of what data values it accepts See Section 5 1 7 Server SQL Modes Try to enter single and double quotation marks and in all of your Web forms If you get any kind of MySQL error investigate the problem right away Try to modify dynamic URLs by adding 22 23 and 27 to them Try to modify data types in dynamic URLs f...

Страница 594: ...ay perform only the operations permitted to them As a user when you connect to a MySQL server your identity is determined by the host from which you connect and the user name you specify When you issue requests after connecting the system grants privileges according to your identity and what you want to do MySQL considers both your host name and user name in identifying you because there is no rea...

Страница 595: ..._priv tables in the mysql database see Section 6 2 2 Privilege System Grant Tables The MySQL server reads the contents of these tables into memory when it starts and reloads them under the circumstances indicated in Section 6 2 6 When Privilege Changes Take Effect Access control decisions are based on the in memory copies of the grant tables Some releases of MySQL introduce changes to the structur...

Страница 596: ...l table level privileges The ALTER 576 privilege enables use of ALTER TABLE to change the structure of tables ALTER TABLE also requires the CREATE 576 and INSERT 577 privileges Renaming a table requires ALTER 576 and DROP 577 on the old table ALTER 576 CREATE 576 and INSERT 577 on the new table The ALTER ROUTINE 576 privilege is needed to alter or drop stored routines procedures and functions This...

Страница 597: ...sting tables If you have the CREATE 576 privilege for a table you can include index definitions in the CREATE TABLE statement The INSERT 577 privilege enables rows to be inserted into tables in a database INSERT 577 is also required for the ANALYZE TABLE OPTIMIZE TABLE and REPAIR TABLE table maintenance statements The LOCK TABLES 577 privilege enables the use of explicit LOCK TABLES statements to ...

Страница 598: ...r disabling logging performing updates even if the read_only 488 system variable is enabled starting and stopping replication on slave servers specification of any account in the DEFINER attribute of stored programs and views and enables you to connect once even if the connection limit controlled by the max_connections 467 system variable is reached To create or alter stored routines if binary log...

Страница 599: ...formation about user defined functions See Section 21 2 Adding New Functions to MySQL help_xxx These tables are used for server side help See Section 5 1 8 Server Side Help proc Contains information about stored procedures and functions See Section 18 2 Using Stored Routines Procedures and Functions time_zone_xxx These tables contain time zone information See Section 10 6 MySQL Server Time Zone Su...

Страница 600: ...tage 2 Request Verification Note The host table must be modified directly with statements such as INSERT UPDATE and DELETE It is not affected by statements such as GRANT and REVOKE that modify the grant tables indirectly Most MySQL installations need not use this table at all The tables_priv and columns_priv tables are similar to the db table but are more fine grained They apply at the table and c...

Страница 601: ... 5 0 0 but did not become operational until MySQL 5 0 3 The Create_view_priv and Show_view_priv columns were added in MySQL 5 0 1 The Create_routine_priv Alter_routine_priv and max_user_connections 472 columns were added in MySQL 5 0 3 During the second stage of access control the server performs request verification to make sure that each client has sufficient privileges for each request that it ...

Страница 602: ...ySQL 5 0 6 It is an ENUM column with values of FUNCTION or PROCEDURE to indicate the type of routine the row refers to This column enables privileges to be granted separately for a function and a procedure with the same name The Timestamp and Grantor columns are set to the current timestamp and the CURRENT_USER 959 value respectively However they are unused and are discussed no further here Scope ...

Страница 603: ... or write files on the server host is independent of the database you are accessing The mysqld server reads the contents of the grant tables into memory when it starts You can tell it to reload the tables by issuing a FLUSH PRIVILEGES statement or executing a mysqladmin flush privileges or mysqladmin reload command Changes to the grant tables take effect as indicated in Section 6 2 6 When Privileg...

Страница 604: ...atches any user name An account with a blank user name is an anonymous user To specify an anonymous user in SQL statements use a quoted empty user name part such as localhost The host name part of an account name can take many forms and wildcards are permitted A host value can be a host name or an IP address The name localhost indicates the local host The IP address 127 0 0 1 indicates the loopbac...

Страница 605: ...nt host pattern like 192 168 1 but not 192 168 01 To avoid problems like this it is advisable to check the format in which your DNS returns host names and addresses and use values in the same format in MySQL account names 6 2 4 Access Control Stage 1 Connection Verification When you attempt to connect to a MySQL server the server accepts or rejects the connection based on your identity and whether...

Страница 606: ...77 fred fred connecting from the host with IP address 144 155 166 177 144 155 166 fred fred connecting from any host in the 144 155 166 class C subnet 144 155 166 0 255 255 255 0 fred Same as previous example It is possible for the client host name and user name of an incoming connection to match more than one row in the user table The preceding set of examples demonstrates this Several of the ent...

Страница 607: ...re used first when the server attempts to find a match for the connection This is not true The preceding example illustrates this where a connection from thomas loc gov by jeffrey is first matched not by the row containing jeffrey as the User column value but by the row with no user name As a result jeffrey is authenticated as an anonymous user even though he specified a user name when connecting ...

Страница 608: ...rivileges you must escape it with a backslash For example to include the underscore character _ as part of a database name specify it as _ in the GRANT statement A Host value in the db table means any host A blank Host value in the db table means consult the host table for further information a process that is described later in this section A or blank Host value in the host table means any host A...

Страница 609: ...s the server adds them to the global privileges granted by the user table If the result permits the requested operation access is granted Otherwise the server successively checks the user s table and column privileges in the tables_priv and columns_priv tables adds those to the user s privileges and permits or denies access based on the result For stored routine operations the server uses the proc...

Страница 610: ...cations may cache the database name thus this effect may not be visible to them without actually changing to a different database or flushing the privileges Global privileges and passwords are unaffected for a connected client These changes take effect only for subsequent connections If the server is started with the skip grant tables 420 option it does not read the grant tables or implement any a...

Страница 611: ...erver test the initial privileges by executing this command shell mysql u root test The server should let you connect without error After a fresh installation you should connect to the server and set up your users and their access permissions shell mysql u root mysql The server should let you connect because the MySQL root user has no password initially That is also a security risk so setting the ...

Страница 612: ...t the password See Section 6 3 5 Assigning Account Passwords and Section 13 7 1 1 CREATE USER Syntax localhost is a synonym for your local host name and is also the default host to which clients try to connect if you specify no host explicitly To avoid this problem on such systems you can use a host 127 0 0 1 231 option to name the server host explicitly This will make a TCP IP connection to the l...

Страница 613: ...the user table with a User column value of root and that mysqld cannot resolve the host name for your client Access denied for user unknown These errors indicate a DNS problem To fix it execute mysqladmin flush hosts to reset the internal DNS host cache See Section 8 9 8 DNS Lookup Optimization and the Host Cache Some permanent solutions are Determine what is wrong with your DNS server and fix it ...

Страница 614: ...cause the server to reload the privilege tables Otherwise your changes have no effect until the next time the server is restarted Remember that after you change the root password with an UPDATE statement you will not need to specify the new password until after you flush the privileges because the server will not know you ve changed the password yet If your privileges seem to have changed in the m...

Страница 615: ...rmation about account representation in the user table see Section 6 2 2 Privilege System Grant Tables There are several distinctions between the way user names and passwords are used by MySQL and the way they are used by your operating system User names as used by MySQL for authentication purposes have nothing to do with user names login names as used by Windows or Unix On Unix most MySQL clients...

Страница 616: ...CHARSET_NAME option and appropriate character set name as arguments This causes authentication to take place using the specified character set Otherwise authentication will fail unless the server default character set is the same as the encoding in the authentication defaults Standard MySQL client programs support a default character set option that causes mysql_options to be called as just descri...

Страница 617: ...m accepting some of the statements Workarounds are indicated for these cases For more information about SQL modes and their effect on grant table manipulation see Section 5 1 7 Server SQL Modes and Section 13 7 1 3 GRANT Syntax First use the mysql program to connect to the server as the MySQL root user shell mysql user root mysql If you have assigned a password to the root account you will also ne...

Страница 618: ...er to reload the grant tables using FLUSH PRIVILEGES shell mysql user root mysql mysql INSERT INTO user VALUES localhost monty PASSWORD some_pass Y Y Y Y Y Y Y Y Y Y Y Y Y Y mysql INSERT INTO user VALUES monty PASSWORD some_pass Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y 0 0 0 0 mysql INSERT INTO user SET Host localhost User admin Reload_priv Y Process_priv Y mysql INSERT INTO user Host U...

Страница 619: ...ify the grant tables directly shell mysql user root mysql mysql INSERT INTO user Host User Password VALUES localhost custom PASSWORD obscure mysql INSERT INTO user Host User Password VALUES host47 example com custom PASSWORD obscure mysql INSERT INTO user Host User Password VALUES server domain custom PASSWORD obscure mysql INSERT INTO db Host Db User Select_priv Insert_priv Update_priv Delete_pri...

Страница 620: ...t against the update limit An account in this context corresponds to a row in the mysql user table That is a connection is assessed against the User and Host values in the user table row that applies to the connection For example an account usera example com corresponds to a row in the user table that has User and Host values of usera and example com to permit usera to connect from any host in the...

Страница 621: ...3 have connection limits of 5 and 20 respectively because they have nonzero MAX_USER_CONNECTIONS limits The server stores resource limits for an account in the user table row corresponding to the account The max_questions max_updates and max_connections columns store the per hour limits and the max_user_connections column stores the MAX_USER_CONNECTIONS limit See Section 6 2 2 Privilege System Gra...

Страница 622: ...d as an anonymous user you can change your own password by omitting the FOR clause mysql SET PASSWORD PASSWORD mypass The old_passwords 480 system variable value determines the hashing method used by PASSWORD 956 If you specify the password using that function and SET PASSWORD rejects the password as not being in the correct format it may be necessary to set old_passwords 480 to change the hashing...

Страница 623: ...e the server to reread the grant tables Otherwise the change remains unnoticed by the server until you restart it To establish a password for a new account provide a value for the Password column mysql INSERT INTO mysql user Host User Password VALUES localhost jeffrey PASSWORD mypass mysql FLUSH PRIVILEGES To change the password for an existing account use UPDATE to set the Password column value m...

Страница 624: ...ns electronic certificates to anyone who needs them Certificates rely on asymmetric encryption algorithms that have two encryption keys a public key and a secret key A certificate owner can show the certificate to another party as proof of identity A certificate consists of its owner s public key Any data encrypted with this public key can be decrypted only using the corresponding secret key which...

Страница 625: ...h SSL support as described in Section 6 3 6 2 Configuring MySQL for SSL In addition the proper SSL related options must be used to specify the appropriate certificate and key files For a complete list of SSL options see Section 6 3 6 4 SSL Command Options To start the MySQL server so that it permits clients to connect using SSL use the options that identify the certificate and key files the server...

Страница 626: ...rwise For example mysql SHOW STATUS LIKE Ssl_cipher Variable_name Value Ssl_cipher DHE RSA AES256 SHA For the mysql client an alternative is to use the STATUS or s command and check the SSL line mysql s SSL Not in use Or mysql s SSL Cipher in use is DHE RSA AES256 SHA The C API enables application programs to use SSL To establish a secure connection program use the mysql_ssl_set C API function to ...

Страница 627: ...in the descriptions for those options For this reason ssl 607 is not usually specified explicitly It is more often used explicitly in its opposite form to override other SSL options and indicate that SSL should not be used To do this specify the option as skip ssl 607 or ssl 0 607 For example you might have SSL options specified in the client group of your option file to use SSL connections by def...

Страница 628: ...ficate tree yaSSL requires that all components of the CA certificate tree be contained within a single CA certificate tree and that each certificate in the file has a unique SubjectName value To work around this yaSSL limitation concatenate the individual certificate files comprising the certificate tree into a new file Then specify the new file as the value of the ssl capath 608 option ssl cert f...

Страница 629: ...de nonempty responses Create clean environment shell rm rf newcerts shell mkdir newcerts cd newcerts Create CA certificate shell openssl genrsa 2048 ca key pem shell openssl req new x509 nodes days 3600 key ca key pem out ca cert pem Create server certificate remove passphrase and sign it server cert pem public key server key pem private key shell openssl req newkey rsa 2048 days 3600 nodes keyout...

Страница 630: ...phrase Verifying password Enter PEM pass phrase You are about to be asked to enter information that will be incorporated into your certificate request What you are about to enter is what is called a Distinguished Name or a DN There are quite a few fields but you can leave some blank For some fields there will be a default value If you enter the field will be left blank Country Name 2 letter code A...

Страница 631: ... the request matches the signature Signature ok The Subjects Distinguished Name is as follows countryName PRINTABLE FI organizationName PRINTABLE MySQL AB commonName PRINTABLE MySQL admin Certificate is to be certified until Sep 13 14 22 46 2003 GMT 365 days Sign the certificate y n y 1 out of 1 certificate requests certified commit y n y Write out database with 1 new entries Data Base Updated Cre...

Страница 632: ...QL AB commonName PRINTABLE MySQL user Certificate is to be certified until Sep 13 16 45 17 2003 GMT 365 days Sign the certificate y n y 1 out of 1 certificate requests certified commit y n y Write out database with 1 new entries Data Base Updated Create a my cnf file that you can use to test the certificates cat EOF DIR my cnf client ssl ca DIR ca cert pem ssl cert DIR client cert pem ssl key DIR ...

Страница 633: ...onment Variables button 3 Under System Variables select Path then click the Edit button The Edit System Variable dialogue should appear 4 Add C OpenSSL Win32 bin to the end notice the semicolon 5 Press OK 3 times 6 Check that OpenSSL was correctly integrated into the Path variable by opening a new command console Start Run cmd exe and verifying that OpenSSL is available Microsoft Windows Version C...

Страница 634: ... the following guidelines to perform SQL based auditing that ties database activity to MySQL accounts MySQL accounts correspond to rows in the mysql user table When a client connects successfully the server authenticates the client to a particular row in this table The User and Host column values in this row uniquely identify the account and correspond to the user_name host_name format in which ac...

Страница 635: ...ENT_USER USER CURRENT_USER user2 remote example com user2 example com If an application must invoke USER 964 for user auditing for example if it does auditing from within triggers but must also be able to associate the USER 964 value with an account in the user table it is necessary to avoid accounts that contain wildcards in the User or Host column Specifically do not permit User to be empty whic...

Страница 636: ...616 ...

Страница 637: ... in case problems occur such as system crashes hardware failures or users deleting data by mistake Backups are also essential as a safeguard before upgrading a MySQL installation and they can be used to transfer a MySQL installation to another system or to set up replication slave servers MySQL offers a variety of backup strategies from which you can choose the methods that best suit the requireme...

Страница 638: ...arger than for physical backup particularly when saved in text format Backup and restore granularity is available at the server level all databases database level all tables in a particular database or table level This is true regardless of storage engine The backup does not include log or configuration files or other database related files that are not part of databases Backups stored in logical ...

Страница 639: ...ions do not take place that would compromise backup integrity Offline backup methods have these characteristics Clients can be affected adversely because the server is unavailable during backup The backup procedure is simpler because there is no possibility of interference from client activity A similar distinction between online and offline applies for recovery operations and similar characterist...

Страница 640: ...a given time Point in time recovery is based on the binary log and typically follows a full recovery from the backup files that restores the server to its state when the backup was made Then the data changes written in the binary log files are applied as incremental recovery to redo data modifications and bring the server up to the desired point in time Table Maintenance Data integrity can be comp...

Страница 641: ...p with the tab 305 option See Section 7 4 3 Dumping Data in Delimited Text Format with mysqldump To reload a delimited text data file use LOAD DATA INFILE or mysqlimport Making Incremental Backups by Enabling the Binary Log MySQL supports incremental backups You must start the server with the log bin 1467 option to enable binary logging see Section 5 2 3 The Binary Log The binary log files provide...

Страница 642: ...d so forth The example commands do not include options such as user 232 and password 231 for the mysqldump and mysql client programs You should include such options as necessary to enable client programs to connect to the MySQL server Assume that data is stored in the InnoDB storage engine which has support for transactions and automatic crash recovery Assume also that the MySQL server is under lo...

Страница 643: ...SERT statements that can be used to reload the dumped tables at a later time This backup operation acquires a global read lock on all tables at the beginning of the dump using FLUSH TABLES WITH READ LOCK As soon as this lock has been acquired the binary log coordinates are read and the lock is released If long updating statements are running when the FLUSH statement is issued the backup operation ...

Страница 644: ...cause the flush logs 300 option causes the server to flush its logs The master data 302 option causes mysqldump to write binary log information to its output so the resulting sql dump file includes these lines Position to start replication or point in time recovery from CHANGE MASTER TO MASTER_LOG_FILE gbichot2 bin 000007 MASTER_LOG_POS 4 Because the mysqldump command made a full backup those line...

Страница 645: ...ata directory resides That way the logs are safe even if the device containing the directory is lost If we had done this we would have the gbichot2 bin 000009 file and any subsequent files at hand and we could apply them using mysqlbinlog and mysql to restore the most recent data changes with no loss up to the moment of the crash shell mysqlbinlog gbichot2 bin 000009 mysql For more information abo...

Страница 646: ... file shell mysqldump arguments file_name To dump all databases invoke mysqldump with the all databases 298 option shell mysqldump all databases dump sql To dump only specific databases name them on the command line and use the databases 299 option shell mysqldump databases db1 db2 db3 dump sql The databases 299 option causes all names on the command line to be treated as database names Without th...

Страница 647: ... db1 dump sql Alternatively from within mysql create the database select it as the default database and load the dump file mysql CREATE DATABASE IF NOT EXISTS db1 mysql USE db1 mysql source dump sql 7 4 3 Dumping Data in Delimited Text Format with mysqldump This section describes how to use mysqldump to create delimited text dump files For information about reloading such dump files see Section 7 ...

Страница 648: ...r escape the value appropriately for your command interpreter Alternatively specify the value using hex notation Suppose that you want mysqldump to quote column values within double quotation marks To do so specify double quote as the value for the fields enclosed by 300 option But this character is often special to command interpreters and must be treated specially For example on Unix you can quo...

Страница 649: ... stored programs stored procedures and functions and triggers How to dump definitions and data separately 7 4 5 1 Making a Copy of a Database shell mysqldump db1 dump sql shell mysqladmin create db2 shell mysql db2 dump sql Do not use databases 299 on the mysqldump command line because that causes USE db1 to be included in the dump file which overrides the effect of naming db2 on the mysql command...

Страница 650: ...so that the dump file contains only table data For example to dump table definitions and data separately for the test database use these commands shell mysqldump no data test dump defs sql shell mysqldump no create info test dump data sql For a definition only dump add the routines 304 option to also include stored routine definitions shell mysqldump no data routines test dump defs sql 7 4 5 5 Usi...

Страница 651: ...rent location Section 5 2 3 The Binary Log To see a listing of all binary log files use this statement mysql SHOW BINARY LOGS To determine the name of the current binary log file issue the following statement mysql SHOW MASTER STATUS The mysqlbinlog utility converts the events in the binary log files from binary format to text so that they can be executed or viewed mysqlbinlog has options for sele...

Страница 652: ...he table and data you could restore the previous night s backup and then execute the following command shell mysqlbinlog stop datetime 2005 04 20 9 59 59 var log mysql bin 123456 mysql u root p This command recovers all of the data up until the date and time given by the stop datetime 347 option If you did not detect the erroneous SQL statement that was entered until hours later you will probably ...

Страница 653: ...SQL logs will reflect the original times at which the transactions were executed 7 6 MyISAM Table Maintenance and Crash Recovery This section discusses how to use myisamchk to check or repair MyISAM tables tables that have MYD and MYI files for storing data and indexes For general myisamchk background see Section 4 6 3 myisamchk MyISAM Table Maintenance Utility Other table repair information can b...

Страница 654: ...ladmin flush tables before you run myisamchk Your tables may become corrupted if the server and myisamchk access the tables simultaneously When performing crash recovery it is important to understand that each MyISAM table tbl_name in a database corresponds to the three files in the database directory shown in the following table File Purpose tbl_name frm Definition format file tbl_name MYD Data f...

Страница 655: ... MyISAM tables See Section 13 7 2 3 CHECK TABLE Syntax and Section 13 7 2 6 REPAIR TABLE Syntax Symptoms of corrupted tables include queries that abort unexpectedly and observable errors such as these tbl_name frm is locked against change Can t find file tbl_name MYI Errcode nnn Unexpected end of file Record file is crashed Got error nnn from table handler To get more information about the error r...

Страница 656: ... to disk Stage 1 Checking your tables Run myisamchk MYI or myisamchk e MYI if you have more time Use the s silent option to suppress unnecessary information If the mysqld server is stopped you should use the update state 323 option to tell myisamchk to mark the table as checked You have to repair only those tables for which myisamchk announces an error For such tables proceed to Stage 2 If you get...

Страница 657: ...ver happen because the description file is not changed after the table is created 1 Restore the description file from a backup and go back to Stage 3 You can also restore the index file and go back to Stage 2 In the latter case you should start with myisamchk r 2 If you do not have a backup but know exactly how the table was created create a copy of the table in another database Remove the new dat...

Страница 658: ...ck each table that could have been affected before it is used further These are expected crashed tables To cause the server to check MyISAM tables automatically start it with the myisam recover 415 option See Section 5 1 3 Server Command Options You should also check your tables regularly during normal system operation For example you can run a cron job to check important tables once a week using ...

Страница 659: ...L Query Cache 703 8 7 Locking Issues 709 8 7 1 Internal Locking Methods 709 8 7 2 Table Locking Issues 711 8 7 3 Concurrent Inserts 712 8 7 4 External Locking 713 8 8 Optimizing Database Structure 714 8 8 1 Make Your Data as Small as Possible 714 8 8 2 Using PROCEDURE ANALYSE 715 8 8 3 How MySQL Opens and Closes Tables 716 8 8 4 Disadvantages of Creating Many Tables in the Same Database 717 8 8 5 ...

Страница 660: ...y bandwidth becomes a bottleneck This is an uncommon bottleneck for most systems but one to be aware of 8 1 1 MySQL Design Limitations and Tradeoffs When using the MyISAM storage engine MySQL uses extremely fast table locking that permits multiple readers or a single writer The biggest problem with this storage engine occurs when you have a steady stream of mixed updates and slow selects on a sing...

Страница 661: ... define an easily extendable interface through which you manipulate your data For example C is available on most systems so it makes sense to use a C class based interface to the databases If you use some feature that is specific to a given database system such as the REPLACE statement which is specific to MySQL you should implement the same feature for other SQL servers by coding an alternative m...

Страница 662: ... and limitations are by actually running queries For example it determines What data types are supported How many indexes are supported What functions are supported How big a query can be How big a VARCHAR column can be For more information about benchmark results visit http www mysql com why mysql benchmarks 8 1 4 Using Your Own Benchmarks You should definitely benchmark your application and data...

Страница 663: ...d indexes to tables so that the statement executes faster by using indexes to find rows You can also use EXPLAIN to check whether the optimizer joins the tables in an optimal order To give a hint to the optimizer to use a join order corresponding to the order in which the tables are named in a SELECT statement begin the statement with SELECT STRAIGHT_JOIN rather than just SELECT See Section 13 2 8...

Страница 664: ...can be NULL if the row refers to the union result of other rows In this case the table column shows a value like unionM N to indicate that the row refers to the union of the rows with id values of M and N select_type The type of SELECT which can be any of those shown in the following table select_type Value Meaning SIMPLE Simple SELECT not using UNION or subqueries PRIMARY Outermost SELECT UNION S...

Страница 665: ...appropriate index and check the query with EXPLAIN again See Section 13 1 4 ALTER TABLE Syntax To see what indexes a table has use SHOW INDEX FROM tbl_name key The key column indicates the key index that MySQL actually decided to use If MySQL decides to use one of the possible_keys indexes to look up rows that index is listed as the key value It is possible that key will name an index that is not ...

Страница 666: ...he following queries tbl_name can be used as a const 646 table SELECT FROM tbl_name WHERE primary_key 1 SELECT FROM tbl_name WHERE primary_key_part1 1 AND primary_key_part2 2 eq_ref 646 One row is read from this table for each combination of rows from the previous tables Other than the system 646 and const 646 types this is the best possible join type It is used when all parts of an index are used...

Страница 667: ...umn in the output row contains a list of indexes used and key_len contains a list of the longest key parts for the indexes used For more information see Section 8 3 1 4 Index Merge Optimization unique_subquery 647 This type replaces ref 646 for some IN subqueries of the following form value IN SELECT primary_key FROM single_table WHERE some_expr unique_subquery 647 is just an index lookup function...

Страница 668: ...er cases Normally you can avoid ALL by adding indexes that enable row retrieval from the table based on constant values or column values from earlier tables EXPLAIN Extra Information The Extra column of EXPLAIN output contains additional information about how MySQL resolves the query The following list explains the values that can appear in this column If you want to make your queries as fast as p...

Страница 669: ... in the preceding tables MySQL checks whether it is possible to use a range 647 or index_merge 647 access method to retrieve rows This is not very fast but is faster than performing a join with no index at all The applicability criteria are as described in Section 8 3 1 3 Range Optimization and Section 8 3 1 4 Index Merge Optimization with the exception that all column values for the preceding tab...

Страница 670: ...end to the client Unless you specifically intend to fetch or examine all rows from the table you may have something wrong in your query if the Extra value is not Using where and the table join type is ALL or index 648 Even if you are using an index for all parts of a WHERE clause you may see Using where if the column can be NULL Using where with pushed condition This item applies to NDBCLUSTER tab...

Страница 671: ...formation table type possible_keys key key_len ref rows Extra et ALL PRIMARY NULL NULL NULL 74 do ALL PRIMARY NULL NULL NULL 2135 et_1 ALL PRIMARY NULL NULL NULL 74 tt ALL AssignedPC NULL NULL NULL 3872 ClientID ActualPC Range checked for each record index map 0x23 Because type is ALL for each table this output indicates that MySQL is generating a Cartesian product of all the tables that is every ...

Страница 672: ...the case for the tt table Fortunately it is easy to tell MySQL to analyze the key distribution mysql ANALYZE TABLE tt With the additional index information the join is perfect and EXPLAIN produces this result table type possible_keys key key_len ref rows Extra tt ALL AssignedPC NULL NULL NULL 3872 Using ClientID where ActualPC et eq_ref PRIMARY PRIMARY 15 tt ActualPC 1 et_1 eq_ref PRIMARY PRIMARY ...

Страница 673: ...t t1 1 row in set 0 00 sec Because the statement displayed by SHOW WARNINGS may contain special markers to provide information about query rewriting or optimizer actions the statement is not necessarily valid SQL and is not intended to be executed The output may also include rows with Message values that provide additional non SQL explanatory notes about actions taken by the optimizer The followin...

Страница 674: ...thing is cached by the OS or the MySQL server things become only marginally slower as the table gets bigger After the data gets too big to be cached things start to go much slower until your applications are bound only by disk seeks which increase by log N To avoid this increase the key cache size as the data grows For MyISAM tables the key cache size is controlled by the key_buffer_size 458 syste...

Страница 675: ...ity value myisamchk description verbose shows index distribution information To sort an index and data according to an index use myisamchk sort index sort records 1 assuming that you want to sort on index 1 This is a good way to make queries faster if you have a unique index from which you want to read all rows in order according to the index The first time you sort a large table this way it may t...

Страница 676: ...porary table Each table index is queried and the best index is used unless the optimizer believes that it is more efficient to use a table scan At one time a scan was used based on whether the best index spanned more than 30 of the table but a fixed percentage no longer determines the choice between using an index or a scan The optimizer now is more complex and bases its estimate on additional fac...

Страница 677: ...nge condition when using the 876 876 876 876 BETWEEN 877 876 or 876 operators or LIKE 896 comparisons if the argument to LIKE 896 is a constant string that does not start with a wildcard character For all types of indexes multiple range conditions combined with OR 881 or AND 880 form a range condition Constant value in the preceding descriptions means one of the following A constant from the query...

Страница 678: ...l condition to be used for the range scan key1 bar In general and as demonstrated by the preceding example the condition used for a range scan is less restrictive than the WHERE clause MySQL performs an additional check to filter out rows that satisfy the range condition but not the full WHERE clause The range condition extraction algorithm can handle nested AND 880 OR 881 constructs of arbitrary ...

Страница 679: ...a BTREE index an interval might be usable for conditions combined with AND 880 where each condition compares a key part with a constant value using 875 876 IS NULL 877 876 876 876 876 876 876 BETWEEN 877 or LIKE pattern 896 where pattern does not start with a wildcard An interval can be used as long as it is possible to determine a single key tuple containing all rows that match the condition or t...

Страница 680: ... index Analogous steps are performed for range conditions on multiple part indexes 8 3 1 4 Index Merge Optimization The Index Merge method is used to retrieve rows with several range 647 scans and to merge their results into one The merge can produce unions intersections or unions of intersections of its underlying scans This access method merges index scans from a single table it does not merge s...

Страница 681: ...nd plan The choice between different possible variants of the Index Merge access method and other access methods is based on cost estimates of various available options 8 3 1 4 1 The Index Merge Intersection Access Algorithm This access algorithm can be employed when a WHERE clause was converted to several range conditions on different keys combined with AND 880 and each condition is one of the fo...

Страница 682: ...ion Access Algorithm This access algorithm is employed when the WHERE clause was converted to several range conditions combined by OR 881 but for which the Index Merge method union algorithm is not applicable Examples SELECT FROM tbl_name WHERE key_col1 10 OR key_col2 20 SELECT FROM tbl_name WHERE key_col1 10 OR key_col2 20 AND nonkey_col 30 The difference between the sort union algorithm and the ...

Страница 683: ... clause Condition pushdown may also be employed when an indexed column is compared with a constant using a or operator mysql EXPLAIN SELECT a b FROM t1 WHERE a 2 G 1 row id 1 select_type SIMPLE table t1 type range possible_keys a key a key_len 5 ref NULL rows 2 Extra Using where with pushed condition Other supported comparisons for condition pushdown include the following column NOT LIKE pattern p...

Страница 684: ... MySQL can use indexes and ranges to search for NULL with IS NULL 877 Examples SELECT FROM tbl_name WHERE key_col IS NULL SELECT FROM tbl_name WHERE key_col NULL SELECT FROM tbl_name WHERE key_col const1 OR key_col const2 OR key_col IS NULL If a WHERE clause includes a col_name IS NULL 877 condition for a column that is declared as NOT NULL that expression is optimized away This optimization does ...

Страница 685: ...with all columns set to NULL If you use LEFT JOIN to find rows that do not exist in some table and you have the following test col_name IS NULL in the WHERE part where col_name is a column that is declared as NOT NULL MySQL stops searching for more rows for a particular key combination after it has found one row that matches the LEFT JOIN condition The implementation of RIGHT JOIN is analogous to ...

Страница 686: ...ne at a time from outer loops to inner loops it typically reads tables processed in the inner loops many times Block Nested Loop Join Algorithm A Block Nested Loop BNL Join algorithm uses buffering of rows read in outer loops to reduce the number of times that tables in inner loops must be read For example if 10 rows are read into a buffer and the buffer is passed to the next inner loop each row r...

Страница 687: ...s of MySQL 5 0 1 the syntax for expressing joins permits nested joins The following discussion refers to the join syntax described in Section 13 2 8 2 JOIN Syntax The syntax of table_factor is extended in comparison with the SQL Standard The latter accepts only table_reference not a list of them inside a pair of parentheses This is a conservative extension if we consider each comma in a list of ta...

Страница 688: ...LL 101 mysql SELECT FROM t1 LEFT JOIN t2 LEFT JOIN t3 ON t2 b t3 b OR t2 b IS NULL ON t1 a t2 a a a b b 1 1 101 101 2 NULL NULL NULL mysql SELECT FROM t1 LEFT JOIN t2 ON t1 a t2 a LEFT JOIN t3 ON t2 b t3 b OR t2 b IS NULL a a b b 1 1 101 101 2 NULL NULL 101 In the following example an outer join operation is used together with an inner join operation t1 LEFT JOIN t2 t3 ON t1 a t2 a That expression...

Страница 689: ...e second query it is formed with an inner join operation In the first query the parentheses can be omitted The grammatical structure of the join expression will dictate the same order of execution for join operations For the second query the parentheses cannot be omitted although the join expression here can be interpreted unambiguously without them In our extended syntax the parentheses in t2 t3 ...

Страница 690: ...the nested loop pattern to get FOR each row t1 in T1 BOOL f1 FALSE FOR each row t2 in T2 such that P1 t1 t2 BOOL f2 FALSE FOR each row t3 in T3 such that P2 t2 t3 IF P t1 t2 t3 t t1 t2 t3 OUTPUT t f2 TRUE f1 TRUE IF f2 IF P t1 t2 NULL t t1 t2 NULL OUTPUT t f1 TRUE IF f1 IF P t1 NULL NULL t t1 NULL NULL OUTPUT t In general for any nested loop for the first inner table in an outer join operation a f...

Страница 691: ...1 t1 t2 FOR each row t3 in T3 such that P2 t1 t3 IF P t1 t2 t3 t t1 t2 t3 OUTPUT t f1 TRUE IF f1 IF P t1 NULL NULL t t1 NULL NULL OUTPUT t and FOR each row t1 in T1 BOOL f1 FALSE FOR each row t3 in T3 such that P2 t1 t3 FOR each row t2 in T2 such that P1 t1 t2 IF P t1 t2 t3 t t1 t2 t3 OUTPUT t f1 TRUE IF f1 IF P t1 NULL NULL t t1 NULL NULL OUTPUT t In both nestings T1 must be processed in the oute...

Страница 692: ...uarded by the flags that are turned on when a match has been encountered For our example with outer joins with P T1 T2 T3 C1 T1 AND C T2 AND C3 T3 the nested loop schema using guarded pushed down conditions looks like this FOR each row t1 in T1 such that C1 t1 BOOL f1 FALSE FOR each row t2 in T2 such that P1 t1 t2 AND f1 C2 t2 TRUE BOOL f2 FALSE FOR each row t3 in T3 such that P2 t2 t3 AND f1 f2 C...

Страница 693: ...sides to access table T1 before table T2 that may lead to a very inefficient execution plan Fortunately MySQL converts such a query into a query without an outer join operation if the WHERE condition is null rejected A condition is called null rejected for an outer join operation if it evaluates to FALSE or to UNKNOWN for any NULL complemented row built for the operation Thus for this outer join T...

Страница 694: ...which is equivalent to the query SELECT FROM T1 LEFT JOIN T2 ON T2 A T1 A T3 WHERE T3 C 0 AND T3 B T2 B Now the remaining outer join operation can be replaced by an inner join too because the condition T3 B T2 B is null rejected and we get a query without outer joins at all SELECT FROM T1 INNER JOIN T2 ON T2 A T1 A T3 WHERE T3 C 0 AND T3 B T2 B Sometimes we succeed in replacing an embedded outer j...

Страница 695: ...rt SELECT FROM t1 ORDER BY key_part1 key_part2 SELECT FROM t1 WHERE key_part1 constant ORDER BY key_part2 SELECT FROM t1 ORDER BY key_part1 DESC key_part2 DESC SELECT FROM t1 WHERE key_part1 1 ORDER BY key_part1 DESC key_part2 DESC SELECT FROM t1 WHERE key_part1 constant ORDER BY key_part1 ASC SELECT FROM t1 WHERE key_part1 constant ORDER BY key_part1 DESC SELECT FROM t1 WHERE key_part1 constant1 ...

Страница 696: ...rder may be completely different from the order for ABS a of course SELECT ABS a AS b FROM t1 ORDER BY a By default MySQL sorts all GROUP BY col1 col2 queries as if you specified ORDER BY col1 col2 in the query as well If you include an ORDER BY clause explicitly that contains the same column list MySQL optimizes it away without any speed penalty although the sorting still occurs If a query includ...

Страница 697: ...Read the rows that match the WHERE clause 2 For each row record a tuple of values consisting of the sort key value and row position and also the columns required for the query 3 Sort the tuples by sort key value 4 Retrieve the rows in sorted order but read the required columns directly from the sorted tuples rather than by accessing the table a second time Using the modified filesort algorithm the...

Страница 698: ...ex types that the keys are ordered for example BTREE This property enables use of lookup groups in an index without having to consider all keys in the index that satisfy all WHERE conditions This access method considers only a fraction of the keys in an index so it is called a loose index scan When there is no WHERE clause a loose index scan reads as many keys as the number of groups which may be ...

Страница 699: ...ese conditions Otherwise it performs an index scan Because this method reads all keys in each range defined by the WHERE clause or scans the whole index if there are no range conditions we term it a tight index scan With a tight index scan the grouping operation is performed only after all keys that satisfy the range conditions have been found For this method to work it is sufficient that there is...

Страница 700: ...e IN operator to test subquery results or that use ANY which is equivalent This section discusses these optimizations particularly with regard to the challenges that NULL values present Suggestions on what you can do to help the optimizer are given at the end of the discussion Consider the following subquery comparison outer_expr IN SELECT inner_expr FROM WHERE subquery_where MySQL evaluates queri...

Страница 701: ... to look for such rows but if none are found also look for rows where inner_expr is NULL Roughly speaking the subquery can be converted to EXISTS SELECT 1 FROM WHERE subquery_where AND outer_expr inner_expr OR inner_expr IS NULL The need to evaluate the extra IS NULL 877 condition is why MySQL has the ref_or_null 647 access method mysql EXPLAIN SELECT outer_expr IN SELECT t2 maybe_null_key FROM t2...

Страница 702: ...ult so for some queries you might get a FALSE result rather than NULL As of MySQL 5 0 36 the optimizer chooses SQL compliance over speed so it accounts for the possibility that outer_expr might be NULL If outer_expr is NULL to evaluate the following expression it is necessary to run the SELECT to determine whether it produces any rows NULL IN SELECT inner_expr FROM WHERE subquery_where It is neces...

Страница 703: ...ex_subquery 647 accesses Table condition generator If the subquery is a join of several tables the triggered condition will be checked as soon as possible When the optimizer uses a triggered condition to create some kind of index lookup based access as for the first two items of the preceding list it must have a fallback strategy for the case when the condition is turned off This fallback strategy...

Страница 704: ...ew rows with LIMIT MySQL uses indexes in some cases when normally it would prefer to do a full table scan If you use LIMIT row_count with ORDER BY MySQL ends the sorting as soon as it has found the first row_count rows of the sorted result rather than sorting the entire result If ordering is done by using an index this is very fast If a filesort must be done all rows that match the query without t...

Страница 705: ...e the key distributions for the scanned table See Section 13 7 2 1 ANALYZE TABLE Syntax Use FORCE INDEX for the scanned table to tell MySQL that table scans are very expensive compared to using the given index SELECT FROM t1 t2 FORCE INDEX index_for_column WHERE t1 col_name t2 col_name See Section 13 2 8 3 Index Hint Syntax Start mysqld with the max seeks for key 1000 471 option or use SET max_see...

Страница 706: ... 14 1 3 3 Compressed Table Characteristics 6 Re create the indexes with myisamchk rq path to db tbl_name This creates the index tree in memory before writing it to disk which is much faster that updating the index during LOAD DATA INFILE because it avoids lots of disk seeks The resulting index tree is also perfectly balanced 7 Execute a FLUSH TABLES statement or a mysqladmin flush tables command L...

Страница 707: ...2 2 Speed of UPDATE Statements An update statement is optimized like a SELECT query with the additional overhead of a write The speed of the write depends on the amount of data being updated and the number of indexes that are updated Indexes that are not changed do not get updated Another way to get fast updates is to delay updates and then do many updates in a row later Performing multiple update...

Страница 708: ...sers For example if you set the myisamchk key_buffer_size variable to 128MB you could set the corresponding key_buffer_size 458 system variable larger than that if it is not already set larger to allow for key buffer use by activity in other sessions However changing the global key buffer size invalidates the buffer causing increased disk I O and slowdown for other sessions An alternative that avo...

Страница 709: ...erts even in tables that have deleted rows See Section 8 7 3 Concurrent Inserts To fix any compression issues that may have occurred with ARCHIVE tables you can use OPTIMIZE TABLE See Section 14 8 The ARCHIVE Storage Engine Use ALTER TABLE ORDER BY expr1 expr2 if you usually retrieve rows in expr1 expr2 order By using this option after extensive changes to the table you may be able to get higher p...

Страница 710: ...speed Stored routines or UDFs user defined functions may be a good way to gain performance for some tasks See Section 18 2 Using Stored Routines Procedures and Functions and Section 21 2 Adding New Functions to MySQL for more information You can increase performance by caching queries or answers in your application and then executing many inserts or updates together If your database system support...

Страница 711: ...se you need not parse your text files to find line and column boundaries Replication can provide a performance benefit for some operations You can distribute client retrievals among replication servers to split up the load To avoid slowing down the master while making backups you can make backups using a slave server See Chapter 16 Replication Declaring a MyISAM table with the DELAY_KEY_WRITE 1 ta...

Страница 712: ...xes per table and the maximum index length is defined per storage engine See Chapter 14 Storage Engines All storage engines support at least 16 indexes per table and a total index length of at least 256 bytes Most storage engines have higher limits With col_name N syntax in an index specification you can create an index that uses only the first N characters of a string column Indexing only a prefi...

Страница 713: ...t_name and first_name values It can also be used for queries that specify just a last_name value because that column is a leftmost prefix of the index see Section 8 5 2 Multiple Column Indexes Therefore the name index is used for lookups in the following queries SELECT FROM test WHERE last_name Widenius SELECT FROM test WHERE last_name Widenius AND first_name Michael SELECT FROM test WHERE last_na...

Страница 714: ...ORY tables are described at the end of this section MySQL uses indexes for these operations To find the rows matching a WHERE clause quickly To eliminate rows from consideration If there is a choice between multiple indexes MySQL normally uses the index that finds the smallest number of rows To retrieve rows from other tables when performing joins MySQL can use indexes on columns more efficiently ...

Страница 715: ...l3 If an index exists on col1 col2 col3 only the first two queries use the index The third and fourth queries do involve indexed columns but col2 and col2 col3 are not leftmost prefixes of col1 col2 col3 B Tree Index Characteristics A B tree index can be used for column comparisons in expressions that use the 875 876 876 876 876 or BETWEEN 877 operators The index also can be used for LIKE 896 comp...

Страница 716: ...pe of index cannot be used to search for the next entry in order MySQL cannot determine approximately how many rows there are between two values this is used by the range optimizer to decide which index to use This may affect some queries if you change a MyISAM table to a hash indexed MEMORY table Only whole keys can be used to search for a row With a B tree index any leftmost prefix of the key ca...

Страница 717: ...ny NULL values this method skews the average value group size downward If the average non NULL value group size is large counting NULL values each as a group of size 1 causes the optimizer to overestimate the value of the index for joins that look for non NULL values Consequently the nulls_unequal method may cause the optimizer to use this index for ref 646 lookups when other methods may be better...

Страница 718: ..._buffer_size 458 value is too small to allocate the minimal number of block buffers 8 When the key cache is not operational index files are accessed using only the native file system buffering provided by the operating system In other words table index blocks are accessed using the same strategy as that employed for table data blocks An index block is a contiguous unit of access to the MyISAM inde...

Страница 719: ...ntention further MySQL also provides multiple key caches This feature enables you to assign different table indexes to different key caches Where there are multiple key caches the server must know which cache to use when processing queries for a given MyISAM table By default all MyISAM table indexes are cached in the default key cache To assign table indexes to a specific key cache use the CACHE I...

Страница 720: ...robability that the index blocks corresponding to nonleaf nodes of the index B tree remain in the cache An update operation most frequently executed for temporary tables is performed much faster when the updated node is in the cache and need not be read in from disk first If the size of the indexes of the temporary tables are comparable with the size of cold key cache the probability is very high ...

Страница 721: ...able high level B tree nodes To avoid this you must use a midpoint insertion strategy with the key_cache_division_limit 460 set to much less than 100 Then valuable frequently hit nodes are preserved in the hot sublist during an index scan operation as well 8 6 1 4 Index Preloading If there are enough blocks in a key cache to hold blocks of an entire index or at least the blocks corresponding to it...

Страница 722: ...ing for the indexes ceases 8 6 2 The InnoDB Buffer Pool InnoDB maintains a buffer pool for caching data and indexes in memory InnoDB manages the pool as a list using a least recently used LRU algorithm incorporating a midpoint insertion strategy When room is needed to add a new block to the pool InnoDB evicts the least recently used block and adds the new block to the middle of the list The midpoi...

Страница 723: ...s so a result set generated by one client can be sent in response to the same query issued by another client The query cache can be useful in an environment where you have tables that do not change very often and for which the server receives many identical queries This is a typical situation for many Web servers that generate many dynamic pages based on database content The query cache does not r...

Страница 724: ...e in the query cache before parsing so the following two queries are regarded as different by the query cache SELECT FROM tbl_name Select from tbl_name Queries must be exactly the same byte for byte to be seen as identical In addition query strings that are identical may be treated as different for other reasons Queries that use different databases different protocol versions or different default ...

Страница 725: ...nctions It refers to user variables or local stored program variables It refers to tables in the mysql or INFORMATION_SCHEMA system database It is of any of the following forms SELECT LOCK IN SHARE MODE SELECT FOR UPDATE SELECT INTO OUTFILE SELECT INTO DUMPFILE SELECT FROM WHERE autoincrement_col IS NULL The last form is not cached because it is used as the ODBC workaround for obtaining the last i...

Страница 726: ...ables with additional configuration information given here To set the size of the query cache set the query_cache_size 485 system variable Setting it to 0 disables the query cache The default size is 0 so the query cache is disabled by default Be careful not to set the size of the cache too large Due to the need for threads to lock the cache during updates you may see lock contention issues with a...

Страница 727: ...nection by setting the SESSION query_cache_type 485 value For example a client can disable use of the query cache for its own queries like this mysql SET SESSION query_cache_type OFF If you set query_cache_type 485 at server startup rather than at runtime with a SET statement only the numeric values are permitted To control the maximum size of individual query results that can be cached set the qu...

Страница 728: ...he query cache The FLUSH TABLES statement also does this To monitor query cache performance use SHOW STATUS to view the cache status variables mysql SHOW STATUS LIKE Qcache Variable_name Value Qcache_free_blocks 36 Qcache_free_memory 138488 Qcache_hits 79570 Qcache_inserts 27087 Qcache_lowmem_prunes 3114 Qcache_not_cached 22989 Qcache_queries_in_cache 415 Qcache_total_blocks 912 Descriptions of ea...

Страница 729: ...level locking for InnoDB tables In many cases you can make an educated guess about which locking type is best for an application but generally it is difficult to say that a given lock type is better than another Everything depends on the application and different parts of an application may require different lock types To decide whether you want to use a storage engine with row level locking you s...

Страница 730: ...r sessions to perform concurrent inserts while you have the table locked To perform many INSERT and SELECT operations on a table real_table when concurrent inserts are not possible you can insert rows into a temporary table temp_table and update the real table with the rows from the temporary table periodically This can be done with the following code mysql LOCK TABLES real_table WRITE temp_table ...

Страница 731: ...DB and NDBCLUSTER For InnoDB and BDB tables MySQL uses table locking only if you explicitly lock the table with LOCK TABLES For these storage engines avoid using LOCK TABLES at all because InnoDB uses automatic row level locking and BDB uses page level locking to ensure transaction isolation For large tables table locking is often better than row locking but there are some disadvantages Table lock...

Страница 732: ...R_RESULT with SELECT statements can help to make the duration of table locks shorter See Section 13 2 8 SELECT Syntax You could change the locking code in mysys thr_lock c to use a single queue In this case write locks and read locks would have the same priority which might help some applications Here are some tips concerning table locks in MySQL Concurrent users are not a problem if you do not mi...

Страница 733: ...SAM database tables by multiple processes External locking is used in situations where a single process such as the MySQL server cannot be assumed to be the only process that requires access to tables Here are some examples If you run multiple servers that use the same database directory not recommended each server must have external locking enabled If you use myisamchk to perform table maintenanc...

Страница 734: ...sign your tables to minimize their space on the disk This can result in huge improvements by reducing the amount of data written to and read from disk Smaller tables normally require less main memory while their contents are being actively processed during query execution Any space reduction for table data also results in smaller indexes that can be processed faster MySQL supports many different s...

Страница 735: ...ix on the first number of characters it is better to index only this prefix using MySQL s support for creating an index on the leftmost part of the column see Section 13 1 8 CREATE INDEX Syntax Shorter indexes are faster not only because they require less disk space but because they also give you more hits in the index cache and thus fewer disk seeks See Section 8 9 2 Tuning Server Parameters In s...

Страница 736: ...an handle the number of open file descriptors implied by the table_cache 498 setting If table_cache 498 is set too high MySQL may run out of file descriptors and refuse connections fail to perform queries and be very unreliable You also have to take into account that the MyISAM storage engine needs two file descriptors for each unique open table You can increase the number of file descriptors avai...

Страница 737: ...ead when the table cache is full because for every table that has to be opened another must be closed You can reduce this overhead by increasing the number of entries permitted in the table cache 8 8 5 How MySQL Uses Internal Temporary Tables In some cases the server creates internal temporary tables while processing queries Such a table can be held in memory and processed by the MEMORY storage en...

Страница 738: ...ater kernels have good SMP support Note that older Linux kernels have a 2GB filesize limit by default If you have such a kernel and a need for files larger than 2GB you should get the Large File Support LFS patch for the ext2 file system Other file systems such as ReiserFS and XFS do not have this 2GB limitation Before using MySQL in production we advise you to test it on your intended platform Ot...

Страница 739: ...xternal locking FALSE federated TRUE gdb FALSE large pages FALSE init connect No default value init file No default value init slave No default value innodb TRUE innodb_checksums TRUE innodb_data_home_dir No default value innodb_adaptive_hash_index TRUE innodb_doublewrite TRUE innodb_fast_shutdown 1 innodb_file_per_table FALSE innodb_flush_log_at_trx_commit 1 innodb_flush_method No default value i...

Страница 740: ...og info file relay log info replicate same server id FALSE report host No default value report password No default value report port 3306 report user No default value rpl recovery rank 0 safe user create FALSE secure auth FALSE secure file priv No default value server id 0 show slave auth info FALSE skip grant tables FALSE skip slave start FALSE slave load tmpdir tmp socket tmp mysql sock sporadic...

Страница 741: ...446744073709547520 max_binlog_size 1073741824 max_connect_errors 10 max_connections 100 max_delayed_threads 20 max_error_count 64 max_heap_table_size 16777216 max_join_size 18446744073709551615 max_length_for_sort_data 1024 max_prepared_stmt_count 16382 max_relay_log_size 0 max_seeks_for_key 18446744073709551615 max_sort_length 1024 max_sp_recursion_depth 0 max_tmp_tables 32 max_user_connections 0...

Страница 742: ...ion 5 1 4 Server System Variables and Section 5 1 6 Server Status Variables MySQL uses algorithms that are very scalable so you can usually run with very little memory However normally you get better performance by giving MySQL more memory When tuning a MySQL server the two most important variables to configure are key_buffer_size 458 and table_cache 498 You should first feel confident that you ha...

Страница 743: ...ion requests and another handles named pipe connection requests The server does not create threads to handle interfaces that it does not listen to For example a Windows server that does not have support for named pipe connections enabled does not create a thread to handle them Connection manager threads associate each client connection with a thread dedicated to it that handles authentication and ...

Страница 744: ... variable net_buffer_length 477 The connection buffer and result buffer each begin with a size equal to net_buffer_length 477 bytes but are dynamically enlarged up to max_allowed_packet 466 bytes as needed The result buffer shrinks to net_buffer_length 477 bytes after each SQL statement While a statement is running a copy of the current statement string is also allocated All threads share the same...

Страница 745: ...ches information in memory as a result of GRANT and CREATE USER statements This memory is not released by the corresponding REVOKE and DROP USER statements so for a server that executes many instances of the statements that cause caching there will be an increase in memory use This cached memory can be freed with FLUSH PRIVILEGES ps and other system status programs may report that mysqld uses a lo...

Страница 746: ...ation If hdparm is not used wisely file system corruption may result so back up everything before experimenting You can also set the parameters for the file system that the database uses If you do not need to know when files were last accessed which is not really useful on a database server you can mount your file systems with the o noatime option That skips updates to the last access time in inod...

Страница 747: ...e Section 13 1 10 CREATE TABLE Syntax Alternatively if mysqld is not running symlinking can be accomplished manually using ln s from the command line Note Beginning with MySQL 5 0 60 the path used with either or both of the DATA DIRECTORY and INDEX DIRECTORY options may not include the MySQL data directory Bug 32167 myisamchk does not replace a symlink with the data file or index file It works dir...

Страница 748: ... Suppose that you want to place the database directory for a database named mydb at D data mydb To do this create a symbolic link in the MySQL data directory that points to D data mydb However before creating the symbolic link make sure that the D data mydb directory exists by creating it if necessary If you already have a database directory named mydb in the data directory move it to D data Other...

Страница 749: ...page txt file of your Linux sources The kernel for some recent systems such as Red Hat Enterprise Linux appear to have the large pages feature enabled by default To check whether this is true for your kernel use the following command and look for output lines containing huge shell cat proc meminfo grep i huge HugePages_Total 0 HugePages_Free 0 HugePages_Rsvd 0 HugePages_Surp 0 Hugepagesize 4096 kB...

Страница 750: ...e error log Warning Using conventional memory pool To verify that large pages are being used check proc meminfo again shell cat proc meminfo grep i huge HugePages_Total 20 HugePages_Free 20 HugePages_Rsvd 2 HugePages_Surp 0 Hugepagesize 4096 kB 8 9 8 DNS Lookup Optimization and the Host Cache The MySQL server maintains a host cache in memory that contains information about clients IP address host ...

Страница 751: ...case the server uses only IP addresses and not host names to match connecting hosts to rows in the MySQL grant tables Only accounts specified in those tables using IP addresses can be used If you have a very slow DNS and many hosts you might be able to improve performance either by disabling DNS lookups with skip name resolve 420 or by increasing the HOST_CACHE_SIZE define default value 128 and re...

Страница 752: ...ent To see the complete statements use SHOW FULL PROCESSLIST The following sections list the possible Command values and State values grouped by category The meaning for some of these values is self evident For others additional description is provided 8 10 1 Thread Command Values A thread can have any of the following Command values Binlog Dump This is a thread on a master server for sending bina...

Страница 753: ...g The thread is handling a server ping request Prepare The thread is preparing a prepared statement Processlist The thread is producing information about server threads Query The thread is executing a statement Quit The thread is terminating Refresh The thread is flushing table logs or caches or resetting status variable or replication server information Register Slave The thread is registering a ...

Страница 754: ...NALYZE TABLE checking permissions The thread is checking whether the server has the required privileges to execute the statement Checking table The thread is performing a table check operation cleaning up The thread has processed one command and is preparing to free memory and reset certain state variables closing tables The thread is flushing the changed table data to disk and closing the used ta...

Страница 755: ...g to tmp table on disk deleting from main table The server is executing the first part of a multiple table delete It is deleting only from the first table and saving columns and offsets to be used for deleting from the other reference tables deleting from reference tables The server is executing the second part of a multiple table delete and deleting the matched rows from the other tables discard_...

Страница 756: ... thread is locked by some other thread the kill takes effect as soon as the other thread releases its lock Locked The query is locked by another query logging slow query The thread is writing a statement to the slow query log NULL This state is used for the SHOW PROCESSLIST state login The initial state for a connection thread until the client has been authenticated successfully Opening tables Ope...

Страница 757: ...ing to reopen it Repair by sorting The repair code is using a sort to create indexes Repair done The thread has completed a multi threaded repair for a MyISAM table Repair with keycache The repair code is using creating keys one by one through the key cache This is much slower than Repair by sorting Rolling back The thread is rolling back a transaction Saving state For MyISAM table operations such...

Страница 758: ...al system locks with the skip external locking 420 option However external locking is disabled by default so it is likely that this option will have no effect For SHOW PROFILE this state means the thread is requesting the lock not waiting for it Table lock The next thread state after System lock The thread has acquired an external lock and is going to request an internal table lock update The thre...

Страница 759: ...tes These thread states are associated with processing for DELAYED inserts see Section 13 2 5 2 INSERT DELAYED Syntax Some states are associated with connection threads that process INSERT DELAYED statements from clients Other states are associated with delayed insert handler threads that insert the rows There is a delayed insert handler thread for each table for which INSERT DELAYED statements ar...

Страница 760: ...able reschedule After inserting a number of rows the delayed insert thread sleeps to let other threads do work upgrading lock A delayed insert handler is trying to get a lock for the table to insert rows Waiting for INSERT A delayed insert handler is waiting for a connection thread to add rows to the queue see storing row into queue 8 10 4 Query Cache Thread States These thread states are associat...

Страница 761: ... the most common states you see in the State column for a slave server I O thread This state also appears in the Slave_IO_State column displayed by SHOW SLAVE STATUS so you can get a good view of what is happening by using that statement Waiting for master update The initial state before Connecting to master Connecting to master The thread is attempting to connect to the master Checking master ver...

Страница 762: ...bined size exceeds this value The I O thread is waiting until the SQL thread frees enough space by processing relay log contents so that it can delete some relay log files Waiting for slave mutex on exit A state that occurs briefly as the thread is stopping 8 10 7 Replication Slave SQL Thread States The following list shows the most common states you may see in the State column for a slave server ...

Страница 763: ...e index on master dump table This state occurs after Reading master dump table data starting slave The thread is starting the slave threads after processing a successful LOAD DATA FROM MASTER load operation 8 10 9 MySQL Cluster Thread States Committing events to binlog Opening mysql ndb_apply_status Processing events The thread is processing events for binary logging Processing events from schema ...

Страница 764: ...MySQL Cluster Thread States 744 Waiting for schema epoch The thread is waiting for a schema epoch that is a global checkpoint ...

Страница 765: ...tifiers such as database table and column names Reserved words User defined and system variables Comments 9 1 Literal Values This section describes how to write literal values in MySQL These include strings numbers hexadecimal values boolean values and NULL The section also covers the various nuances and gotchas that you may run into when dealing with these basic types in MySQL 9 1 1 String Litera...

Страница 766: ... shown in Table 9 1 Special Character Escape Sequences For all other escape sequences backslash is ignored That is the escaped character is interpreted as if it was not escaped For example x is just x These sequences are case sensitive For example b is interpreted as a backspace but B is interpreted as B Escape processing is done according to the character set indicated by the character_set_connec...

Страница 767: ...L or Control Z The mysql client truncates quoted strings containing NUL characters if they are not escaped and Control Z may be taken for END OF FILE on Windows if not escaped For the escape sequences that represent each of these characters see Table 9 1 Special Character Escape Sequences When writing application programs any string that might contain any of these special characters must be proper...

Страница 768: ...andard SQL and ODBC Date and Time Literals Standard SQL permits temporal literals to be specified using a type keyword and a string The space between the keyword and string is optional DATE str TIME str TIMESTAMP str MySQL recognizes those constructions and also the corresponding ODBC syntax d str t str ts str However MySQL ignores the type keyword and each of the preceding constructions produces ...

Страница 769: ...09 Similarly for values specified as strings that include time part delimiters it is unnecessary to specify two digits for hour minute or second values that are less than 10 2015 10 30 1 2 3 is the same as 2015 10 30 01 02 03 Values specified as numbers should be 6 8 12 or 14 digits long If a number is 8 or 14 digits long it is assumed to be in YYYYMMDD or YYYYMMDDHHMMSS format and that the year i...

Страница 770: ...l syntax values that contain an odd number of digits are treated as having an extra leading 0 For example 0x0a and 0xaaa are interpreted as 0x0a and 0x0aaa In numeric contexts hexadecimal values act like integers 64 bit precision In string contexts they act like binary strings where each pair of hex digits is converted to a character mysql SELECT X 4D7953514C MySQL mysql SELECT 0x0a 0 10 mysql SEL...

Страница 771: ...aware that the NULL value is different from values such as 0 for numeric types or the empty string for string types For more information see Section C 5 5 3 Problems with NULL Values 9 2 Schema Object Names Certain objects within MySQL including database table index column alias view stored procedure partition and other object names are known as identifiers This section describes the permissible s...

Страница 772: ...cribed in Section 5 1 7 Server SQL Modes Identifier quote characters can be included within an identifier if you quote the identifier If the character to be included within the identifier is the same as that used to quote the identifier itself then you need to double the character The following statement creates a table named a b that contains a column named c d mysql CREATE TABLE a b c d INT In t...

Страница 773: ...ers The initial parts of a multiple part name act as qualifiers that affect the context within which the final identifier is interpreted In MySQL you can refer to a table column using any of the following forms Column Reference Meaning col_name The column col_name from whichever table used in the statement contains a column of that name tbl_name col_name The column col_name from table tbl_name of ...

Страница 774: ...lumn aliases Trigger names are case sensitive which differs from standard SQL By default table aliases are case sensitive on Unix but not so on Windows or Mac OS X The following statement would not work on Unix because it refers to the alias both as a and as A mysql SELECT col_name FROM tbl_name AS a WHERE a col_name 1 OR A col_name 2 However this same statement is permitted on Windows To avoid pr...

Страница 775: ...ption If you are using InnoDB tables and you are trying to avoid these data transfer problems you should set lower_case_table_names 466 to 1 on all platforms to force names to be converted to lowercase If you plan to set the lower_case_table_names 466 system variable to 1 on Unix you must first convert your old database and table names to lowercase before stopping mysqld and restarting it with the...

Страница 776: ...n identifier it must not be followed immediately by a parenthesis The requirement that function calls be written with no whitespace between the name and the parenthesis applies only to the built in functions that have special considerations COUNT is one such name The exact list of function names for which following whitespace determines their interpretation are those listed in the sql_functions ar...

Страница 777: ...se this statement SET sql_mode IGNORE_SPACE IGNORE_SPACE 536 is also enabled by certain other composite modes such as ANSI 540 that include it in their value SET sql_mode ANSI Check Section 5 1 7 Server SQL Modes to see which composite modes enable IGNORE_SPACE 536 To minimize the dependency of SQL code on the IGNORE_SPACE 536 setting use these guidelines Avoid creating UDFs or stored functions th...

Страница 778: ... true for the names of built in functions Reserved words are permitted as identifiers if you quote them as described in Section 9 2 Schema Object Names mysql CREATE TABLE interval begin INT end INT ERROR 1064 42000 You have an error in your SQL syntax near interval begin INT end INT mysql CREATE TABLE interval begin INT end INT Query OK 0 rows affected 0 01 sec Exception A word that follows a peri...

Страница 779: ...OND DEC DECIMAL DECLARE DEFAULT DELAYED DELETE DESC DESCRIBE DETERMINISTIC DISTINCT DISTINCTROW DIV DOUBLE DROP DUAL EACH ELSE ELSEIF ENCLOSED ESCAPED EXISTS EXIT EXPLAIN FALSE FETCH FLOAT FLOAT4 FLOAT8 FOR FORCE FOREIGN FROM FULLTEXT GRANT GROUP HAVING HIGH_PRIORITY HOUR_MICROSECOND HOUR_MINUTE HOUR_SECOND IF IGNORE IN INDEX INFILE INNER INOUT INSENSITIVE INSERT INT INT1 INT2 INT3 INT4 INT8 INTEG...

Страница 780: ... SPATIAL SPECIFIC SQL SQLEXCEPTION SQLSTATE SQLWARNING SQL_BIG_RESULT SQL_CALC_FOUND_ROWS SQL_SMALL_RESULT SSL STARTING STRAIGHT_JOIN TABLE TERMINATED THEN TINYBLOB TINYINT TINYTEXT TO TRAILING TRIGGER TRUE UNDO UNION UNIQUE UNLOCK UNSIGNED UPDATE USAGE USE USING UTC_DATE UTC_TIME UTC_TIMESTAMP VALUES VARBINARY VARCHAR VARCHARACTER VARYING WHEN WHERE WHILE WITH WRITE XOR YEAR_MONTH ZEROFILL Table ...

Страница 781: ...eric characters _ and A user variable name can contain other characters if you quote it as a string or identifier for example my var my var or my var User variable names are not case sensitive in MySQL 5 0 and up but are case sensitive before MySQL 5 0 One way to set a user defined variable is by issuing a SET statement SET var_name expr var_name expr For SET either 882 or 881 can be used as the a...

Страница 782: ...1 you might think that MySQL will evaluate a first and then do an assignment second However changing the statement for example by adding a GROUP BY HAVING or ORDER BY clause may cause MySQL to select an execution plan with a different order of evaluation Another issue with assigning a value to a variable and reading the value within the same statement is that the default result type of a variable ...

Страница 783: ...vide identifiers is that if you are constructing a string for use as a prepared statement to be executed later In this case user variables can be used to provide any part of the statement The following example illustrates how this can be done mysql SET c c1 Query OK 0 rows affected 0 00 sec mysql SET s CONCAT SELECT c FROM t Query OK 0 rows affected 0 00 sec mysql PREPARE stmt FROM s Query OK 0 ro...

Страница 784: ... terms Operator precedence is given in Section 12 3 1 Operator Precedence expr expr OR expr expr expr expr XOR expr expr AND expr expr expr NOT expr expr boolean_primary IS NOT TRUE FALSE UNKNOWN boolean_primary boolean_primary boolean_primary IS NOT NULL boolean_primary predicate boolean_primary comparison_operator predicate boolean_primary comparison_operator ALL ANY subquery predicate compariso...

Страница 785: ...ax param_marker is as used in prepared statements for placeholders See Section 13 5 1 PREPARE Syntax subquery indicates a subquery that returns a single value that is a scalar subquery See Section 13 2 9 1 The Subquery as Scalar Operand identifier expr is ODBC escape syntax and is accepted for ODBC compatibility The value is expr The curly braces in the syntax should be written literally they are ...

Страница 786: ...rted MySQL Server supports some variants of C style comments These enable you to write code that includes MySQL extensions but is still portable by using comments of the following form MySQL specific code In this case MySQL Server parses and executes the code within the comment as it would any other SQL statement but other SQL servers will ignore the extensions For example MySQL Server recognizes ...

Страница 787: ...11 10 4 3 Adding a Simple Collation to an 8 Bit Character Set 812 10 4 4 Adding a UCA Collation to a Unicode Character Set 813 10 5 Character Set Configuration 816 10 6 MySQL Server Time Zone Support 816 10 6 1 Staying Current with Time Zone Changes 819 10 6 2 Time Zone Leap Second Support 820 10 7 MySQL Server Locale Support 821 This chapter covers issues of globalization which includes internati...

Страница 788: ... at the encodings 0 for A and 1 for B Because 0 is less than 1 we say A is less than B What we ve just done is apply a collation to our character set The collation is a set of rules only one rule in this case compare the encodings We call this simplest of all possible collations a binary collation But what if we want to say that the lowercase and uppercase letters are equivalent Then we would have...

Страница 789: ...12_chinese_ci 2 greek ISO 8859 7 Greek greek_general_ci 1 cp1250 Windows Central European cp1250_general_ci 1 gbk GBK Simplified Chinese gbk_chinese_ci 2 latin5 ISO 8859 9 Turkish latin5_turkish_ci 1 Any given character set always has at least one collation It may have several collations To list the collations for a character set use the SHOW COLLATION statement For example to see the collations f...

Страница 790: ...munication between client programs and the MySQL server If you want the client program to communicate with the server using a character set different from the default you ll need to indicate which one For example to use the utf8 Unicode character set issue this statement after connecting to the server SET NAMES utf8 For more information about character set related issues in client server communica...

Страница 791: ...me MySQL server Example CREATE DATABASE db_name CHARACTER SET latin1 COLLATE latin1_swedish_ci MySQL chooses the database character set and database collation in the following manner If both CHARACTER SET X and COLLATE Y are specified character set X and collation Y are used If CHARACTER SET X is specified without COLLATE character set X and its default collation are used To see the default collat...

Страница 792: ...collation are not specified in individual column definitions The table character set and collation are MySQL extensions there are no such things in standard SQL 10 1 3 4 Column Character Set and Collation Every character column that is a column of type CHAR VARCHAR or TEXT has a column character set and a column collation Column definition syntax for CREATE TABLE and ALTER TABLE has optional claus...

Страница 793: ...able defaults are used The column has character set latin1 and collation latin1_bin The CHARACTER SET and COLLATE clauses are standard SQL If you use ALTER TABLE to convert a column from one character set to another MySQL attempts to map the data values but if the character sets are incompatible there may be data loss 10 1 3 5 Character String Literal Character Set and Collation Every character st...

Страница 794: ...mplemented according to standard SQL specifications An introducer indicates the character set for the following string but does not change now how the parser performs escape processing within the string Escapes are always interpreted by the parser according to the character set given by character_set_connection 442 The following examples show that escape processing occurs using character_set_conne...

Страница 795: ...ONAL CHARACTER 10 NCHAR 10 As are these VARCHAR 10 CHARACTER SET utf8 NATIONAL VARCHAR 10 NCHAR VARCHAR 10 NATIONAL CHARACTER VARYING 10 NATIONAL CHAR VARYING 10 You can use N literal or n literal to create a string in the national character set These statements are equivalent SELECT N some text SELECT n some text SELECT _utf8 some text For information on upgrading character sets to MySQL 5 0 from...

Страница 796: ...8 Compatibility with Other DBMSs For MaxDB compatibility these two statements are the same CREATE TABLE t1 f1 CHAR N UNICODE CREATE TABLE t1 f1 CHAR N CHARACTER SET ucs2 10 1 4 Connection Character Sets and Collations Several character set and collation system variables relate to a client s interaction with the server Some of these have been mentioned in earlier sections The server character set a...

Страница 797: ... the server Thus SET NAMES cp1251 tells the server future incoming messages from this client are in character set cp1251 It also specifies the character set that the server should use for sending results back to the client For example it indicates what character set to use for column values if you use a SELECT statement A SET NAMES charset_name statement is equivalent to these three statements SET...

Страница 798: ...mmand issues a SET NAMES statement and also changes the default character set that mysql uses when it reconnects after the connection has dropped Example Suppose that column1 is defined as CHAR 5 CHARACTER SET latin2 If you do not say SET NAMES or SET CHARACTER SET then for SELECT column1 FROM t the server sends back all the values for column1 using the character set that the client specified when...

Страница 799: ...ach time they connect This can be done by executing a SET NAMES utf8 statement after connecting The statement can be used regardless of connection method The mysql client PHP scripts and so forth In some cases it may be possible to configure the connection to use the desired character set some other way For example for connections made using mysql you can specify the default character set utf8 266...

Страница 800: ...ntent Type content text html charset utf 8 10 1 6 Character Set for Error Messages This section describes how the server uses character sets for constructing error messages and returning them to clients For information about the language of error messages rather than the character set see Section 10 2 Setting the Error Message Language In MySQL 5 0 the server constructs error messages and returns ...

Страница 801: ...t1 WHERE _latin1 Müller COLLATE latin1_german2_ci k SELECT FROM t1 WHERE k LIKE _latin1 Müller COLLATE latin1_german2_ci With HAVING SELECT k FROM t1 GROUP BY k HAVING k _latin1 Müller COLLATE latin1_german2_ci 10 1 7 3 COLLATE Clause Precedence The COLLATE clause has high precedence higher than 881 so the following two expressions are equivalent x y COLLATE z x y COLLATE z 10 1 7 4 Collations Mus...

Страница 802: ...coercibility Functions such as USER 964 have a coercibility of 2 rather than 3 and literals have a coercibility of 3 rather than 4 MySQL uses coercibility values with the following rules to resolve ambiguities Use the collation with the lowest coercibility value If both sides have the same coercibility then If both sides are Unicode or both sides are not Unicode it is an error If one of the sides ...

Страница 803: ... and BLOB data types have no character set or collation in the sense that nonbinary strings do Applied to a binary string the CHARSET and COLLATION functions both return a value of binary Binary strings are sequences of bytes and the numeric values of those bytes determine sort order The _bin collations differ from the binary collation in several respects The unit for sorting and comparison Binary...

Страница 804: ...LOWER aA LOWER CONVERT aA USING latin1 LOWER aA LOWER CONVERT aA USING latin1 aA aa 1 row in set 0 00 sec Trailing space handling in comparisons Nonbinary strings have PADSPACE behavior for all collations including _bin collations Trailing spaces are insignificant in comparisons mysql SET NAMES utf8 COLLATE utf8_bin Query OK 0 rows affected 0 00 sec mysql SELECT a a a a 1 1 row in set 0 00 sec For...

Страница 805: ...llation for the latin1 character set is latin1_bin so if the table default character set is latin1 these two column definitions are equivalent CHAR 10 BINARY CHAR 10 CHARACTER SET latin1 COLLATE latin1_bin The effect of BINARY as a column attribute differs from its effect prior to MySQL 4 1 Formerly BINARY resulted in a column that was treated as a binary string A binary string is a string of byte...

Страница 806: ...t of the SELECT using the German DIN 1 rule which says that U umlaut sorts with U The third column shows the result of the SELECT using the German DIN 2 rule which says that U umlaut sorts with UE Example 2 Searching for German Umlauts Suppose that you have three tables that differ only by the character set and collation used mysql SET NAMES utf8 mysql CREATE TABLE german1 c CHAR 10 CHARACTER SET ...

Страница 807: ...xpressions for many cases where MySQL would otherwise return an illegal mix of collations error The following discussion provides examples of expressions and their repertoires and describes how the use of repertoire changes string expression evaluation The repertoire for string constants depends on string content SET NAMES utf8 SELECT abc SELECT _utf8 def SELECT N MySQL Although the character set ...

Страница 808: ...1 _ucs2 0x0042 CONCAT _ucs2 0x0041 _ucs2 0x00C2 For the first call the repertoire is ASCII because both arguments are within the range of the ascii character set For the second call the repertoire is UNICODE because the second argument is outside the ascii character set range The repertoire for function return values is determined based only on the repertoire of the arguments that affect the resul...

Страница 809: ... no collation For example with CASE WHEN a THEN b WHEN b THEN c COLLATE X END the resulting collation is X The same applies for UNION 881 CONCAT 887 ELT 888 GREATEST 878 IF 883 and LEAST 879 For operations that convert to character data the character set and collation of the strings that result from the operations are defined by the character_set_connection 442 and collation_connection 443 system ...

Страница 810: ...SCHEMA has several tables that contain information similar to that displayed by the SHOW statements For example the CHARACTER_SETS and COLLATIONS tables contain the information displayed by SHOW CHARACTER SET and SHOW COLLATION See Chapter 19 INFORMATION_SCHEMA Tables The SHOW CHARACTER SET statement shows all available character sets It takes an optional LIKE 896 clause that indicates which chara...

Страница 811: ...he character set is not part of the display but is implied by the collation name 10 1 10 Unicode Support MySQL 5 0 supports two character sets for storing Unicode data ucs2 the UCS 2 encoding of the Unicode character set using 16 bits per character utf8 a UTF 8 encoding of the Unicode character set using one to three bytes per character These two character sets support the characters from the Basi...

Страница 812: ...ces that take from one to four bytes Currently MySQL support for UTF 8 does not include 4 byte sequences An older standard for UTF 8 encoding RFC 2279 describes UTF 8 sequences that take from one to six bytes RFC 3629 renders RFC 2279 obsolete for this reason sequences with five and six bytes are no longer used The idea of UTF 8 is that various Unicode characters are encoded using byte sequences o...

Страница 813: ...Connection Character Sets and Collations Alternatively a client program can perform the conversion after receiving the result from the server It is more efficient for the client to perform the conversion but this option is not always available for all clients If character_set_results 443 is set to NULL no conversion is performed and the server returns metadata using its original character set the ...

Страница 814: ...y be lossy if the column contains characters that are not in both character sets A special case occurs if you have old tables from before MySQL 4 1 where a nonbinary column contains values that actually are encoded in a character set different from the server s default character set For example an application might have stored sjis values in a column even though MySQL s default character set was l...

Страница 815: ...n cp852_general_ci latin7 ISO 8859 13 Baltic latin7_general_ci cp1251 Windows Cyrillic cp1251_general_ci cp1256 Windows Arabic cp1256_general_ci cp1257 Windows Baltic cp1257_general_ci binary Binary pseudo charset binary geostd8 GEOSTD8 Georgian geostd8_general_ci cp932 SJIS for Windows Japanese cp932_japanese_ci eucjpms UJIS for Windows Japanese eucjpms_japanese_ci In cases where a character set ...

Страница 816: ...ing marks are not fully supported This affects primarily Vietnamese Yoruba and some smaller languages such as Navajo MySQL implements language specific Unicode collations only if the ordering with xxx_unicode_ci does not work well for a language Language specific collations are UCA based They are derived from xxx_unicode_ci with additional language tailoring rules For any Unicode character set ope...

Страница 817: ...f8_unicode_ci because it is more accurate xxx_swedish_ci includes Swedish rules For example in Swedish the following relationship holds which is not something expected by a German or French speaker Ü Y Ö The xxx_spanish_ci and xxx_spanish2_ci collations correspond to modern Spanish and traditional Spanish respectively In both collations ñ n tilde is a separate letter between n and o In addition fo...

Страница 818: ...x90 to 0x0090 and 0x9d to 0x009d The latin1_swedish_ci collation is the default that probably is used by the majority of MySQL customers Although it is frequently said that it is based on the Swedish Finnish collation rules there are Swedes and Finns who disagree with this statement The latin1_german1_ci and latin1_german2_ci collations are based on the DIN 1 and DIN 2 standards where DIN stands f...

Страница 819: ...2 DOS Central European collations cp852_bin cp852_general_ci default keybcs2 DOS Kamenicky Czech Slovak collations keybcs2_bin keybcs2_general_ci default latin2 ISO 8859 2 Central European collations latin2_bin latin2_croatian_ci latin2_czech_cs latin2_general_ci default latin2_hungarian_ci macce Mac Central European collations macce_bin macce_general_ci default For additional information about Ce...

Страница 820: ...ropean and Middle Eastern collations in MySQL see Collation Charts Org armscii8 cp1256 geostd8 greek hebrew latin5 10 1 13 5 Baltic Character Sets The Baltic character sets cover Estonian Latvian and Lithuanian languages cp1257 Windows Baltic collations cp1257_bin cp1257_general_ci default cp1257_lithuanian_ci latin7 ISO 8859 13 Baltic collations latin7_bin latin7_estonian_cs latin7_general_ci def...

Страница 821: ...an character sets that we support include Chinese Japanese Korean and Thai These can be complicated For example the Chinese sets must allow for thousands of different characters See Section 10 1 13 7 1 The cp932 Character Set for additional information about the cp932 and sjis character sets For answers to some common questions and problems relating support for Asian character sets in MySQL see Se...

Страница 822: ...sjis character set corresponds to the Shift_JIS character set defined by IANA which supports JIS X0201 and JIS X0208 characters See http www iana org assignments character sets However the meaning of SHIFT JIS as a descriptive term has become very vague and it often includes the extensions to Shift_JIS that are defined by various vendors For example SHIFT JIS used in Japanese Windows environments ...

Страница 823: ...s use the code point of NEC special characters If the character is in both IBM selected characters and NEC selected IBM extended characters use the code point of IBM extended characters The table shown at http www microsoft com globaldev reference dbcs 932 htm provides information about the Unicode values of cp932 characters For cp932 table entries with characters under which a four digit number a...

Страница 824: ...3F 00A3 8192 3F 00AC 81CA 3F 2015 815C 815C 2016 8161 3F 2212 817C 3F 2225 3F 8161 301C 8160 3F FF0D 3F 817C FF3C 3F 815F FF5E 3F 8160 FFE0 3F 8191 FFE1 3F 8192 FFE2 3F 81CA Users of any Japanese character sets should be aware that using character set client handshake 402 or skip character set client handshake 402 has an important effect See Section 5 1 3 Server Command Options 10 2 Setting the Er...

Страница 825: ...MySQL The proper procedure depends on whether the character set is simple or complex If the character set does not need special string collating routines for sorting and does not need multi byte character support it is simple If the character set needs either of those features it is complex For example greek and swe7 are simple character sets whereas big5 and czech are complex character sets To us...

Страница 826: ...must contain a collation element that defines the character ordering For a complex character set create a C source file that describes the character set properties and defines the support routines necessary to properly perform operations on the character set Create the file ctype MYSET c in the strings directory Look at one of the existing ctype c files such as ctype big5 c to see what needs to be...

Страница 827: ...cated in the sql share charsets directory For a character set named MYSYS the file is named MYSET xml It uses map array elements to list character set properties map elements appear within these elements ctype defines attributes for each character lower and upper list the lowercase and uppercase characters unicode maps 8 bit character values to Unicode values collation elements indicate character ...

Страница 828: ...mplex to be handled with simple arrays you must define string collating functions in the ctype MYSET c source file in the strings directory The existing character sets provide the best documentation and examples to show how these functions are implemented Look at the ctype c files in the strings directory such as the files for the big5 czech gbk sjis and tis160 character sets Take a look at the MY...

Страница 829: ...cter set That is based on what is already present for the character set s current collations add data structures functions and configuration information for the new collation Note If you modify an existing collation that may affect the ordering of rows for indexes on columns that use the collation In this case rebuild any such indexes to avoid problems such as incorrect query results For further i...

Страница 830: ...he multi byte character 膰 has a character code of 0x81B0 but a weight of 0xC286 For implementation instructions see Section 10 3 Adding a Character Set Collations for Unicode multi byte character sets Some of these collations are based on the Unicode Collation Algorithm UCA others are not Non UCA collations have a one to one mapping from character code to weight In MySQL such collations are case i...

Страница 831: ...D C API data structure The number member of the MY_CHARSET_INFO data structure returned by the mysql_get_character_set_info C API function To determine the largest currently used ID issue the following statement mysql SELECT MAX ID FROM INFORMATION_SCHEMA COLLATIONS MAX ID 210 For the output just shown you could choose an ID higher than 210 for the new collation To display a list of all currently ...

Страница 832: ...a collation element that indicates the collation name and ID to associate the name with the ID For example charset name latin1 collation name latin1_test_ci id 56 charset 4 In the latin1 xml configuration file add a collation element that names the collation and that contains a map element that defines a character code to weight mapping table for character codes 0 to 255 Each value within the map ...

Страница 833: ... describe the collation s sort characteristics see Section 10 4 4 2 LDML Syntax Supported in MySQL The example adds a collation named utf8_phone_ci to the utf8 character set The collation is designed for a scenario involving a Web application for which users post their names and phone numbers Phone numbers can be given in very different formats 7 12345 67 7 12 345 67 7 12 345 67 7 12 345 67 712345...

Страница 834: ...sample phone numbers using the new collation mysql CREATE TABLE phonebook name VARCHAR 64 phone VARCHAR 64 CHARACTER SET utf8 COLLATE utf8_phone_ci Query OK 0 rows affected 0 09 sec mysql INSERT INTO phonebook VALUES Svoj 7 912 800 80 02 Query OK 1 row affected 0 00 sec mysql INSERT INTO phonebook VALUES Hf 7 912 800 80 04 Query OK 1 row affected 0 00 sec mysql INSERT INTO phonebook VALUES Bar 7 9...

Страница 835: ...Basic Latin letters A Z and a z can also be written literally this is a MySQL limitation the LDML specification permits literal non Latin1 characters in the rules Only characters in the Basic Multilingual Plane can be specified This notation does not apply to characters outside the BMP range of 0000 to FFFF The Index xml file itself should be written using ASCII encoding Syntax Rules LDML has rese...

Страница 836: ...or Unicode character sets you can define collations without recompiling by using LDML notation See Section 10 4 4 Adding a UCA Collation to a Unicode Character Set The character set is a dynamic character set but you do not have a configuration file for it In this case you should install the configuration file for the character set from a new MySQL distribution If your character set index file doe...

Страница 837: ... this statement mysql SET time_zone timezone The current session time zone setting affects display and storage of time values that are zone sensitive This includes the values displayed by functions such as NOW 926 or CURTIME 918 and values stored in and retrieved from TIMESTAMP columns Values for TIMESTAMP columns are converted from the current time zone to UTC for storage and from UTC to the curr...

Страница 838: ...em mysql processes those statements to load the time zone tables mysql_tzinfo_to_sql also can be used to load a single time zone file or to generate leap second information To load a single time zone file tz_file that corresponds to a time zone name tz_name invoke mysql_tzinfo_to_sql like this shell mysql_tzinfo_to_sql tz_file tz_name mysql u root mysql With this approach you must execute a separa...

Страница 839: ...nt time zone tables mysqld caches time zone information that it looks up so after replacing the time zone tables you should restart mysqld to make sure that it does not continue to serve outdated time zone data If you are uncertain whether named time zones are available for use either as the server s time zone setting or by clients that set their own time zone check whether your time zone tables a...

Страница 840: ...eading to backup restore problems As of MySQL 5 0 74 leap second values are returned with a time part that ends with 59 59 This means that a function such as NOW 926 can return the same value for two or three consecutive seconds during the leap second It remains true that literal temporal values having a time part that ends with 59 60 or 59 61 are considered invalid If it is necessary to search fo...

Страница 841: ... 2008 12 31 23 59 59 1 row in set 0 00 sec 10 7 MySQL Server Locale Support Beginning with MySQL 5 0 25 the locale indicated by the lc_time_names 462 system variable controls the language used to display day and month names and abbreviations This variable affects the output from the DATE_FORMAT 921 DAYNAME 923 and MONTHNAME 926 functions lc_time_names 462 does not affect the STR_TO_DATE 927 or GET...

Страница 842: ...s converted from utf8 to the character set indicated by the character_set_connection 442 system variable lc_time_names 462 may be set to any of the following locale values The set of locales supported by MySQL may differ from those supported by your operating system ar_AE Arabic United Arab Emirates ar_BH Arabic Bahrain ar_DZ Arabic Algeria ar_EG Arabic Egypt ar_IN Arabic India ar_IQ Arabic Iraq a...

Страница 843: ..._CH French Switzerland fr_FR French France fr_LU French Luxembourg gl_ES Galician Spain gu_IN Gujarati India he_IL Hebrew Israel hi_IN Hindi India hr_HR Croatian Croatia hu_HU Hungarian Hungary id_ID Indonesian Indonesia is_IS Icelandic Iceland it_CH Italian Switzerland it_IT Italian Italy ja_JP Japanese Japan ko_KR Korean Republic of Korea lt_LT Lithuanian Lithuania lv_LV Latvian Latvia mk_MK Mac...

Страница 844: ...824 ...

Страница 845: ... width for integer types For floating point and fixed point types M is the total number of digits that can be stored the precision For string types M is the maximum length The maximum permissible value of M depends on the data type D applies to floating point and fixed point types and indicates the number of digits following the decimal point the scale The maximum possible value is 30 but should b...

Страница 846: ...MEMORY InnoDB BDB and NDBCLUSTER Before 5 0 3 BIT is a synonym for TINYINT 1 TINYINT M UNSIGNED ZEROFILL A very small integer The signed range is 128 to 127 The unsigned range is 0 to 255 BOOL BOOLEAN These types are synonyms for TINYINT 1 A value of zero is considered false Nonzero values are considered true mysql SELECT IF 0 true false IF 0 true false false mysql SELECT IF 1 true false IF 1 true...

Страница 847: ...metic is done using signed BIGINT or DOUBLE values so you should not use unsigned big integers larger than 9223372036854775807 63 bits except with bit functions If you do that some of the last digits in the result may be wrong because of rounding errors when converting a BIGINT value to a DOUBLE MySQL can handle BIGINT in the following cases When using integers to store large unsigned values in a ...

Страница 848: ...d behavior still applies to those columns To convert the tables to the newer DECIMAL format dump them with mysqldump and reload them DEC M D UNSIGNED ZEROFILL NUMERIC M D UNSIGNED ZEROFILL FIXED M D UNSIGNED ZEROFILL These types are synonyms for DECIMAL The FIXED synonym is available for compatibility with other database systems FLOAT M D UNSIGNED ZEROFILL A small single precision floating point n...

Страница 849: ... A date The supported range is 1000 01 01 to 9999 12 31 MySQL displays DATE values in YYYY MM DD format but permits assignment of values to DATE columns using either strings or numbers DATETIME A date and time combination The supported range is 1000 01 01 00 00 00 to 9999 12 31 23 59 59 MySQL displays DATETIME values in YYYY MM DD HH MM SS format but permits assignment of values to DATETIME column...

Страница 850: ...l FROM tbl_name SELECT FROM_DAYS SUM TO_DAYS date_col FROM tbl_name Note The MySQL server can be run with the MAXDB 540 SQL mode enabled In this case TIMESTAMP is identical with DATETIME If this mode is enabled at the time that a table is created TIMESTAMP columns are created as DATETIME columns As a result such columns use DATETIME display format have the same range of values and there is no auto...

Страница 851: ...TER SET binary c2 TEXT CHARACTER SET binary c3 ENUM a b c CHARACTER SET binary The resulting table has this definition CREATE TABLE t c1 VARBINARY 10 c2 BLOB c3 ENUM a b c CHARACTER SET binary The ASCII attribute is shorthand for CHARACTER SET latin1 The UNICODE attribute is shorthand for CHARACTER SET ucs2 The BINARY attribute is shorthand for specifying the binary collation of the column charact...

Страница 852: ...CHAR 0 NULL occupies only one bit and can take only the values NULL and the empty string NATIONAL VARCHAR M CHARACTER SET charset_name COLLATE collation_name A variable length string M represents the maximum column length in characters In MySQL 5 0 the range of M is 0 to 255 before MySQL 5 0 3 and 0 to 65 535 in MySQL 5 0 3 and later The effective maximum length of a VARCHAR in MySQL 5 0 3 and lat...

Страница 853: ...Each TEXT value is stored using a 2 byte length prefix that indicates the number of bytes in the value An optional length M can be given for this type If this is done MySQL creates the column as the smallest TEXT type large enough to hold values M characters long MEDIUMBLOB A BLOB column with a maximum length of 16 777 215 2 24 1 bytes Each MEDIUMBLOB value is stored using a 3 byte length prefix t...

Страница 854: ...DOUBLE PRECISION The keyword INT is a synonym for INTEGER and the keywords DEC and FIXED are synonyms for DECIMAL MySQL treats DOUBLE as a synonym for DOUBLE PRECISION a nonstandard extension MySQL also treats REAL as a synonym for DOUBLE PRECISION a nonstandard variation unless the REAL_AS_FLOAT 539 SQL mode is enabled As of MySQL 5 0 3 a BIT data type is available for storing bit field values Be...

Страница 855: ...n the positive end of the range the column could actually store numbers up to 9999 99 For positive numbers MySQL 5 0 2 and earlier used the byte reserved for the sign to extend the upper end of the range In standard SQL the syntax DECIMAL M is equivalent to DECIMAL M 0 Similarly the syntax DECIMAL is equivalent to DECIMAL M 0 where the implementation is permitted to decide the value of M MySQL sup...

Страница 856: ...SQL supports an extension for optionally specifying the display width of integer data types in parentheses following the base keyword for the type For example INT 4 specifies an INT with a display width of four digits This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left padding them with spaces That is...

Страница 857: ...ponding endpoint of the column data type range If you store 256 into a TINYINT or TINYINT UNSIGNED column MySQL stores 127 or 255 respectively When a floating point or fixed point column is assigned a value that exceeds the range implied by the specified or default precision and scale MySQL stores the value representing the corresponding endpoint of that range Column assignment conversions that oc...

Страница 858: ... a range of legal values as well as a zero value that may be used when you specify an illegal value that MySQL cannot represent The TIMESTAMP type has special automatic updating behavior described later For temporal type storage requirements see Section 11 2 Data Type Storage Requirements Keep in mind these general considerations when working with date and time types MySQL retrieves values for a g...

Страница 859: ... that require complete dates To disallow zero month or day parts in dates enable the NO_ZERO_IN_DATE 538 SQL mode MySQL permits you to store a zero value of 0000 00 00 as a dummy date This is in some cases more convenient than using NULL values and uses less data and index space To disallow 0000 00 00 enable the NO_ZERO_DATE 538 SQL mode Zero date or time values used through Connector ODBC are con...

Страница 860: ...d format for values specified as strings in which any punctuation character may be used as the delimiter between date parts or time parts In some cases this syntax can be deceiving For example a value such as 10 11 12 might look like a time value because of the delimiter but is interpreted as the year 2010 11 12 if used in a date context The value 10 45 15 is converted to 0000 00 00 because 45 is ...

Страница 861: ...eaning 11 12 00 12 minutes after 11 o clock but MySQL interprets them as 00 11 12 11 minutes 12 seconds Similarly 12 and 12 are interpreted as 00 00 12 By default values that lie outside the TIME range but are otherwise legal are clipped to the closest endpoint of the range For example 850 00 00 and 850 00 00 are converted to 838 59 59 and 838 59 59 Illegal TIME values are converted to 00 00 00 No...

Страница 862: ...t migrating existing YEAR 2 columns to YEAR 4 Note that migration will become necessary at some point because support for YEAR data types with display values other than 4 most notably YEAR 2 is reduced as of MySQL 5 6 6 and will be removed entirely in a future release YEAR 2 Limitations Issues with the YEAR 2 data type include ambiguity of displayed values and possible loss of information when val...

Страница 863: ...mn to produce exactly two digits Code that does not account for different handling for inserts of numeric 0 Inserting 0 into YEAR 2 or YEAR 4 results in an internal value of 2000 or 0000 respectively 11 1 5 5 Automatic Initialization and Updating for TIMESTAMP Note In older versions of MySQL prior to 4 1 the properties of the TIMESTAMP data type differed significantly in several ways from what is ...

Страница 864: ...te values specified for example as 0 0000 00 00 00 00 00 to be rejected Be aware that the TRADITIONAL 540 SQL mode includes NO_ZERO_DATE 538 The following rules describe the possibilities for defining the first TIMESTAMP column in a table with the current timestamp for both the default and auto update values for one but not the other or for neither With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE...

Страница 865: ...finitions CREATE TABLE t1 ts1 TIMESTAMP DEFAULT 0 ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP CREATE TABLE t2 ts1 TIMESTAMP NULL ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP CREATE TABLE t3 ts1 TIMESTAMP NULL DEFAULT 0 ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP The tables have these properties In each table definition the firs...

Страница 866: ... example INSERT INTO t1 VALUES NOW INSERT INTO t2 VALUES CURRENT_TIMESTAMP 11 1 5 6 Fractional Seconds in Time Values A trailing fractional seconds part is permissible for temporal values in contexts such as literal values and in the arguments to or return values from some temporal functions Example mysql SELECT MICROSECOND 2010 12 10 14 12 09 019473 MICROSECOND 2010 12 10 14 12 09 019473 19473 Ho...

Страница 867: ... CURTIME 0 CURTIME CURTIME 0 10 41 36 104136 000000 mysql SELECT NOW NOW 0 NOW NOW 0 2007 11 30 10 41 47 20071130104147 000000 Before MySQL 5 0 8 the conversion results in an integer value with no microseconds part 11 1 5 8 Two Digit Years in Dates Date values with two digit years are ambiguous because the century is unknown Such values must be interpreted into four digit form because MySQL stores...

Страница 868: ...ore than 255 bytes If strict SQL mode is not enabled and you assign a value to a CHAR or VARCHAR column that exceeds the column s maximum length the value is truncated to fit and a warning is generated For truncation of nonspace characters you can cause an error to occur rather than a warning and suppress insertion of the value by using strict SQL mode See Section 5 1 7 Server SQL Modes For VARCHA...

Страница 869: ...pe PADSPACE This means that all CHAR VARCHAR and TEXT values in MySQL are compared without regard to any trailing spaces Comparison in this context does not include the LIKE 896 pattern matching operator for which trailing spaces are significant For example mysql CREATE TABLE names myname CHAR 10 Query OK 0 rows affected 0 03 sec mysql INSERT INTO names VALUES Monty Query OK 1 row affected 0 00 se...

Страница 870: ...a warning and suppress insertion of the value by using strict SQL mode See Section 5 1 7 Server SQL Modes When BINARY values are stored they are right padded with the pad value to the specified length The pad value and how it is handled is version specific As of MySQL 5 0 15 the pad value is 0x00 the zero byte Values are right padded with 0x00 on insert and no trailing bytes are removed on select ...

Страница 871: ...s TEXT values are treated as nonbinary strings character strings They have a character set and values are sorted and compared based on the collation of the character set If strict SQL mode is not enabled and you assign a value to a BLOB or TEXT column that exceeds the column s maximum length the value is truncated to fit and a warning is generated For truncation of nonspace characters you can caus...

Страница 872: ...actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers You can change the message buffer size by changing the value of the max_allowed_packet 466 variable but you must do so for both the server and your client program For example both mysql and mysqldump enable you to change the client side max_allowed_packet 4...

Страница 873: ... the numeric value 0 More about this later If strict SQL mode is enabled attempts to insert invalid ENUM values result in an error If an ENUM column is declared to permit NULL the NULL value is a legal value for the column and the default value is NULL If an ENUM column is declared NOT NULL its default value is the first element of the list of permitted values Each enumeration value has an index V...

Страница 874: ...ore 2 it matches an enumeration value so it is stored as 2 If you store 3 it does not match any enumeration value so it is treated as an index and becomes 2 the value with index 3 mysql INSERT INTO t numbers VALUES 2 2 3 mysql SELECT FROM t numbers 1 2 2 ENUM values are sorted according to the order in which the enumeration members were listed in the column specification In other words ENUM values...

Страница 875: ...ue For example you can retrieve numeric values from a SET column like this mysql SELECT set_col 0 FROM tbl_name If a number is stored into a SET column the bits that are set in the binary representation of the number determine the set members in the column value For a column specified as SET a b c d the members have the following decimal and binary values SET Member Decimal Value Binary Value a 1 ...

Страница 876: ...SET value set_col 0 mysql SELECT FROM tbl_name WHERE set_col LIKE value The first statement finds rows where set_col contains the value set member The second is similar but not the same It finds rows where set_col contains value anywhere even as a substring of another set member The following statements also are legal mysql SELECT FROM tbl_name WHERE set_col 1 mysql SELECT FROM tbl_name WHERE set_...

Страница 877: ...finition includes no explicit DEFAULT value MySQL determines the default value as follows If the column can take NULL as a value the column is defined with an explicit DEFAULT NULL clause This is the same as before 5 0 2 If the column cannot take NULL as the value MySQL defines the column with no explicit DEFAULT clause Exception If the column is defined as part of a PRIMARY KEY but not explicitly...

Страница 878: ... buffer Different storage engines handle the allocation and storage of this data in different ways according to the method they use for handling the corresponding types For more information see Chapter 14 Storage Engines and Section E 7 4 Limits on Table Column Count and Row Size Important For tables using the NDBCLUSTER storage engine there is the factor of 4 byte alignment to be taken into accou...

Страница 879: ... DOUBLE PRECISION REAL 8 bytes DECIMAL M D NUMERIC M D Varies see following discussion BIT M approximately M 7 8 bytes The storage requirements for DECIMAL and NUMERIC are version specific As of MySQL 5 0 3 values for DECIMAL columns are represented using a binary format that packs nine decimal base 10 digits into four bytes Storage for the integer and fractional parts of each value are determined...

Страница 880: ... MEDIUMTEXT value requires L bytes to store the value plus three bytes to store the length of the value To calculate the number of bytes used to store a particular CHAR VARCHAR or TEXT column value you must take into account the character set used for that column and whether the value contains multi byte characters In particular when using the utf8 Unicode character set you must keep in mind that ...

Страница 881: ...ored in the original table The other consists of any data in excess of 256 bytes which is stored in a hidden table The rows in this second table are always 2 000 bytes long This means that the size of a TEXT column is 256 if size 256 where size represents the size of the row otherwise the size is 256 size 2000 size 256 2000 The size of an ENUM object is determined by the number of different enumer...

Страница 882: ...INT INT8 BIGINT LONG VARBINARY MEDIUMBLOB LONG VARCHAR MEDIUMTEXT LONG MEDIUMTEXT MIDDLEINT MEDIUMINT NUMERIC DECIMAL Data type mapping occurs at table creation time after which the original type specifications are discarded If you create a table with types used by other vendors and then issue a DESCRIBE tbl_name statement MySQL reports the table structure using the equivalent MySQL types For exam...

Страница 883: ... 12 Encryption and Compression Functions 952 12 13 Information Functions 957 12 14 Miscellaneous Functions 964 12 15 Functions and Modifiers for Use with GROUP BY Clauses 968 12 15 1 GROUP BY Aggregate Functions 968 12 15 2 GROUP BY Modifiers 972 12 15 3 MySQL Extensions to GROUP BY 975 12 16 Spatial Extensions 976 12 16 1 Introduction to MySQL Spatial Support 976 12 16 2 The OpenGIS Geometry Mode...

Страница 884: ...it with the sql mode IGNORE_SPACE 422 option See Section 5 1 7 Server SQL Modes Individual client programs can request this behavior by using the CLIENT_IGNORE_SPACE option for mysql_real_connect In either case all function names become reserved words For the sake of brevity most examples in this chapter display the output from the mysql program in abbreviated form Rather than showing examples in ...

Страница 885: ...or each integer passed CHARACTER_LENGTH 887 A synonym for CHAR_LENGTH CHARSET 958 Return the character set of the argument COALESCE 878 Return the first non NULL argument COERCIBILITY 958 Return the collation coercibility value of the string argument COLLATION 959 Return the collation of the string argument COMPRESS 954 Return result as a binary string CONCAT_WS 888 Return concatenate with separat...

Страница 886: ...AULT 965 Return the default value for a table column DEGREES 909 Convert radians to degrees DES_DECRYPT 954 Decrypt a string DES_ENCRYPT 954 Encrypt a string DIV 907 Integer division 906 Division operator ELT 888 Return string at index number ENCODE 955 Encode a string ENCRYPT 955 Encrypt a string 876 NULL safe equal to operator 875 Equal operator EXP 910 Raise to the power of EXPORT_SET 888 Retur...

Страница 887: ...he index of the first occurrence of substring INTERVAL 879 Return the index of the argument that is less than the first argument IS_FREE_LOCK 966 Checks whether the named lock is free IS NOT NULL 877 NOT NULL value test IS NOT 876 Test a value against a boolean IS NULL 877 NULL value test IS_USED_LOCK 966 Checks whether the named lock is in use Return connection identifier if true IS 876 Test a va...

Страница 888: ...rn the maximum value MD5 955 Calculate MD5 checksum MICROSECOND 925 Return the microseconds from argument MID 891 Return a substring starting from the specified position MIN 971 Return the minimum value 906 Minus operator MINUTE 925 Return the minute from the argument MOD 911 Return the remainder or MOD 907 Modulo operator MONTH 925 Return the month from the date passed MONTHNAME 926 Return the na...

Страница 889: ...ring the specified number of times REPLACE 892 Replace occurrences of a specified string REVERSE 892 Reverse the characters in a string 951 Right shift RIGHT 892 Return the specified rightmost number of characters RLIKE 899 Synonym for REGEXP ROUND 913 Round the argument ROW_COUNT 963 The number of rows updated RPAD 892 Append string the specified number of times RTRIM 893 Remove trailing spaces S...

Страница 890: ...n returns the date or datetime expression with two arguments the sum of the arguments TIMESTAMPADD 929 Add an interval to a datetime expression TIMESTAMPDIFF 930 Subtract an interval from a datetime expression TO_DAYS 930 Return the date argument converted to days TRIM 894 Remove leading and trailing spaces TRUNCATE 914 Truncate to specified number of decimal places UCASE 895 Synonym for UPPER 906...

Страница 891: ... If one or both arguments are NULL the result of the comparison is NULL except for the NULL safe 876 equality comparison operator For NULL NULL the result is true No conversion is needed If both arguments in a comparison operation are strings they are compared as strings If both arguments are integers they are compared as integers Hexadecimal values are treated as binary strings if not compared to...

Страница 892: ... to floating point and from integer to floating point do not necessarily occur the same way The integer may be converted to floating point by the CPU whereas the string is converted digit by digit in an operation that involves floating point multiplications The results shown will vary on different systems and can be affected by factors such as computer architecture or the compiler version or optim...

Страница 893: ... test IS NOT 876 Test a value against a boolean IS NULL 877 NULL value test IS 876 Test a value against a boolean 951 Left shift 876 Less than or equal operator 876 Less than operator LIKE 896 Simple pattern matching 906 Minus operator or MOD 907 Modulo operator NOT BETWEEN AND 878 Check whether a value is not within a range of values 876 Not equal operator NOT LIKE 898 Negation of simple pattern ...

Страница 894: ...he meaning of some operators depends on the SQL mode By default 881 is a logical OR 881 operator With PIPES_AS_CONCAT 539 enabled 881 is string concatenation with a precedence between 951 and the unary operators By default 880 has a higher precedence than NOT as of MySQL 5 0 2 For earlier versions or from 5 0 2 on with HIGH_NOT_PRECEDENCE 536 enabled 880 and NOT have the same precedence See Sectio...

Страница 895: ...th numbers and strings Strings are automatically converted to numbers and numbers to strings as necessary The following relational comparison operators can be used to compare not only scalar operands but row operands For examples of row comparisons see Section 13 2 9 5 Row Subqueries Some of the functions in this section such as LEAST 879 and GREATEST 878 return values other than 1 TRUE 0 FALSE or...

Страница 896: ...CT 01 0 01 0 mysql SELECT zapp zappp 1 876 Less than or equal mysql SELECT 0 1 2 1 876 Less than mysql SELECT 2 2 0 876 Greater than or equal mysql SELECT 2 2 1 876 Greater than mysql SELECT 2 2 0 IS boolean_value 876 Tests a value against a boolean value where boolean_value can be TRUE FALSE or UNKNOWN mysql SELECT 1 IS TRUE 0 IS FALSE NULL IS UNKNOWN 1 1 1 IS boolean_value 876 syntax was added i...

Страница 897: ... Section 5 1 4 Server System Variables For DATE and DATETIME columns that are declared as NOT NULL you can find the special date 0000 00 00 by using a statement like this SELECT FROM tbl_name WHERE date_column IS NULL This is needed to get some ODBC applications to work because ODBC does not support a 0000 00 00 date value See Section 20 1 7 1 1 Obtaining Auto Increment Values and the description ...

Страница 898: ...f the values in the IN list else returns 0 If all values are constants they are evaluated according to the type of expr and sorted The search for the item then is done using a binary search This means IN is very quick if the IN value list consists entirely of constants Otherwise type conversion takes place according to the rules described in Section 12 2 Type Conversion in Expression Evaluation bu...

Страница 899: ...22 23 30 44 200 0 LEAST value1 value2 879 With two or more arguments returns the smallest minimum valued argument The arguments are compared using the following rules If the return value is used in an INTEGER context or all arguments are integer valued they are compared as integers If the return value is used in a REAL context or all arguments are real valued they are compared as reals If the argu...

Страница 900: ...ULL value to TRUE For example the following statements all assess to TRUE mysql SELECT 10 IS TRUE 1 mysql SELECT 10 IS TRUE 1 mysql SELECT string IS NOT NULL 1 NOT 880 880 Logical NOT Evaluates to 1 if the operand is 0 to 0 if the operand is nonzero and NOT NULL returns NULL mysql SELECT NOT 10 0 mysql SELECT NOT 0 1 mysql SELECT NOT NULL NULL mysql SELECT 1 1 0 mysql SELECT 1 1 1 The last example...

Страница 901: ...ent Operators Name Description 882 Assign a value as part of a SET statement or as part of the SET clause in an UPDATE statement 881 Assign a value 881 Assignment operator Causes the user variable on the left hand side of the operator to take on the value to its right The value on the right hand side may be a literal value another variable storing a value or any legal expression that yields a scal...

Страница 902: ...used in a SET statement is treated identically to 881 The value on the right hand side may be a literal value another variable storing a value or any legal expression that yields a scalar value including the result of a query provided that this value is a scalar value You can perform multiple assignments in the same SET statement In the SET clause of an UPDATE statement also acts as an assignment ...

Страница 903: ...a numeric context the result is returned as a decimal real or integer value Note The syntax of the CASE 883 expression shown here differs slightly from that of the SQL CASE statement described in Section 13 6 5 1 CASE Syntax for use inside stored programs The CASE statement cannot have an ELSE NULL clause and it is terminated with END CASE instead of END IF expr1 expr2 expr3 883 If expr1 is TRUE e...

Страница 904: ...TABLE tmp SELECT IFNULL 1 test AS test mysql DESCRIBE tmp Field Type Null Key Default Extra test varbinary 4 NO In this example the type of the test column is VARBINARY 4 NULLIF expr1 expr2 884 Returns NULL if expr1 expr2 is true otherwise returns expr1 This is the same as CASE WHEN expr1 expr2 THEN NULL ELSE expr1 END 883 mysql SELECT NULLIF 1 1 NULL mysql SELECT NULLIF 1 2 1 Note that MySQL eval...

Страница 905: ...OCATE 890 Return the position of the first occurrence of substring LOWER 890 Return the argument in lowercase LPAD 891 Return the string argument left padded with the specified string LTRIM 891 Remove leading spaces MAKE_SET 891 Return a set of comma separated strings that have the corresponding bit in bits set MATCH 934 Perform full text search MID 891 Return a substring starting from the specifi...

Страница 906: ...hat operate on string positions the first position is numbered 1 For functions that take length arguments noninteger arguments are rounded to the nearest integer ASCII str 886 Returns the numeric value of the leftmost character of the string str Returns 0 if str is the empty string Returns NULL if str is NULL ASCII 886 works for 8 bit characters mysql SELECT ASCII 2 50 mysql SELECT ASCII 2 50 mysq...

Страница 907: ...ch argument is interpreted modulo 256 so CHAR 256 886 and CHAR 256 256 886 both are equivalent to CHAR 0 886 CHAR_LENGTH str 887 Returns the length of the string str measured in characters A multi byte character counts as a single character This means that for a string containing five 2 byte characters LENGTH 890 returns 10 whereas CHAR_LENGTH 887 returns 5 CHARACTER_LENGTH str 887 CHARACTER_LENGT...

Страница 908: ... not set in the value you get an off string Bits in bits are examined from right to left from low order to high order bits Strings are added to the result from left to right separated by the separator string the default being the comma character The number of bits examined is given by number_of_bits which has a default of 64 if not specified number_of_bits is silently clipped to 64 if larger than ...

Страница 909: ... representation of the value of N treated as a longlong BIGINT number This is equivalent to CONV N 10 16 909 The inverse of this operation is performed by CONV HEX N 16 10 909 mysql SELECT 0x616263 HEX abc UNHEX HEX abc abc 616263 abc mysql SELECT HEX 255 CONV HEX 255 16 10 FF 255 INSERT str pos len newstr 889 Returns the string str with the substring beginning at position pos and len characters l...

Страница 910: ...ot be read because one of the preceding conditions is not satisfied the function returns NULL As of MySQL 5 0 19 the character_set_filesystem 442 system variable controls interpretation of file names that are given as literal strings mysql UPDATE t SET blob_col LOAD_FILE tmp picture WHERE id 1 LOCATE substr str 890 LOCATE substr str pos 890 The first syntax returns the position of the first occurr...

Страница 911: ...ng of the strings that have the corresponding bit in bits set str1 corresponds to bit 0 str2 to bit 1 and so on NULL values in str1 str2 are not appended to the result mysql SELECT MAKE_SET 1 a b c a mysql SELECT MAKE_SET 1 4 hello nice world hello world mysql SELECT MAKE_SET 1 4 hello nice NULL world hello mysql SELECT MAKE_SET 0 a b c MID str pos len 891 MID str pos len 891 is a synonym for SUBS...

Страница 912: ...eral strings and within the C API in Section 9 1 1 String Literals and Section 20 6 6 53 mysql_real_escape_string REPEAT str count 892 Returns a string consisting of the string str repeated count times If count is less than 1 returns an empty string Returns NULL if str or count are NULL mysql SELECT REPEAT MySQL 3 MySQLMySQLMySQL REPLACE str from_str to_str 892 Returns the string str with all occu...

Страница 913: ... A Z range are treated as vowels Important When using SOUNDEX 893 you should be aware of the following limitations This function as currently implemented is intended to work well with strings that are in the English language only Strings in other languages may not produce reliable results This function is not guaranteed to provide consistent results with strings that use multi byte character sets ...

Страница 914: ...G Quadratically 5 6 ratica mysql SELECT SUBSTRING Sakila 3 ila mysql SELECT SUBSTRING Sakila 5 3 aki mysql SELECT SUBSTRING Sakila FROM 4 FOR 2 ki This function is multi byte safe If len is less than 1 the result is the empty string SUBSTRING_INDEX str delim count 894 Returns the substring from string str before count occurrences of the delimiter delim If count is positive everything to the left o...

Страница 915: ...retrieval For example 41 is stored into a CHAR 3 column as 41 and retrieved as 41 with the trailing pad space stripped so UNHEX 895 for the column value returns A By contrast 41 is stored into a BINARY 3 column as 41 0 and retrieved as 41 0 with the trailing pad 0x00 byte not stripped 0 is not a legal hexadecimal digit so UNHEX 895 for the column value returns NULL For a numeric argument N the inv...

Страница 916: ... standard LIKE 896 performs matching on a per character basis thus it can produce results different from the 875 comparison operator mysql SELECT ä LIKE ae COLLATE latin1_german2_ci ä LIKE ae COLLATE latin1_german2_ci 0 mysql SELECT ä ae COLLATE latin1_german2_ci ä ae COLLATE latin1_german2_ci 1 In particular trailing spaces are significant which is not true for CHAR or VARCHAR comparisons perform...

Страница 917: ...d SQL LIKE 896 mysql SELECT 10 LIKE 1 1 Note Because MySQL uses C escape syntax in strings for example n to represent a newline character you must double any that you use in LIKE 896 strings For example to search for n specify it as n To search for specify it as this is because the backslashes are stripped once by the parser and again when the pattern match is made leaving a single backslash to be...

Страница 918: ...t test explicitly for NOT NULL using OR 881 and not AND 880 as shown here SELECT COUNT FROM foo WHERE bar NOT LIKE baz OR bar IS NULL STRCMP expr1 expr2 898 STRCMP 898 returns 0 if the strings are the same 1 if the first argument is smaller than the second according to the current sort order and 1 otherwise mysql SELECT STRCMP text text2 1 mysql SELECT STRCMP text2 text 1 mysql SELECT STRCMP text ...

Страница 919: ...me as NOT expr REGEXP pat expr REGEXP pat 899 expr RLIKE pat 899 Performs a pattern match of a string expression expr against a pattern pat The pattern can be an extended regular expression The syntax for regular expressions is discussed in Section 12 5 2 Regular Expressions Returns 1 if expr matches pat otherwise it returns 0 If either expr or pat is NULL the result is NULL RLIKE 899 is a synonym...

Страница 920: ... regular expression B an s matches any of the strings Bananas Baaaaas Bs and any other string starting with a B ending with an s and containing any number of a or n characters in between A regular expression for the REGEXP 899 operator may use any of the following special characters and constructs Match the beginning of a string mysql SELECT fo nfo REGEXP fo 0 mysql SELECT fofo REGEXP fo 1 Match t...

Страница 921: ...h n instances of a inclusive m and n must be in the range from 0 to RE_DUP_MAX default 255 inclusive If both m and n are given m must be less than or equal to n mysql SELECT abcde REGEXP a bcd 2 e 0 mysql SELECT abcde REGEXP a bcd 3 e 1 mysql SELECT abcde REGEXP a bcd 1 10 e 1 a dX a dX Matches any character that is or is not if is used either a b c d or X A character between two other characters ...

Страница 922: ...racter Name Character NUL 0 SOH 001 STX 002 ETX 003 EOT 004 ENQ 005 ACK 006 BEL 007 alert 007 BS 010 backspace b HT 011 tab t LF 012 newline n VT 013 vertical tab v FF 014 form feed f CR 015 carriage return r SO 016 SI 017 DLE 020 DC1 021 DC2 022 DC3 023 DC4 024 NAK 025 SYN 026 ETB 027 CAN 030 EM 031 SUB 032 ESC 033 IS4 034 FS 034 IS3 035 GS 035 IS2 036 RS 036 IS1 037 US 037 space exclamation mark...

Страница 923: ...ers of an equivalence class o and o are all synonymous An equivalence class may not be used as an endpoint of a range character_class Within a bracket expression written using and character_class represents a character class that matches all characters belonging to that class The following table lists the standard class names These names stand for the character classes defined in the ctype 3 manua...

Страница 924: ...owing regular expressions is the correct one mysql SELECT 1 2 REGEXP 1 2 0 mysql SELECT 1 2 REGEXP 1 2 0 mysql SELECT 1 2 REGEXP 1 2 1 12 6 Numeric Functions and Operators Table 12 10 Numeric Functions and Operators Name Description ABS 908 Return the absolute value ACOS 908 Return the arc cosine ASIN 908 Return the arc sine ATAN2 ATAN 908 Return the arc tangent of the two arguments ATAN 908 Retur...

Страница 925: ...ision 906 Division operator 906 Minus operator or MOD 907 Modulo operator 906 Addition operator 906 Multiplication operator 906 Change the sign of the argument The usual arithmetic operators are available The result is determined according to the following rules In the case of 906 906 and 906 the result is calculated with BIGINT 64 bit precision if both operands are integers If both operands are i...

Страница 926: ...rs apply to numbers For other types of values alternative operations may be available For example to add date values use DATE_ADD 919 see Section 12 7 Date and Time Functions 906 Addition mysql SELECT 3 5 8 906 Subtraction mysql SELECT 3 5 2 906 Unary minus This operator changes the sign of the operand mysql SELECT 2 2 Note If this operator is used with a BIGINT the return value is also a BIGINT T...

Страница 927: ...nt CONV 909 Convert numbers between different number bases COS 909 Return the cosine COT 909 Return the cotangent CRC32 909 Compute a cyclic redundancy check value DEGREES 909 Convert radians to degrees EXP 910 Raise to the power of FLOOR 910 Return the largest integer value not greater than the argument LN 910 Return the natural logarithm of the argument LOG10 911 Return the base 10 logarithm of ...

Страница 928: ...rns the arc sine of X that is the value whose sine is X Returns NULL if X is not in the range 1 to 1 mysql SELECT ASIN 0 2 0 20135792079033 mysql SELECT ASIN foo ASIN foo 0 1 row in set 1 warning 0 00 sec mysql SHOW WARNINGS Level Code Message Warning 1292 Truncated incorrect DOUBLE value foo ATAN X 908 Returns the arc tangent of X that is the value whose tangent is X mysql SELECT ATAN 2 1 1071487...

Страница 929: ... minimum base is 2 and the maximum base is 36 If to_base is a negative number N is regarded as a signed number Otherwise N is treated as unsigned CONV 909 works with 64 bit precision mysql SELECT CONV a 16 2 1010 mysql SELECT CONV 6E 18 8 172 mysql SELECT CONV 17 10 18 H mysql SELECT CONV 10 10 10 0xa 10 10 40 COS X 909 Returns the cosine of X where X is given in radians mysql SELECT COS PI 1 COT ...

Страница 930: ... can be used to obtain a hexadecimal representation of a decimal number or a string the manner in which it does so varies according to the argument s type See this function s description in Section 12 5 String Functions for details LN X 910 Returns the natural logarithm of X that is the base e logarithm of X If X is less than or equal to 0 then NULL is returned mysql SELECT LN 2 0 69314718055995 m...

Страница 931: ...10 100 2 mysql SELECT LOG10 100 NULL LOG10 X 911 is equivalent to LOG 10 X 910 MOD N M 911 N M 907 N MOD M 907 Modulo operation Returns the remainder of N divided by M mysql SELECT MOD 234 10 4 mysql SELECT 253 7 1 mysql SELECT MOD 29 9 2 mysql SELECT 29 MOD 9 2 This function is safe to use with BIGINT values MOD 911 also works on values that have a fractional part and returns the exact remainder ...

Страница 932: ...a repeatable sequence of column values In the following example note that the sequences of values produced by RAND 3 is the same both places where it occurs mysql CREATE TABLE t i INT Query OK 0 rows affected 0 42 sec mysql INSERT INTO t VALUES 1 2 3 Query OK 3 rows affected 0 00 sec Records 3 Duplicates 0 Warnings 0 mysql SELECT i RAND FROM t i RAND 1 0 61914388706828 2 0 93845168309142 3 0 83482...

Страница 933: ...tor It is a fast way to generate random numbers on demand that is portable between platforms for the same MySQL version ROUND X 913 ROUND X D 913 Rounds the argument X to D decimal places The rounding algorithm depends on the data type of X D defaults to 0 if not specified D can be negative to cause D digits left of the decimal point of the value X to become zero mysql SELECT ROUND 1 23 1 mysql SE...

Страница 934: ...value with any fractional part is rounded to the nearest even integer The following example shows how rounding differs for exact and approximate values mysql SELECT ROUND 2 5 ROUND 25E 1 ROUND 2 5 ROUND 25E 1 3 2 For more information see Section 12 17 Precision Math SIGN X 914 Returns the sign of the argument as 1 0 or 1 depending on whether X is negative zero or positive mysql SELECT SIGN 32 1 my...

Страница 935: ...ns Name Description ADDDATE 917 Add time values intervals to a date value ADDTIME 917 Add time CONVERT_TZ 918 Convert from one timezone to another CURDATE 918 Return the current date CURRENT_DATE CURRENT_DATE 918 Synonyms for CURDATE CURRENT_TIME CURRENT_TIME 918 Synonyms for CURTIME CURRENT_TIMESTAMP CURRENT_TIMESTAMP 918 Synonyms for NOW CURTIME 918 Return the current time DATE_ADD 919 Add time ...

Страница 936: ...Convert a string to a date SUBDATE 928 A synonym for DATE_SUB when invoked with three arguments SUBTIME 928 Subtract times SYSDATE 928 Return the time at which the function executes TIME_FORMAT 930 Format as time TIME_TO_SEC 930 Return the argument converted to seconds TIME 929 Extract the time portion of the expression passed TIMEDIFF 929 Subtract time TIMESTAMP 929 With a single argument this fu...

Страница 937: ... 10 6 MySQL Server Time Zone Support Some date functions can be used with zero dates or incomplete dates such as 2001 11 00 whereas others cannot Functions that extract parts of dates typically work with incomplete dates and thus can return 0 when you might otherwise expect a nonzero value For example mysql SELECT DAYOFMONTH 2001 11 00 MONTH 2005 00 00 0 0 Other functions expect complete dates and...

Страница 938: ...f you intend to use CONVERT_TZ 918 while other tables are locked with LOCK TABLES you must also lock the mysql time_zone_name table CURDATE 918 Returns the current date as a value in YYYY MM DD or YYYYMMDD format depending on whether the function is used in a string or numeric context mysql SELECT CURDATE 2008 06 13 mysql SELECT CURDATE 0 20080613 CURRENT_DATE 918 CURRENT_DATE 918 CURRENT_DATE 918...

Страница 939: ...e interpreted The INTERVAL keyword and the unit specifier are not case sensitive The following table shows the expected form of the expr argument for each unit value unit Value Expected expr Format MICROSECOND MICROSECONDS SECOND SECONDS MINUTE MINUTES HOUR HOURS DAY DAYS WEEK WEEKS MONTH MONTHS QUARTER QUARTERS YEAR YEARS SECOND_MICROSECOND SECONDS MICROSECONDS MINUTE_MICROSECOND MINUTES SECONDS ...

Страница 940: ...TE_ADD 2100 12 31 23 59 59 INTERVAL 1 1 MINUTE_SECOND 2101 01 01 00 01 00 mysql SELECT DATE_SUB 2005 01 01 00 00 00 INTERVAL 1 1 1 1 DAY_SECOND 2004 12 30 22 58 59 mysql SELECT DATE_ADD 1900 01 01 00 00 00 INTERVAL 1 10 DAY_HOUR 1899 12 30 14 00 00 mysql SELECT DATE_SUB 1998 01 02 INTERVAL 31 DAY 1997 12 02 mysql SELECT DATE_ADD 1992 12 31 23 59 59 000002 INTERVAL 1 999999 SECOND_MICROSECOND 1993 ...

Страница 941: ...s adjusted to the maximum days in the new month mysql SELECT DATE_ADD 2009 01 30 INTERVAL 1 MONTH 2009 02 28 Date arithmetic operations require complete dates and do not work with incomplete dates such as 2006 07 00 or badly malformed dates mysql SELECT DATE_ADD 2006 07 00 INTERVAL 1 DAY NULL mysql SELECT 2005 03 32 INTERVAL 1 MONTH NULL DATE_FORMAT date format 921 Formats the date value according...

Страница 942: ...ermits the storing of incomplete dates such as 2014 00 00 As of MySQL 5 0 25 the language used for day and month names and abbreviations is controlled by the value of the lc_time_names 462 system variable Section 10 7 MySQL Server Locale Support As of MySQL 5 0 36 DATE_FORMAT 921 returns a string with a character set and collation given by character_set_connection 442 and collation_connection 443 ...

Страница 943: ...rs as DATE_ADD 919 or DATE_SUB 922 but extracts parts from the date rather than performing date arithmetic mysql SELECT EXTRACT YEAR FROM 2009 07 02 2009 mysql SELECT EXTRACT YEAR_MONTH FROM 2009 07 02 01 02 03 200907 mysql SELECT EXTRACT DAY_MINUTE FROM 2009 07 02 01 02 03 20102 mysql SELECT EXTRACT MICROSECOND FROM 2003 01 02 10 30 00 000123 123 FROM_DAYS N 923 Given a day number N returns a DAT...

Страница 944: ...ngs for the specifiers used see the table in the DATE_FORMAT 921 function description ISO format refers to ISO 9075 not ISO 8601 Function Call Result GET_FORMAT DATE USA 924 m d Y GET_FORMAT DATE JIS 924 Y m d GET_FORMAT DATE ISO 924 Y m d GET_FORMAT DATE EUR 924 d m Y GET_FORMAT DATE INTERNAL 924 Y m d GET_FORMAT DATETIME USA 924 Y m d H i s GET_FORMAT DATETIME JIS 924 Y m d H i s GET_FORMAT DATE...

Страница 945: ... values dayofyear must be greater than 0 or the result is NULL mysql SELECT MAKEDATE 2011 31 MAKEDATE 2011 32 2011 01 31 2011 02 01 mysql SELECT MAKEDATE 2011 365 MAKEDATE 2014 365 2011 12 31 2014 12 31 mysql SELECT MAKEDATE 2011 0 NULL MAKETIME hour minute second 925 Returns a time value calculated from the hour minute and second arguments mysql SELECT MAKETIME 12 15 30 12 15 30 MICROSECOND expr ...

Страница 946: ...ySQL 5 0 12 mysql SELECT NOW SLEEP 2 NOW NOW SLEEP 2 NOW 2006 04 12 13 47 36 0 2006 04 12 13 47 36 mysql SELECT SYSDATE SLEEP 2 SYSDATE SYSDATE SLEEP 2 SYSDATE 2006 04 12 13 47 44 0 2006 04 12 13 47 46 In addition the SET TIMESTAMP statement affects the value returned by NOW 926 but not by SYSDATE 928 This means that timestamp settings in the binary log have no effect on invocations of SYSDATE 928...

Страница 947: ...e extracted from str is illegal STR_TO_DATE 927 returns NULL and as of MySQL 5 0 3 produces a warning The server scans str attempting to match format to it The format string can contain literal characters and format specifiers beginning with Literal characters in format must match literally in str Format specifiers in format must match a date or time part in str For the specifiers that can be used...

Страница 948: ...2 INTERVAL 31 DAY 2007 12 02 The second form enables the use of an integer value for days In such cases it is interpreted as the number of days to be subtracted from the date or datetime expression expr mysql SELECT SUBDATE 2008 01 02 12 00 00 31 2007 12 02 12 00 00 SUBTIME expr1 expr2 928 SUBTIME 928 returns expr1 expr2 expressed as a value in the same format as expr1 expr1 is a time or datetime ...

Страница 949: ... the range allowed for TIME values Alternatively you can use either of the functions TIMESTAMPDIFF 930 and UNIX_TIMESTAMP 931 both of which return integers mysql SELECT TIMEDIFF 2000 01 01 00 00 00 2000 01 01 00 00 00 000001 00 00 00 000001 mysql SELECT TIMEDIFF 2008 12 31 23 59 59 000001 2008 12 30 01 01 01 000002 46 58 57 999999 TIMESTAMP expr 929 TIMESTAMP expr1 expr2 929 With a single argument...

Страница 950: ...he date or datetime arguments for this function is the opposite of that used with the TIMESTAMP 929 function when invoked with 2 arguments TIME_FORMAT time format 930 This is used like the DATE_FORMAT 921 function but the format string may contain format specifiers only for hours minutes seconds and microseconds Other specifiers produce a NULL value or 0 If the time value contains an hour part tha...

Страница 951: ...ESTAMP 931 UNIX_TIMESTAMP date 931 If called with no argument returns a Unix timestamp seconds since 1970 01 01 00 00 00 UTC as an unsigned integer If UNIX_TIMESTAMP 931 is called with a date argument it returns the value of the argument as seconds since 1970 01 01 00 00 00 UTC date may be a DATE string a DATETIME string a TIMESTAMP or a number in the format YYMMDD or YYYYMMDD The server interpret...

Страница 952: ...he current UTC time as a value in HH MM SS or HHMMSS uuuuuu format depending on whether the function is used in a string or numeric context mysql SELECT UTC_TIME UTC_TIME 0 18 07 53 180753 000000 UTC_TIMESTAMP 932 UTC_TIMESTAMP 932 Returns the current UTC date and time as a value in YYYY MM DD HH MM SS or YYYYMMDDHHMMSS uuuuuu format depending on whether the function is used in a string or numeric...

Страница 953: ...nstead because we want the function to return the week number in the given year This makes use of the WEEK 932 function reliable when combined with other functions that extract a date part from a date If you would prefer the result to be evaluated with respect to the year that contains the first day of the week for the given date use 0 2 5 or 7 as the optional mode argument mysql SELECT WEEK 2000 ...

Страница 954: ...a proleptic Gregorian calendar This is what is used by MySQL as is required by standard SQL For this reason dates prior to the cutover stored as MySQL DATE or DATETIME values must be adjusted to compensate for the difference It is important to realize that the cutover did not occur at the same time in all countries and that the later it happened the more days were lost For example in Great Britain...

Страница 955: ... second search The WITH QUERY EXPANSION modifier specifies a query expansion search For more information see Section 12 9 3 Full Text Searches with Query Expansion Constraints on full text searching are listed in Section 12 9 5 Full Text Restrictions The myisam_ftdump utility can be used to dump the contents of a full text index This may be helpful for debugging full text queries See Section 4 6 2...

Страница 956: ... if the search matches few rows otherwise the second may be faster because it would read many rows anyway For natural language full text searches it is a requirement that the columns named in the MATCH 934 function be the same columns included in some FULLTEXT index in your table For the preceding query note that the columns named in the MATCH 934 function title and body are the same as those name...

Страница 957: ... word begins or ends To be able to add words or other indexed terms in such languages to a FULLTEXT index you must preprocess them so that they are separated by some arbitrary delimiter such as Some words are ignored in full text searches Any word that is too short is ignored The default minimum length of words that are found by full text searches is four characters Words in the stopword list are ...

Страница 958: ...s MySQL can perform boolean full text searches using the IN BOOLEAN MODE modifier With this modifier certain characters have special meaning at the beginning or end of words in the search string In the following query the and operators indicate that a word is required to be present or absent respectively for a match to occur Thus the query retrieves all the rows that contain the word MySQL but tha...

Страница 959: ... wildcard operator Unlike the other operators it should be appended to the word to be affected Words match if they begin with the word preceding the operator If a word is specified with the truncation operator it is not stripped from a boolean query even if it is too short as determined from the ft_min_word_len 452 setting or a stopword This occurs because the word is not seen as too short or a st...

Страница 960: ...s Find rows that contain the exact phrase some words for example rows that contain some words of wisdom but not some noise words Note that the characters that enclose the phrase are operator characters that delimit the phrase They are not the quotation marks that enclose the search string itself 12 9 3 Full Text Searches with Query Expansion Full text search supports query expansion and in particu...

Страница 961: ...ched for full text queries using the server character set and collation the values of the character_set_server and collation_server system variables False hits or misses may occur for stopword lookups if the stopword file or columns used for full text indexing or searches have a character set or collation different from character_set_server or collation_server Case sensitivity of stopword lookups ...

Страница 962: ... first five followed following follows for former formerly forth four from further furthermore get gets getting given gives go goes going gone got gotten greetings had hadn t happens hardly has hasn t have haven t having he he s hello help hence her here here s hereafter hereby herein hereupon hers herself hi him himself his hither hopefully how howbeit however i d i ll i m i ve ie if ignored imme...

Страница 963: ...g seems seen self selves sensible sent serious seriously seven several shall she should shouldn t since six so some somebody somehow someone something sometime sometimes somewhat somewhere soon sorry specified specify specifying still sub such sup sure t s take taken tell tends th than thank thanks thanx that that s thats the their theirs them themselves then thence there there s thereafter thereb...

Страница 964: ... use the same character set and collation The MATCH 934 column list must match exactly the column list in some FULLTEXT index definition for the table unless this MATCH 934 is IN BOOLEAN MODE Boolean mode searches can be done on nonindexed columns although they are likely to be slow The argument to AGAINST must be a string value that is constant during query evaluation This rules out for example a...

Страница 965: ...mined by the particular weighting scheme chosen To disable it look for the following line in myisam ftdefs h define GWS_IN_USE GWS_PROB Change that line to this define GWS_IN_USE GWS_FREQ Then recompile MySQL There is no need to rebuild the indexes in this case Note By making this change you severely decrease MySQL s ability to provide adequate relevance values for the MATCH 934 function If you re...

Страница 966: ...se parameters are known only by the server They are not stored in MyISAM index files To avoid the problem if you have modified the minimum or maximum word length or stopword file values used by the server specify the same ft_min_word_len 452 ft_max_word_len 452 and ft_stopword_file 453 values for myisamchk that you use for mysqld For example if you have set the minimum word length to 3 you can rep...

Страница 967: ...lowing array this is the element in the fourth row down third value from the end ctype map 00 20 20 20 20 20 20 20 20 20 28 28 28 28 28 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 48 10 10 10 10 10 10 10 10 10 10 10 10 01 10 10 84 84 84 84 84 84 84 84 84 84 10 10 10 10 10 10 10 81 81 81 81 81 81 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 10 10 10 10 10 10 82 82 82 82 82 ...

Страница 968: ...ificant mysql SELECT a A 1 mysql SELECT BINARY a A 0 mysql SELECT a a 1 mysql SELECT BINARY a a 0 In a comparison BINARY 948 affects the entire operation it can be given before either operand with the same result BINARY str 948 is shorthand for CAST str AS BINARY 948 Note that in some contexts if you cast an indexed column to BINARY MySQL is not able to use the index efficiently CAST expr AS type ...

Страница 969: ...value to a nonbinary string Comparisons of the result use the string collation For example if the character set of the result has a case insensitive collation a LIKE 896 operation is not case sensitive SELECT A LIKE CONVERT blob_col USING latin1 FROM tbl_name To use a different character set substitute its name for latin1 in the preceding statement To specify a particular collation for the convert...

Страница 970: ...c with both signed and unsigned 64 bit values If you are using numeric operators such as 906 or 906 and one of the operands is an unsigned integer the result is unsigned by default see Section 12 6 1 Arithmetic Operators You can override this by using the SIGNED or UNSIGNED cast operator to cast a value to a signed or unsigned 64 bit integer respectively mysql SELECT CAST 1 2 AS UNSIGNED 184467440...

Страница 971: ...LECT 1 0 1 mysql SELECT 11 3 8 The result is an unsigned 64 bit integer 951 Shifts a longlong BIGINT number to the left mysql SELECT 1 2 4 The result is an unsigned 64 bit integer The value is truncated to 64 bits In particular if the shift count is greater or equal to the width of an unsigned 64 bit number the result is zero 951 Shifts a longlong BIGINT number to the right mysql SELECT 4 2 1 The ...

Страница 972: ...inary string data type This will avoid potential problems with trailing space removal or character set conversion that would change data values such as may occur if you use a nonbinary string data type CHAR VARCHAR TEXT For functions such as MD5 or SHA1 that return a string of hex digits the return value cannot be converted to uppercase or compared in case insensitive fashion as is You must conver...

Страница 973: ...es on the server side AES_DECRYPT crypt_str key_str 953 This function decrypts data using the official AES Advanced Encryption Standard algorithm For more information see the description of AES_ENCRYPT 953 AES_ENCRYPT str key_str 953 AES_ENCRYPT 953 and AES_DECRYPT 953 enable encryption and decryption of data using the official AES Advanced Encryption Standard algorithm previously known as Rijndae...

Страница 974: ... DES_DECRYPT crypt_str key_str 954 Decrypts a string encrypted with DES_ENCRYPT 954 If an error occurs this function returns NULL This function works only if MySQL has been configured with SSL support See Section 6 3 6 Using SSL for Secure Connections If no key_str argument is given DES_DECRYPT 954 examines the first byte of the encrypted string to determine the DES key number that was used to enc...

Страница 975: ...ted_credit_card DES_ENCRYPT credit_card_number ENCODE str pass_str 955 Encrypt str using pass_str as the password To decrypt the result use DECODE 954 The result is a binary string of the same length as str The strength of the encryption is based on how good the random generator is It should suffice for short strings ENCRYPT str salt 955 Encrypts str using the Unix crypt system call and returns a ...

Страница 976: ... system variable mysql SET old_passwords 0 mysql SELECT PASSWORD mypass PASSWORD mypass 6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 mysql SET old_passwords 1 mysql SELECT PASSWORD mypass PASSWORD mypass 6f8c114b58f2ce9e If old_passwords 1 PASSWORD str 956 returns the same value as OLD_PASSWORD str 956 For descriptions of the permitted values of old_passwords 480 see Section 5 1 4 Server System Variab...

Страница 977: ...ny string any string mysql SELECT UNCOMPRESS any string NULL UNCOMPRESSED_LENGTH compressed_string 957 Returns the length that the compressed string had before being compressed mysql SELECT UNCOMPRESSED_LENGTH COMPRESS REPEAT a 30 30 12 13 Information Functions Table 12 17 Information Functions Name Description BENCHMARK 957 Repeatedly execute an expression CHARSET 958 Return the character set of ...

Страница 978: ... N expr in terms of the amount of overhead involved The two have very different execution profiles and you should not expect them to take the same amount of time The former involves the parser optimizer table locking and runtime evaluation N times each The latter involves only runtime evaluation N times and all the other components just once Memory structures already allocated are reused and runti...

Страница 979: ...onnected clients mysql SELECT CONNECTION_ID 23786 CURRENT_USER 959 CURRENT_USER 959 Returns the user name and host name combination for the MySQL account that the server used to authenticate the current client This account determines your access privileges The return value is a string in the utf8 character set The value of CURRENT_USER 959 can differ from the value of USER 964 mysql SELECT USER da...

Страница 980: ...een written without the LIMIT clause In the absence of the SQL_CALC_FOUND_ROWS option in the most recent successful SELECT statement FOUND_ROWS 960 returns the number of rows in the result set returned by that statement If the statement includes a LIMIT clause FOUND_ROWS 960 returns the number of rows up to the limit For example FOUND_ROWS 960 returns 10 or 60 respectively if the statement include...

Страница 981: ...SERT ON DUPLICATE KEY UPDATE Syntax The currently executing statement does not affect the value of LAST_INSERT_ID 961 Suppose that you generate an AUTO_INCREMENT value with one statement and then refer to LAST_INSERT_ID 961 in a multiple row INSERT statement that inserts rows into a table with its own AUTO_INCREMENT column The value of LAST_INSERT_ID 961 will remain stable in the second statement ...

Страница 982: ...t is not NULL and not 0 Important If you insert multiple rows using a single INSERT statement LAST_INSERT_ID 961 returns the value generated for the first inserted row only The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server For example mysql USE test Database changed mysql CREATE TABLE t id INT AUTO_INCREMENT NOT NULL PRIMARY KEY name...

Страница 983: ...t automatically generated value It is multi user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement or mysql_insert_id without affecting or being affected by other clients that generate their own sequence values Note that mysql_insert_id is only updated after INSERT and UPDATE statements so you cannot use the C API function to re...

Страница 984: ...haracter set mysql SELECT USER davida localhost The value indicates the user name you specified when connecting to the server and the client host from which you connected The value can be different from that of CURRENT_USER 959 You can extract only the user name part like this mysql SELECT SUBSTRING_INDEX USER 1 davida VERSION 964 Returns a string that indicates the MySQL server version The string...

Страница 985: ...if the attempt timed out for example because another client has previously locked the name or NULL if an error occurred such as running out of memory or the thread was killed with mysqladmin kill If you have a lock obtained with GET_LOCK 965 it is released when you execute RELEASE_LOCK 967 execute a new GET_LOCK 965 or your connection terminates either normally or abnormally Locks obtained with GE...

Страница 986: ...rm IP addresses such as 127 1 as a representation of 127 0 0 1 Because of this INET_ATON 966 a should not be used for such addresses Note To store values generated by INET_ATON 966 use an INT UNSIGNED column rather than INT which is signed If you use a signed column values corresponding to IP addresses for which the first octet is greater than 127 cannot be stored correctly See Section 11 1 4 6 Ou...

Страница 987: ...obtained with GET_LOCK 965 Returns 1 if the lock was released 0 if the lock was not established by this thread in which case the lock is not released and NULL if the named lock did not exist The lock does not exist if it was never obtained by a call to GET_LOCK 965 or if it has previously been released The DO statement is convenient to use with RELEASE_LOCK 967 See Section 13 2 3 DO Syntax SLEEP d...

Страница 988: ...TE clause to refer to column values from the INSERT portion of the statement In other words VALUES col_name in the UPDATE clause refers to the value of col_name that would be inserted had no duplicate key conflict occurred This function is especially useful in multiple row inserts The VALUES 968 function is meaningful only in the ON DUPLICATE KEY UPDATE clause of INSERT statements and returns NULL...

Страница 989: ...aracter To work around this problem convert to numeric units perform the aggregate operation and convert back to a temporal value Examples SELECT SEC_TO_TIME SUM TIME_TO_SEC time_col FROM tbl_name SELECT FROM_DAYS SUM TO_DAYS date_col FROM tbl_name Functions such as SUM 972 or AVG 969 that expect a numeric argument cast the argument to a number if necessary For SET or ENUM values the cast operatio...

Страница 990: ...sactions may be occurring each of which may affect the count COUNT DISTINCT expr expr 970 Returns a count of the number of rows with different non NULL expr values COUNT DISTINCT 970 returns 0 if there were no matching rows mysql SELECT COUNT DISTINCT results FROM student In MySQL you can obtain the number of distinct expression combinations that do not contain NULL by giving a list of expressions...

Страница 991: ...ns the maximum value of expr MAX 971 may take a string argument in such cases it returns the maximum string value See Section 8 5 3 How MySQL Uses Indexes The DISTINCT keyword can be used to find the maximum of the distinct values of expr however this produces the same result as omitting DISTINCT MAX 971 returns NULL if there were no matching rows mysql SELECT student_name MIN test_score MAX test_...

Страница 992: ...pr It considers rows as the whole population not as a sample so it has the number of rows as the denominator This function was added in MySQL 5 0 3 Before 5 0 3 you can use VARIANCE 972 which is equivalent but is not standard SQL VAR_POP 972 returns NULL if there were no matching rows VAR_SAMP expr 972 Returns the sample variance of expr That is the denominator is the number of rows minus one This...

Страница 993: ...uper aggregate line is identified by the value NULL in the year column ROLLUP has a more complex effect when there are multiple GROUP BY columns In this case each time there is a break change in value in any but the last grouping column the query produces an extra super aggregate summary row For example without ROLLUP a summary on the sales table based on year country and product might look like t...

Страница 994: ...g ROLLUP The following items list some behaviors specific to the MySQL implementation of ROLLUP When you use ROLLUP you cannot also use an ORDER BY clause to sort the results In other words ROLLUP and ORDER BY are mutually exclusive However you still have some control over sort order GROUP BY in MySQL sorts results and you can use explicit ASC and DESC keywords with columns named in the GROUP BY l...

Страница 995: ...ly when all values in each nonaggregated column not named in the GROUP BY are the same for each group The server is free to choose any value from each group so unless they are the same the values chosen are indeterminate Furthermore the selection of values from each group cannot be influenced by adding an ORDER BY clause Sorting of the result set occurs after values have been chosen and ORDER BY d...

Страница 996: ...storage and analysis of geographic features Before MySQL 5 0 16 these features are available for MyISAM tables only As of MySQL 5 0 16 InnoDB NDB BDB and ARCHIVE also support spatial features For spatial columns MyISAM supports both SPATIAL and non SPATIAL indexes Other storage engines support non SPATIAL indexes as described in Section 13 1 8 CREATE INDEX Syntax This chapter covers the following ...

Страница 997: ... location For example a crossroad as a particular place where two streets intersect Some documents use the term geospatial feature to refer to geographic features Geometry is another word that denotes a geographic feature Originally the word geometry meant measurement of the earth Another meaning comes from cartography referring to the geometric features that cartographers use to map the world Thi...

Страница 998: ... named MultiPoint MultiLineString and MultiPolygon for modeling geometries corresponding to collections of Points LineStrings and Polygons respectively MultiCurve and MultiSurface are introduced as abstract superclasses that generalize the collection interfaces to handle Curves and Surfaces Geometry Curve Surface MultiCurve and MultiSurface are defined as noninstantiable classes They define a comm...

Страница 999: ...termines its own assertions for being simple or nonsimple Whether the value is closed or not closed Geometry values of types LineString MultiString are either closed or not closed Each type determines its own assertions for being closed or not closed Whether the value is empty or nonempty A geometry is empty if it does not have any points Exterior interior and boundary of an empty geometry are not...

Страница 1000: ...epresent rivers In a city map LineString objects could represent streets LineString Properties A LineString has coordinates of segments defined by each consecutive pair of points A LineString is a Line if it consists of exactly two points A LineString is a LinearRing if it is both closed and simple 12 16 2 6 Class Surface A Surface is a two dimensional geometry It is a noninstantiable class Its on...

Страница 1001: ... Spatial Reference System that is in the same coordinate system There are no other constraints on the elements of a GeometryCollection although the subclasses of GeometryCollection described in the following sections may restrict membership Restrictions may be based on Element type for example a MultiPoint may contain only Point elements Dimension Constraints on the degree of spatial overlap betwe...

Страница 1002: ...Two MultiSurface elements have boundaries that intersect at most at a finite number of points 12 16 2 13 Class MultiPolygon A MultiPolygon is a MultiSurface object composed of Polygon elements MultiPolygon Examples On a region map a MultiPolygon could represent a system of lakes MultiPolygon Assertions A MultiPolygon has no two Polygon elements with interiors that intersect A MultiPolygon has no t...

Страница 1003: ...a This differs from the syntax for the SQL POINT 987 function which requires a comma between the coordinates Take care to use the syntax appropriate to the context of a given spatial operation For example the following statements both extract the X coordinate from a Point object The first produces the object directly using the POINT 987 function The second uses a WKT representation converted to a ...

Страница 1004: ...ay be either 1 or 0 to indicate little endian or big endian storage The little endian and big endian byte orders are also known as Network Data Representation NDR and External Data Representation XDR respectively The WKB type is a code that indicates the geometry type Values from 1 through 7 indicate Point LineString Polygon MultiPoint MultiLineString MultiPolygon and GeometryCollection A Point va...

Страница 1005: ...wkt srid 985 Constructs a GEOMETRYCOLLECTION value using its WKT representation and SRID GeomFromText wkt srid 985 GeometryFromText wkt srid 985 Constructs a geometry value of any type using its WKT representation and SRID LineFromText wkt srid 985 LineStringFromText wkt srid 985 Constructs a LINESTRING value using its WKT representation and SRID MLineFromText wkt srid 985 MultiLineStringFromText ...

Страница 1006: ...eomFromWKB wkb srid 986 GeometryFromWKB wkb srid 986 Constructs a geometry value of any type using its WKB representation and SRID LineFromWKB wkb srid 986 LineStringFromWKB wkb srid 986 Constructs a LINESTRING value using its WKB representation and SRID MLineFromWKB wkb srid 986 MultiLineStringFromWKB wkb srid 986 Constructs a MULTILINESTRING value using its WKB representation and SRID MPointFrom...

Страница 1007: ...RT INTO t1 pt_col VALUES Point 1 2 Prior to MySQL 5 0 82 convert the WKB return value to a Point before inserting it INSERT INTO t1 pt_col VALUES GeomFromWKB Point 1 2 GeometryCollection g1 g2 987 Constructs a GeometryCollection LineString pt1 pt2 987 Constructs a LineString value from a number of Point or WKB Point arguments If the number of arguments is less than two the return value is NULL Mul...

Страница 1008: ...r to the INSERT SET g GeomFromText POINT 1 1 INSERT INTO geom VALUES g The following examples insert more complex geometries into the table SET g LINESTRING 0 0 1 1 2 2 INSERT INTO geom VALUES GeomFromText g SET g POLYGON 0 0 10 0 10 10 0 10 0 0 5 5 7 5 7 7 5 7 5 5 INSERT INTO geom VALUES GeomFromText g SET g GEOMETRYCOLLECTION POINT 1 1 LINESTRING 0 0 1 1 2 2 3 3 4 4 INSERT INTO geom VALUES GeomF...

Страница 1009: ...ing SELECT AsText g FROM geom Fetching spatial data in WKB format The AsBinary 989 function converts a geometry from internal format into a BLOB containing the WKB value SELECT AsBinary g FROM geom 12 16 5 Spatial Analysis Functions After populating spatial columns with values you are ready to query and analyze them MySQL provides a set of functions to perform various operations on spatial data Th...

Страница 1010: ...ing Geometry Values Using WKB Functions 12 16 5 2 Geometry Property Functions Each function that belongs to this group takes a geometry value as its argument and returns some quantitative or qualitative property of the geometry Some functions restrict their argument type Such functions return NULL if the argument is of an incorrect geometry type For example Area 993 returns NULL if the object type...

Страница 1011: ...n also defines the following functions which MySQL does not implement Boundary g 991 Returns a geometry that is the closure of the combinatorial boundary of the geometry value g IsEmpty g 991 This function is a placeholder that returns 0 for any valid geometry value 1 for any invalid geometry value or NULL MySQL does not support GIS EMPTY values such as POINT EMPTY IsSimple g 991 In MySQL 5 0 this...

Страница 1012: ...omText ls POINT 3 3 GLength ls 992 Returns as a double precision number the length of the LineString value ls in its associated spatial reference mysql SET ls LineString 1 1 2 2 3 3 mysql SELECT GLength GeomFromText ls GLength GeomFromText ls 2 8284271247462 GLength 992 is a nonstandard name It corresponds to the OpenGIS Length 890 function NumPoints ls 992 Returns the number of Point objects in t...

Страница 1013: ... the MultiLineString value mls The length of mls is equal to the sum of the lengths of its elements mysql SET mls MultiLineString 1 1 2 2 3 3 4 4 5 5 mysql SELECT GLength GeomFromText mls GLength GeomFromText mls 4 2426406871193 GLength 992 is a nonstandard name It corresponds to the OpenGIS Length 890 function IsClosed mls 993 Returns 1 if the MultiLineString value mls is closed that is the Start...

Страница 1014: ...N GeomFromText poly 1 LINESTRING 1 1 1 2 2 2 2 1 1 1 NumInteriorRings poly 994 Returns the number of interior rings in the Polygon value poly mysql SET poly Polygon 0 0 0 3 3 3 3 0 0 0 1 1 1 2 2 2 2 1 1 1 mysql SELECT NumInteriorRings GeomFromText poly NumInteriorRings GeomFromText poly 1 12 16 5 2 6 MultiPolygon Functions These functions return properties of MultiPolygon values Area mpoly 993 Ret...

Страница 1015: ...metryCollection Point 1 1 LineString 2 2 3 3 mysql SELECT AsText GeometryN GeomFromText gc 1 AsText GeometryN GeomFromText gc 1 POINT 1 1 NumGeometries gc 995 Returns the number of geometries in the GeometryCollection value gc mysql SET gc GeometryCollection Point 1 1 LineString 2 2 3 3 mysql SELECT NumGeometries GeomFromText gc NumGeometries GeomFromText gc 2 12 16 5 3 Functions That Create New G...

Страница 1016: ...geometry that represents the point set union of the geometry values g1 and g2 12 16 5 4 Functions for Testing Spatial Relations Between Geometric Objects The functions described in these sections take two geometries as input parameters and return a qualitative or quantitative relation between them 12 16 5 4 1 Relations on Geometry Minimal Bounding Rectangles MBRs MySQL provides several functions t...

Страница 1017: ...ding Rectangle of g1 is within the Minimum Bounding Rectangle of g2 This tests the opposite relationship as MBRContains 996 mysql SET g1 GeomFromText Polygon 0 0 0 3 3 3 3 0 0 0 mysql SET g2 GeomFromText Polygon 0 0 0 5 5 5 5 0 0 0 mysql SELECT MBRWithin g1 g2 MBRWithin g2 g1 MBRWithin g1 g2 MBRWithin g2 g1 1 0 12 16 5 4 2 Functions That Test Spatial Relationships Between Geometries The OpenGIS sp...

Страница 1018: ...s in nonspatial databases can be optimized using SPATIAL indexes This is true for spatial databases as well With the help of a great variety of multi dimensional indexing methods that have previously been designed it is possible to optimize spatial searches The most typical of these are Point queries that search for all objects that contain a given point Region queries that search for all objects ...

Страница 1019: ... than 32 000 geometries which are stored in the column g of type GEOMETRY The table also has an AUTO_INCREMENT column fid for storing object ID values mysql DESCRIBE geom Field Type Null Key Default Extra fid int 11 PRI NULL auto_increment g geometry 2 rows in set 0 00 sec mysql SELECT COUNT FROM geom count 32376 1 row in set 0 00 sec To add a spatial index on the column g use this statement mysql...

Страница 1020: ...30263 15131 4 30 155 LINESTRING 30269 8 15084 30269 4 15093 4 30258 6 15093 30 157 LINESTRING 30128 2 15011 30113 2 15010 2 30113 6 15000 4 20 rows in set 0 00 sec Use EXPLAIN to check the way this query is executed mysql SET poly Polygon 30000 15000 31000 15000 31000 16000 30000 16000 30000 15000 mysql EXPLAIN SELECT fid AsText g FROM geom WHERE MBRContains GeomFromText poly g G 1 row id 1 select...

Страница 1021: ...ption of geometry columns one row for each geometry column in the database The OpenGIS function Length 890 on LineString and MultiLineString currently should be called in MySQL as GLength 992 The problem is that there is an existing SQL function Length 890 that calculates the length of string values and sometimes it is not possible to distinguish whether the function is called in a textual or spat...

Страница 1022: ... point number whereas 2 34E0 is an approximate value floating point number The DECIMAL data type is a fixed point type and calculations are exact In MySQL the DECIMAL type has several synonyms NUMERIC DEC FIXED The integer types also are exact value types The FLOAT and DOUBLE data types are floating point types and calculations are approximate In MySQL types that are synonymous with FLOAT or DOUBL...

Страница 1023: ...pplications that rely on the older behavior must be modified to account for this change The change of storage format also means that DECIMAL columns no longer support the nonstandard extension that permitted values larger than the range implied by the column definition Formerly 1 byte was allocated for storing the sign character For positive values that needed no sign byte MySQL permitted an extra...

Страница 1024: ... but not written as an exact number so 1 0 3 0 3 0 does not evaluate to exactly 1 0 Otherwise the expression contains only integer values The expression is exact and is evaluated using integer arithmetic and has a precision the same as BIGINT 64 bits If a numeric expression contains any strings they are converted to double precision floating point values and the expression is approximate Inserts i...

Страница 1025: ...than spaces this produces an error in strict mode or a warning otherwise 12 17 4 Rounding Behavior This section discusses precision math rounding for the ROUND 913 function and for inserts into columns with exact value types DECIMAL and integer The ROUND 913 function rounds differently depending on whether its argument is exact or approximate For exact value numbers ROUND 913 uses the round half u...

Страница 1026: ...s produce inexact results mysql SELECT 1 2 3 1 2 3 1 As of MySQL 5 0 3 numbers are used as given when possible mysql SELECT 1 2 3 1 2 3 1 For floating point values results are inexact mysql SELECT 1E0 2E0 3E0 1E0 2E0 3E0 0 Another way to see the difference in exact and approximate value handling is to add a small number to a sum many times Consider the following stored procedure which adds 0001 to...

Страница 1027: ...he implementation of the underlying C library This results in inconsistencies from platform to platform For example you might get a different value on Windows than on Linux or a different value on x86 machines than on PowerPC machines As of MySQL 5 0 3 rounding happens like this Rounding for exact value columns DECIMAL and integer and exact valued numbers uses the round half away from zero rule Va...

Страница 1028: ...536 set division by zero causes an error not a result of NULL Before MySQL 5 0 2 or when not using strict mode in 5 0 2 or a later version division by zero has a result of NULL mysql CREATE TABLE t i TINYINT Query OK 0 rows affected 0 01 sec mysql INSERT INTO t SET i 1 0 Query OK 1 row affected 0 00 sec mysql SELECT i FROM t i NULL 1 row in set 0 00 sec As of MySQL 5 0 2 division by zero is an err...

Страница 1029: ...RIBE t Field Type Null Key Default Extra a decimal 2 1 unsigned NO 0 0 b double NO 0 2 rows in set 0 02 sec Example 7 If the argument to an aggregate function is an exact numeric type the result is also an exact numeric type with a scale at least that of the argument Consider these statements mysql CREATE TABLE t i INT d DECIMAL f FLOAT mysql INSERT INTO t VALUES 1 1 1 mysql CREATE TABLE y SELECT ...

Страница 1030: ...Precision Math Examples 1010 AVG i decimal 14 4 YES NULL AVG d decimal 14 4 YES NULL AVG f double YES NULL From MySQL 5 0 3 to 5 0 6 the first two columns are DECIMAL 64 0 ...

Страница 1031: ...1059 13 2 2 DELETE Syntax 1060 13 2 3 DO Syntax 1064 13 2 4 HANDLER Syntax 1064 13 2 5 INSERT Syntax 1065 13 2 6 LOAD DATA INFILE Syntax 1072 13 2 7 REPLACE Syntax 1081 13 2 8 SELECT Syntax 1082 13 2 9 Subquery Syntax 1098 13 2 10 UPDATE Syntax 1108 13 3 MySQL Transactional and Locking Statements 1110 13 3 1 START TRANSACTION COMMIT and ROLLBACK Syntax 1110 13 3 2 Statements That Cannot Be Rolled ...

Страница 1032: ...he ALTER 576 privilege on the database ALTER SCHEMA is a synonym for ALTER DATABASE as of MySQL 5 0 2 The CHARACTER SET clause changes the default database character set The COLLATE clause changes the default database collation Section 10 1 Character Set Support discusses character set and collation names You can see what character sets and collations are available using respectively the SHOW CHAR...

Страница 1033: ...nd CREATE PROCEDURE As of MySQL 5 0 3 you must have the ALTER ROUTINE 576 privilege for the procedure By default that privilege is granted automatically to the procedure creator This behavior can be changed by disabling the automatic_sp_privileges 437 system variable See Section 18 2 2 Stored Routines and MySQL Privileges 13 1 4 ALTER TABLE Syntax ALTER IGNORE TABLE tbl_name alter_specification al...

Страница 1034: ...riginal table and renames the new one While ALTER TABLE is executing the original table is readable by other sessions Updates and writes to the table that begin after the ALTER TABLE operation begins are stalled until the new table is ready then are automatically redirected to the new table without any failed updates The temporary table is created in the database directory of the new table This ca...

Страница 1035: ...ot reset the counter to a value less than or equal to any that have already been used For MyISAM if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column the value is reset to the current maximum plus one For InnoDB you can use ALTER TABLE AUTO_INCREMENT value as of MySQL 5 0 3 but if the value is less than the current maximum value in the column no error occu...

Страница 1036: ...a table ALTER SET DEFAULT or ALTER DROP DEFAULT specify a new default value for a column or remove the old default value respectively If the old default is removed and the column can be NULL the new default is NULL If the column cannot be NULL MySQL assigns a default value as described in Section 11 1 7 Data Type Default Values DROP INDEX removes an index This is a MySQL extension to standard SQL ...

Страница 1037: ...indexes This feature can be activated explicitly for a MyISAM table ALTER TABLE DISABLE KEYS tells MySQL to stop updating nonunique indexes ALTER TABLE ENABLE KEYS then should be used to re create missing indexes MySQL does this with a special algorithm that is much faster than inserting keys one by one so disabling keys before performing bulk insert operations should give a considerable speedup U...

Страница 1038: ...ata type as necessary to ensure that the new column is long enough to store as many characters as the original column For example a TEXT column has two length bytes which store the byte length of values in the column up to a maximum of 65 535 For a latin1 TEXT column each character requires a single byte so the column can store up to 65 535 characters If the column is converted to utf8 each charac...

Страница 1039: ... from INTEGER to TINYINT NOT NULL leaving the name the same and to change column b from CHAR 10 to CHAR 20 as well as renaming it from b to c ALTER TABLE t2 MODIFY a TINYINT NOT NULL CHANGE b c CHAR 20 To add a new TIMESTAMP column named d ALTER TABLE t2 ADD d TIMESTAMP To add an index on column d and a UNIQUE index on column a ALTER TABLE t2 ADD INDEX d ADD UNIQUE a To remove column c ALTER TABLE...

Страница 1040: ...drop the original table and then rename the copy DROP t1 ALTER TABLE t2 RENAME t1 13 1 5 ALTER VIEW Syntax ALTER ALGORITHM UNDEFINED MERGE TEMPTABLE DEFINER user CURRENT_USER SQL SECURITY DEFINER INVOKER VIEW view_name column_list AS select_statement WITH CASCADED LOCAL CHECK OPTION This statement changes the definition of a view which must exist The syntax is similar to that for CREATE VIEW and t...

Страница 1041: ...nctions see Section 13 7 3 1 CREATE FUNCTION Syntax for User defined Functions 13 1 8 CREATE INDEX Syntax CREATE UNIQUE FULLTEXT SPATIAL INDEX index_name index_type ON tbl_name index_col_name index_type index_col_name col_name length ASC DESC index_type USING BTREE HASH CREATE INDEX is mapped to an ALTER TABLE statement to create indexes See Section 13 1 4 ALTER TABLE Syntax CREATE INDEX cannot be...

Страница 1042: ...es are supported only for MyISAM tables and can include only CHAR VARCHAR and TEXT columns Indexing always happens over the entire column column prefix indexing is not supported and any prefix length is ignored if specified See Section 12 9 Full Text Search Functions for details of operation The MyISAM InnoDB NDB BDB and ARCHIVE storage engines support spatial columns such as POINT and GEOMETRY Se...

Страница 1043: ...ation of an implicit ordered index otherwise creating a unique index or primary key on an NDB table automatically results in the creation of both an ordered index and a hash index each of which indexes the same set of columns This means that a query using a unique index or primary key on a NULL column is always handled by NDB with a full scan of the table In particular if you plan to use an IS NUL...

Страница 1044: ...UTINE 576 privilege They might also require the SUPER 578 privilege depending on the DEFINER value as described later in this section If binary logging is enabled CREATE FUNCTION might require the SUPER 578 privilege as described in Section 18 6 Binary Logging of Stored Programs By default MySQL automatically grants the ALTER ROUTINE 576 and EXECUTE 577 privileges to the routine creator This behav...

Страница 1045: ...delimiter mysql CREATE PROCEDURE simpleproc OUT param1 INT BEGIN SELECT COUNT INTO param1 FROM t END Query OK 0 rows affected 0 00 sec mysql delimiter mysql CALL simpleproc a Query OK 0 rows affected 0 00 sec mysql SELECT a a 3 1 row in set 0 00 sec The example uses the mysql client delimiter command to change the statement delimiter from to while the procedure is being defined This enables the de...

Страница 1046: ...mited exceptions They may include some SET statements that contain table references for example SET a SELECT MAX id FROM t and SELECT statements that fetch values directly into variables for example SELECT i INTO var1 FROM t USE statements within stored routines are not permitted When a routine is invoked an implicit USE db_name is performed and undone when the routine terminates This causes the r...

Страница 1047: ...in what kinds of statements a routine will be permitted to execute CONTAINS SQL indicates that the routine does not contain statements that read or write data This is the default if none of these characteristics is given explicitly Examples of such statements are SET x 1 or DO RELEASE_LOCK abc which execute but neither read nor write data NO SQL indicates that the routine contains no SQL statement...

Страница 1048: ...t PROCEDURE account_count SQL SECURITY INVOKER BEGIN SELECT Number of accounts COUNT FROM mysql user END The procedure still has a DEFINER of admin localhost but in this case it executes with the privileges of the invoking user Thus the procedure succeeds or fails depending on whether the invoker has the EXECUTE 577 privilege for it and the SELECT 578 privilege for the mysql user table As of MySQL...

Страница 1049: ...me index_type FULLTEXT SPATIAL INDEX KEY index_name index_col_name index_type CONSTRAINT symbol FOREIGN KEY index_name index_col_name reference_definition CHECK expr column_definition data_type NOT NULL NULL DEFAULT default_value AUTO_INCREMENT UNIQUE KEY PRIMARY KEY COMMENT string reference_definition data_type BIT length TINYINT length UNSIGNED ZEROFILL SMALLINT length UNSIGNED ZEROFILL MEDIUMIN...

Страница 1050: ...rectory DELAY_KEY_WRITE 0 1 INDEX DIRECTORY absolute path to directory INSERT_METHOD NO FIRST LAST MAX_ROWS value MIN_ROWS value PACK_KEYS 0 1 DEFAULT PASSWORD string ROW_FORMAT DEFAULT DYNAMIC FIXED COMPRESSED REDUNDANT COMPACT UNION tbl_name tbl_name select_statement IGNORE REPLACE AS SELECT Some legal select statement CREATE TABLE creates a table with the given name You must have the CREATE 576...

Страница 1051: ...k files File Purpose tbl_name frm Table format definition file tbl_name MYD Data file tbl_name MYI Index file Chapter 14 Storage Engines describes what files each storage engine creates to represent tables Data Types and Attributes for Columns data_type represents the data type in a column definition spatial_type represents a spatial data type The data type syntax shown is representative only For ...

Страница 1052: ...t it cannot be a function or an expression This means for example that you cannot set the default for a date column to be the value of a function such as NOW 926 or CURRENT_DATE 918 The exception is that you can specify CURRENT_TIMESTAMP 918 as the default for a TIMESTAMP column See Section 11 1 5 5 Automatic Initialization and Updating for TIMESTAMP If a column definition includes no explicit DEF...

Страница 1053: ...pe when creating an index The syntax for the index_type specifier is USING type_name Example CREATE TABLE lookup id INT INDEX USING BTREE id ENGINE MEMORY Before MySQL 5 0 60 USING can be given only before the index column list As of 5 0 60 the preferred position is after the column list Support for use of the option before the column list will be removed in a future MySQL release index_option val...

Страница 1054: ...13 1 10 2 Using FOREIGN KEY Constraints For information specific to foreign keys in InnoDB see Section 14 2 3 4 InnoDB and FOREIGN KEY Constraints For other storage engines MySQL Server parses and ignores the FOREIGN KEY and REFERENCES syntax in CREATE TABLE statements The CHECK clause is parsed but ignored by all storage engines See Section 1 8 5 4 Foreign Keys Important For users familiar with t...

Страница 1055: ... version you should convert any existing ISAM tables to MyISAM before performing the upgrade InnoDB Transaction safe tables with row locking and foreign keys See Section 14 2 The InnoDB Storage Engine MEMORY The data for this storage engine is stored only in memory See Section 14 4 The MEMORY HEAP Storage Engine MERGE A collection of MyISAM tables used as one table Also known as MRG_MyISAM See Sec...

Страница 1056: ...imit If you want to keep down the pointer sizes to make the index smaller and faster and you don t really need big files you can decrease the default pointer size by setting the myisam_data_pointer_size 473 system variable which was added in MySQL 4 1 2 See Section 5 1 4 Server System Variables If you want all your tables to be able to grow above the default limit and are willing to have your tabl...

Страница 1057: ...RGE table you must specify with INSERT_METHOD the table into which the row should be inserted INSERT_METHOD is an option useful for MERGE tables only Use a value of FIRST or LAST to have inserts go to the first or last table or a value of NO to prevent inserts See Section 14 3 The MERGE Storage Engine MAX_ROWS The maximum number of rows you plan to store in the table This is not a hard limit but r...

Страница 1058: ...d be stored For MyISAM tables the option value can be FIXED or DYNAMIC for static or variable length row format myisampack sets the type to COMPRESSED See Section 14 1 3 MyISAM Table Storage Formats Starting with MySQL 5 0 3 for InnoDB tables rows are stored in compact format ROW_FORMAT COMPACT by default The noncompact format used in older versions of MySQL can still be requested by specifying RO...

Страница 1059: ...f the table storage format as the original table The SELECT 578 privilege is required on the original table LIKE works only for base tables not for views CREATE TABLE LIKE does not preserve any DATA DIRECTORY or INDEX DIRECTORY table options that were specified for the original table or any foreign key definitions If the original table is a TEMPORARY table CREATE TABLE LIKE does not preserve TEMPO...

Страница 1060: ...t to have indexes in the created table you should specify these before the SELECT statement mysql CREATE TABLE bar UNIQUE n SELECT n FROM foo Some conversion of data types might occur For example the AUTO_INCREMENT attribute is not preserved and VARCHAR columns can become CHAR columns Retrained attributes are NULL or NOT NULL and for those columns that have them CHARACTER SET COLLATION COMMENT and...

Страница 1061: ...s like this CONSTRAINT symbol FOREIGN KEY index_name index_col_name REFERENCES tbl_name index_col_name ON DELETE reference_option ON UPDATE reference_option reference_option RESTRICT CASCADE SET NULL NO ACTION index_name represents a foreign key ID If given this is ignored if an index for the foreign key is defined explicitly Otherwise if MySQL creates an index for the foreign key it uses index_na...

Страница 1062: ... the parent table and automatically delete or update the matching rows in the child table Both ON DELETE CASCADE and ON UPDATE CASCADE are supported Between two tables do not define several ON UPDATE CASCADE clauses that act on the same column in the parent table or in the child table Note Currently cascaded foreign key actions do not activate triggers SET NULL Delete or update the row from the pa...

Страница 1063: ...duct_order no INT NOT NULL AUTO_INCREMENT product_category INT NOT NULL product_id INT NOT NULL customer_id INT NOT NULL PRIMARY KEY no INDEX product_category product_id INDEX customer_id FOREIGN KEY product_category product_id REFERENCES product category id ON UPDATE CASCADE ON DELETE RESTRICT FOREIGN KEY customer_id REFERENCES customer id ENGINE INNODB Adding foreign keys You can add a new forei...

Страница 1064: ...ice possible violations caused by changing the values Foreign Keys and Other MySQL Statements Table and column identifiers in a FOREIGN KEY REFERENCES clause can be quoted within backticks Alternatively double quotation marks can be used if the ANSI_QUOTES 535 SQL mode is enabled The setting of the lower_case_table_names 466 system variable is also taken into account You can view a child table s f...

Страница 1065: ...ld be avoided The MATCH clause in the SQL standard controls how NULL values in a composite multiple column foreign key are handled when comparing to a primary key MySQL essentially implements the semantics defined by MATCH SIMPLE which permit a foreign key to be all or partially NULL In that case the child table row containing such a foreign key is permitted to be inserted and does not match any r...

Страница 1066: ... because it saves space and makes table operations faster See Chapter 14 Storage Engines Before MySQL 5 0 3 a CHAR or VARCHAR column with a length specification greater than 255 is converted to the smallest TEXT type that can hold values of the given length For example VARCHAR 500 is converted to TEXT and VARCHAR 200000 is converted to MEDIUMTEXT Similar conversions occur for BINARY and VARBINARY ...

Страница 1067: ...AD DATA and REPLACE statements UPDATE The trigger is activated whenever a row is modified for example through UPDATE statements DELETE The trigger is activated whenever a row is deleted from the table for example through DELETE and REPLACE statements However DROP TABLE and TRUNCATE TABLE statements on the table do not activate this trigger because they do not use DELETE See Section 13 1 21 TRUNCAT...

Страница 1068: ...eate a trigger with a nonexistent DEFINER account it is not a good idea for such triggers to be activated until the account actually does exist Otherwise the behavior with respect to privilege checking is undefined Note Because MySQL currently requires the SUPER 578 privilege for the use of CREATE TRIGGER only the second of the preceding rules applies MySQL 5 1 6 implements the TRIGGER privilege a...

Страница 1069: ... triggers cannot contain direct references to tables by name Beginning with MySQL 5 0 10 you can write triggers such as the one named testref shown in this example CREATE TABLE test1 a1 INT CREATE TABLE test2 a2 INT CREATE TABLE test3 a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY CREATE TABLE test4 a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY b4 INT DEFAULT 0 delimiter CREATE TRIGGER testref BEFORE INS...

Страница 1070: ...view or replaces an existing one if the OR REPLACE clause is given This statement was added in MySQL 5 0 1 If the view does not exist CREATE OR REPLACE VIEW is the same as CREATE VIEW If the view does exist CREATE OR REPLACE VIEW is the same as ALTER VIEW The select_statement is a SELECT statement that provides the definition of the view When you select from the view you select in effect using the...

Страница 1071: ...efine explicit names for the view columns the optional column_list clause can be given as a list of comma separated identifiers The number of names in column_list must be the same as the number of columns retrieved by the SELECT statement Note Prior to MySQL 5 0 72 when you modify an existing view the server saves a backup of the current view definition under the view database directory in a subdi...

Страница 1072: ...inst the maximum column length of 64 characters not the maximum alias length of 256 characters ORDER BY is permitted in a view definition but it is ignored if you select from a view using a statement that has its own ORDER BY For other options or clauses in the definition they are added to the options or clauses of the statement that references the view but the effect is undefined For example if a...

Страница 1073: ... the account for the view s invoker For information about user auditing within views see Section 6 3 8 SQL Based MySQL Account Activity Auditing Within a stored routine that is defined with the SQL SECURITY DEFINER characteristic CURRENT_USER 959 returns the routine s DEFINER value This also affects a view defined within such a routine if the view definition contains a DEFINER value of CURRENT_USE...

Страница 1074: ...unt However because the actual definer is unknown MySQL issues a warning To eliminate the warning it is sufficient to re create the view so that the view definition includes a DEFINER clause The optional ALGORITHM clause is a MySQL extension to standard SQL It affects how MySQL processes the view ALGORITHM takes three values MERGE TEMPTABLE or UNDEFINED The default algorithm is UNDEFINED if no ALG...

Страница 1075: ...tables and remove these directories manually before upgrading to MySQL 5 0 See Section 2 19 1 2 Upgrading from MySQL 4 1 to 5 0 The db opt file if it exists If other files or directories remain in the database directory after MySQL removes those just listed the database directory cannot be removed In this case you must remove any remaining files or directories manually and issue the DROP DATABASE ...

Страница 1076: ...yntax DROP TEMPORARY TABLE IF EXISTS tbl_name tbl_name RESTRICT CASCADE DROP TABLE removes one or more tables You must have the DROP 577 privilege for each table All table data and the table definition are removed so be careful with this statement If any of the tables named in the argument list do not exist MySQL returns an error indicating by name which nonexisting tables it was unable to drop bu...

Страница 1077: ... 13 1 19 DROP VIEW Syntax DROP VIEW IF EXISTS view_name view_name RESTRICT CASCADE DROP VIEW removes one or more views You must have the DROP 577 privilege for each view If any of the views named in the argument list do not exist MySQL returns an error indicating by name which nonexisting views it was unable to drop but it also drops all of the views in the list that do exist The IF EXISTS clause ...

Страница 1078: ...nces For an InnoDB table before version 5 0 3 InnoDB processes TRUNCATE TABLE by deleting rows one by one As of MySQL 5 0 3 row by row deletion is used only if there are any FOREIGN KEY constraints that reference the table If there are no FOREIGN KEY constraints InnoDB performs fast truncation by dropping the original table and creating an empty one with the same definition which is much faster th...

Страница 1079: ... CALL p are equivalent CALL can pass back values to its caller using parameters that are declared as OUT or INOUT parameters When the procedure returns a client program can also obtain the number of rows affected for the final statement executed within the routine At the SQL level call the ROW_COUNT 963 function from the C API call the mysql_affected_rows function To get back a value from a proced...

Страница 1080: ...MENTS which also enables CLIENT_MULTI_RESULTS To process the result of a CALL statement executed using mysql_query or mysql_real_query use a loop that calls mysql_next_result to determine whether there are more results For an example see Section 20 6 15 C API Support for Multiple Statement Execution For programs written in a language that provides a MySQL interface there is no native method for di...

Страница 1081: ...ATE TABLE Syntax and Section 13 3 5 LOCK TABLES and UNLOCK TABLES Syntax If you delete the row containing the maximum value for an AUTO_INCREMENT column the value is reused later for a BDB table but not for a MyISAM or InnoDB table If you delete all rows in the table with DELETE FROM tbl_name without a WHERE clause in autocommit 436 mode the sequence starts over for all storage engines except Inno...

Страница 1082: ...ed blocks To reclaim unused index space under these circumstances use OPTIMIZE TABLE If you are going to delete many rows from a table it might be faster to use DELETE QUICK followed by OPTIMIZE TABLE This rebuilds the index rather than performing many index block merge operations The MySQL specific LIMIT row_count option to DELETE tells the server the maximum number of rows to be deleted before c...

Страница 1083: ...FT JOIN t2 ON t1 id t2 id WHERE t2 id IS NULL The syntax permits after each tbl_name for compatibility with Access If you use a multiple table DELETE statement involving InnoDB tables for which there are foreign key constraints the MySQL optimizer might process tables in an order that differs from that of their parent child relationship In this case the statement fails and rolls back Instead you s...

Страница 1084: ...f you have a multiple column index specify the index column values as a comma separated list Either specify values for all the columns in the index or specify values for a leftmost prefix of the index columns Suppose that an index my_idx includes three columns named col_a col_b and col_c in that order The HANDLER statement can specify values for all three columns in the index or for the columns in...

Страница 1085: ...sistency That is HANDLER OPEN does not take a snapshot of the table and does not lock the table This means that after a HANDLER OPEN statement is issued table data can be modified by the current session or other sessions and these modifications might be only partially visible to HANDLER NEXT or HANDLER PREV scans An open handler can be closed and marked for reopen in which case the handler loses i...

Страница 1086: ...use strict mode See Section 5 1 7 Server SQL Modes Use the keyword DEFAULT to set a column explicitly to its default value This makes it easier to write INSERT statements that assign values to all but a few columns because it enables you to avoid writing an incomplete VALUES list that does not include a value for each column in the table Otherwise you would have to write out the list of column nam...

Страница 1087: ... the number of rows actually inserted because Duplicates can be nonzero Duplicates indicates the number of rows that could not be inserted because they would duplicate some existing unique index value Warnings indicates the number of attempts to insert column values that were problematic in some way Warnings can occur under any of the following conditions Inserting NULL into a column that has been...

Страница 1088: ...yISAM tables because doing so disables concurrent inserts See Section 8 7 3 Concurrent Inserts If you specify HIGH_PRIORITY it overrides the effect of the low priority updates 414 option if the server was started with that option It also causes concurrent inserts not to be used See Section 8 7 3 Concurrent Inserts LOW_PRIORITY and HIGH_PRIORITY affect only storage engines that use only table level...

Страница 1089: ...TE KEY UPDATE you can refer to columns in other tables as long as you do not use GROUP BY in the SELECT part One side effect is that you must qualify nonunique column names in the values part The order in which rows are returned by a SELECT statement with no ORDER BY clause is not determined This means that when using replication there is no guarantee that such a SELECT returns rows in the same or...

Страница 1090: ...d DELAYED is ignored on slave replication servers so that INSERT DELAYED is treated as a normal INSERT on slaves This is because DELAYED could cause the slave to have different data than the master Pending INSERT DELAYED statements are lost if a table is write locked and ALTER TABLE is used to modify the table structure INSERT DELAYED is not supported for views The following describes in detail wh...

Страница 1091: ...mpty someone terminates the handler thread with KILL thread_id or someone executes a FLUSH TABLES The following status variables provide information about INSERT DELAYED statements Status Variable Meaning Delayed_insert_threads 525 Number of handler threads Delayed_writes 525 Number of rows written with INSERT DELAYED Not_flushed_delayed_rows 529 Number of rows waiting to be written You can view t...

Страница 1092: ...ame CHARACTER SET charset_name FIELDS COLUMNS TERMINATED BY string OPTIONALLY ENCLOSED BY char ESCAPED BY char LINES STARTING BY string TERMINATED BY string IGNORE number LINES col_name_or_user_var SET col_name expr The LOAD DATA INFILE statement reads rows from a text file into a table at a very high speed LOAD DATA INFILE is the complement of SELECT INTO OUTFILE See Section 13 2 8 1 SELECT INTO ...

Страница 1093: ...he file and error handling as described later LOCAL works only if your server and your client both have been configured to permit it For example if mysqld was started with local infile 0 462 LOCAL does not work See Section 6 1 6 Security Issues with LOAD DATA LOCAL The LOCAL keyword affects where the file is expected to be found If LOCAL is specified the file is read by the client program on the c...

Страница 1094: ...the behavior depends on whether the LOCAL keyword is specified Without LOCAL an error occurs when a duplicate key value is found and the rest of the text file is ignored With LOCAL the default behavior is the same as if IGNORE is specified this is because the server has no way to stop transmission of the file in the middle of the operation To ignore foreign key constraints during the load operatio...

Страница 1095: ...to ignore you can use LINES STARTING BY prefix_string to skip over the prefix and anything before it If a line does not include the prefix the entire line is skipped Suppose that you issue the following statement LOAD DATA INFILE tmp test txt INTO TABLE test FIELDS TERMINATED BY LINES STARTING BY xxx If the data file looks like this xxx abc 1 something xxx def 2 ghi 3 The resulting rows will be ab...

Страница 1096: ...airs or to read a file containing such lines specify a LINES TERMINATED BY r n clause To read a file containing jokes that are separated by lines consisting of you can do this CREATE TABLE jokes a INT NOT NULL AUTO_INCREMENT PRIMARY KEY joke TEXT NOT NULL LOAD DATA INFILE tmp jokes txt INTO TABLE jokes FIELDS TERMINATED BY LINES TERMINATED BY n n joke FIELDS OPTIONALLY ENCLOSED BY controls quoting...

Страница 1097: ...sequences that are exceptions where the first character is the escape character These sequences are shown in the following table using for the escape character The rules for NULL handling are described later in this section Character Escape Sequence 0 An ASCII NUL 0x00 character b A backspace character n A newline linefeed character r A carriage return character t A tab character Z ASCII 26 Contro...

Страница 1098: ...and LINES options in use For the default FIELDS and LINES values NULL is written as a field value of N for output and a field value of N is read as NULL for input assuming that the ESCAPED BY character is If FIELDS ENCLOSED BY is not empty a field containing the literal word NULL as its value is read as a NULL value This differs from the word NULL enclosed within FIELDS ENCLOSED BY characters whic...

Страница 1099: ...SET column2 var1 100 The SET clause can be used to supply values not derived from the input file The following statement sets column3 to the current date and time LOAD DATA INFILE file txt INTO TABLE t1 column1 column2 SET column3 CURRENT_TIMESTAMP You can also discard an input value by assigning it to a user variable and not assigning the variable to a table column LOAD DATA INFILE file txt INTO ...

Страница 1100: ...value is the current timestamp and it is omitted from the field list when a field list is specified LOAD DATA INFILE regards all input as strings so you cannot use numeric values for ENUM or SET columns the way you can with INSERT statements All ENUM and SET values must be specified as strings BIT values cannot be loaded using binary notation for example b 011010 To work around this specify the va...

Страница 1101: ...s a PRIMARY KEY or UNIQUE index using a REPLACE statement makes no sense It becomes equivalent to INSERT because there is no index to be used to determine whether a new row duplicates another Values for all columns are taken from the values specified in the REPLACE statement Any missing columns are set to their default values just as happens for INSERT You cannot refer to values from the current r...

Страница 1102: ...ER BY col_name expr position ASC DESC LIMIT offset row_count row_count OFFSET offset PROCEDURE procedure_name argument_list INTO OUTFILE file_name export_options INTO DUMPFILE file_name INTO var_name var_name FOR UPDATE LOCK IN SHARE MODE SELECT is used to retrieve rows selected from one or more tables and can include UNION statements and subqueries See Section 13 2 8 4 UNION Syntax and Section 13...

Страница 1103: ...d this problem use a qualified tbl_name reference SELECT AVG score t1 FROM t1 The following list provides additional information about other SELECT clauses A select_expr can be given an alias using AS alias_name The alias is used as the expression s column name and can be used in GROUP BY ORDER BY or HAVING clauses For example SELECT CONCAT last_name first_name AS full_name FROM mytable ORDER BY f...

Страница 1104: ... and begin with 1 SELECT college region seed FROM tournament ORDER BY region seed SELECT college region AS r seed AS s FROM tournament ORDER BY r s SELECT college region seed FROM tournament ORDER BY 2 3 To sort in reverse order add the DESC descending keyword to the name of the column in the ORDER BY clause that you are sorting by The default is ascending order this can be specified explicitly us...

Страница 1105: ...that should be in the WHERE clause For example do not write the following SELECT col_name FROM tbl_name HAVING col_name 0 Write this instead SELECT col_name FROM tbl_name WHERE col_name 0 The HAVING clause can refer to aggregate functions which the WHERE clause cannot SELECT user MAX salary FROM users GROUP BY user HAVING MAX salary 10 This did not work in some older versions of MySQL MySQL permit...

Страница 1106: ...dure that can be used to obtain suggestions for optimal column data types that may help reduce table sizes The SELECT INTO form of SELECT enables the query result to be written to a file or stored in variables For more information see Section 13 2 8 1 SELECT INTO Syntax If you use FOR UPDATE with a storage engine that uses page or row locks rows examined by the query are write locked until the end...

Страница 1107: ...ient This option can be used only for top level SELECT statements not for subqueries or following UNION SQL_CALC_FOUND_ROWS tells MySQL to calculate how many rows there would be in the result set disregarding any LIMIT clause The number of rows can then be retrieved with SELECT FOUND_ROWS See Section 12 13 Information Functions The SQL_CACHE and SQL_NO_CACHE options affect caching of query results...

Страница 1108: ...use SELECT INTO OUTFILE since there is no way to write a path to the file relative to the server host s file system However if the MySQL client software is installed on the remote machine you can instead use a client command such as mysql e SELECT file_name to generate the file on the client host It is also possible to create the resulting file on a different host other than the server host if the...

Страница 1109: ...one other than the user under whose account it is running You should never run mysqld as root for this and other reasons The file thus must be world writable so that you can manipulate its contents If the secure_file_priv 490 system variable is set to a nonempty directory name the file to be written must be located in that directory 13 2 8 2 JOIN Syntax MySQL supports the following JOIN syntaxes f...

Страница 1110: ...timizer makes use of indexes For more information see Section 13 2 8 3 Index Hint Syntax The following list describes general factors to take into account when writing joins A table reference can be aliased using tbl_name AS alias_name or tbl_name alias_name SELECT t1 name t2 salary FROM employee AS t1 INNER JOIN info AS t2 ON t1 name t2 name SELECT t1 name t2 salary FROM employee t1 INNER JOIN in...

Страница 1111: ...ld be written literally they are not metasyntax as used elsewhere in syntax descriptions SELECT left_tbl FROM OJ left_tbl LEFT OUTER JOIN right_tbl ON left_tbl id right_tbl id WHERE right_tbl id IS NULL STRAIGHT_JOIN is similar to JOIN except that the left table is always read before the right table This can be used for those few cases for which the join optimizer puts the tables in the wrong orde...

Страница 1112: ...mes a join column so according to standard SQL it should appear only once in the output not twice Similarly in the second SELECT statement column j is named in the USING clause and should appear only once in the output not twice But in both cases the redundant column is not eliminated Also the order of the columns is not correct according to standard SQL Now the statements produce this output j i ...

Страница 1113: ... and t2 a c have the following contents t1 t2 1 x 2 z 2 y 3 w Then mysql SELECT FROM t1 NATURAL LEFT JOIN t2 a b c 1 x NULL 2 y z Here column a contains the values of t1 a mysql SELECT FROM t1 NATURAL RIGHT JOIN t2 a c b 2 z y 3 w NULL Here column a contains the values of t2 a Compare these results to the otherwise equivalent queries with JOIN ON mysql SELECT FROM t1 LEFT JOIN t2 ON t1 a t2 a a b ...

Страница 1114: ...he preceding query was transformed to the following equi join SELECT FROM t1 t2 t3 WHERE t1 b t2 b AND t2 c t3 c That join is missing one more equi join predicate t1 a t3 a As a result it produces one row not the empty result that it should The correct equivalent query is this SELECT FROM t1 t2 t3 WHERE t1 b t2 b AND t2 c t3 c AND t1 a t3 a If you require the same query result in current versions ...

Страница 1115: ... That is in cases when MySQL formerly issued an error that some column is ambiguous the query now is handled correctly This is due to the fact that MySQL now treats the common columns of NATURAL or USING joins as a single column so when a query refers to such columns the query compiler does not consider them as ambiguous Example SELECT FROM t1 NATURAL JOIN t2 WHERE b 1 Previously this query would ...

Страница 1116: ...ROM table1 USE INDEX col1_index col2_index WHERE col1 1 AND col2 2 AND col3 3 SELECT FROM table1 IGNORE INDEX col3_index WHERE col1 1 AND col2 2 AND col3 3 For FULLTEXT searches index hints do not work before MySQL 5 0 74 As of 5 0 74 index hints work as follows For natural language mode searches index hints are silently ignored For example IGNORE INDEX i is ignored with no warning and the index i...

Страница 1117: ...erefore the use of ORDER BY in this context is typically in conjunction with LIMIT so that it is used to determine the subset of the selected rows to retrieve for the SELECT even though it does not necessarily affect the order of those rows in the final UNION result If ORDER BY appears without LIMIT in a SELECT it is optimized away because it will have no effect anyway To use an ORDER BY or LIMIT ...

Страница 1118: ...ies that are structured so that it is possible to isolate each part of a statement They provide alternative ways to perform operations that would otherwise require complex joins and unions Many people find subqueries more readable than complex joins or unions Indeed it was the innovation of subqueries that gave people the original idea of calling the early SQL Structured Query Language Here is an ...

Страница 1119: ...he value in the column can be NULL Nullability of the value selected by a scalar subquery is not copied because if the subquery result is empty the result is NULL For the subquery just shown if t1 were empty the result would be NULL even though s2 is NOT NULL There are a few contexts in which a scalar subquery cannot be used If a statement permits only a literal value you cannot use a subquery For...

Страница 1120: ...ueries with ANY IN or SOME Syntax operand comparison_operator ANY subquery operand IN subquery operand comparison_operator SOME subquery Where comparison_operator is one of these operators The ANY keyword which must follow a comparison operator means return TRUE if the comparison is TRUE for ANY of the values in the column that the subquery returns For example SELECT s1 FROM t1 WHERE s1 ANY SELECT...

Страница 1121: ...T s1 FROM t2 But this expression is NULL when table t2 is empty SELECT FROM t1 WHERE 1 SELECT s1 FROM t2 In addition the following expression is NULL when table t2 is empty SELECT FROM t1 WHERE 1 ALL SELECT MAX s1 FROM t2 In general tables containing NULL values and empty tables are edge cases When writing subqueries always consider whether you have taken those two possibilities into account NOT I...

Страница 1122: ...hat also exist in table t2 SELECT column1 column2 column3 FROM t1 WHERE column1 column2 column3 IN SELECT column1 column2 column3 FROM t2 13 2 9 6 Subqueries with EXISTS or NOT EXISTS If a subquery returns any rows at all EXISTS subquery is TRUE and NOT EXISTS subquery is FALSE For example SELECT column1 FROM t1 WHERE EXISTS SELECT FROM t2 Traditionally an EXISTS subquery starts with SELECT but it...

Страница 1123: ... rule MySQL evaluates from inside to outside For example SELECT column1 FROM t1 AS x WHERE x column1 SELECT column1 FROM t2 AS x WHERE x column1 SELECT column1 FROM t3 WHERE x column2 t3 column1 In this statement x column2 must be a column in table t2 because SELECT column1 FROM t2 AS x renames t2 It is not a column in table t1 because SELECT column1 FROM t1 is an outer query that is farther out F...

Страница 1124: ...rived temporary tables are materialized This occurs because upper level queries need information about all tables during the optimization phase and the table represented by a subquery in the FROM clause is unavailable unless the subquery is executed It is possible under certain circumstances to modify table data using EXPLAIN SELECT This can occur if the outer query accesses any tables and an inne...

Страница 1125: ...owever if the outer SELECT references any tables the optimizer executes the statement in the subquery as well mysql EXPLAIN SELECT FROM t1 AS a1 SELECT f1 5 AS a2 id select_type table type possible_keys key key_len ref rows Extra 1 PRIMARY a1 system NULL NULL NULL NULL 0 const row not found 1 PRIMARY derived2 system NULL NULL NULL NULL 1 2 DERIVED NULL NULL NULL NULL NULL NULL NULL No tables used ...

Страница 1126: ...ELECT column1 FROM t2 Incorrectly used table in subquery Error 1093 ER_UPDATE_TABLE_USED SQLSTATE HY000 Message You can t specify target table x for update in FROM clause This error occurs in cases such as the following which attempts to modify a table and select from the same table in the subquery UPDATE t1 SET column2 SELECT MAX column1 FROM t1 You can use a subquery for assignment within an UPD...

Страница 1127: ... column1 5 FROM t1 FROM t2 Instead of this query SELECT SELECT column1 FROM t1 5 FROM t2 Use a row subquery instead of a correlated subquery For example use this query SELECT FROM t1 WHERE column1 column2 IN SELECT column1 column2 FROM t2 Instead of this query SELECT FROM t1 WHERE EXISTS SELECT FROM t2 WHERE t2 column1 t1 column1 AND t2 column2 t1 column2 Use NOT a ANY rather than a ALL Use x ANY ...

Страница 1128: ...not only possible to rewrite a query without a subquery but it can be more efficient to make use of some of these techniques rather than to use subqueries One of these is the IN construct For example this query SELECT FROM t1 WHERE id IN SELECT id FROM t2 Can be rewritten as SELECT DISTINCT t1 FROM t1 t2 WHERE t1 id t2 id The queries SELECT FROM t1 WHERE id NOT IN SELECT id FROM t2 SELECT FROM t1 ...

Страница 1129: ...e actually updated You need only the SELECT 578 privilege for any columns that are read but not modified The UPDATE statement supports the following modifiers With the LOW_PRIORITY keyword execution of the UPDATE is delayed until no other clients are reading from the table This affects only storage engines that use only table level locking such as MyISAM MEMORY and MERGE With the IGNORE keyword th...

Страница 1130: ...ith a multiple table UPDATE The table_references clause lists the tables involved in the join Its syntax is described in Section 13 2 8 2 JOIN Syntax Here is an example UPDATE items month SET items price month price WHERE items id month id The preceding example shows an inner join that uses the comma operator but multiple table UPDATE statements can use any type of join permitted in SELECT stateme...

Страница 1131: ...STENT SNAPSHOT option does not change the current transaction isolation level so it provides a consistent snapshot only if the current isolation level is one that permits consistent read REPEATABLE READ 1120 or SERIALIZABLE 1121 Important Many APIs used for writing MySQL client applications such as JDBC provide their own methods for starting transactions that can and sometimes should be used inste...

Страница 1132: ... level is not SERIALIZABLE 1121 it is possible that when one transaction commits another ongoing transaction that uses the same tables will see only some of the changes made by the first transaction That is the atomicity of transactions is not guaranteed with mixed engines and inconsistencies can result If mixed engine transactions are infrequent you can use SET TRANSACTION ISOLATION LEVEL to set ...

Страница 1133: ...s that a ROLLBACK from the user does not undo CREATE TABLE statements the user made during that transaction Beginning with MySQL 5 0 8 CREATE TABLE CREATE DATABASE DROP DATABASE and TRUNCATE TABLE cause an implicit commit Beginning with MySQL 5 0 13 ALTER PROCEDURE CREATE PROCEDURE and DROP PROCEDURE cause an implicit commit Also beginning with MySQL 5 0 13 ALTER FUNCTION CREATE FUNCTION and DROP ...

Страница 1134: ...e undo Savepoints that were set at a later time than the named savepoint are deleted If the ROLLBACK TO SAVEPOINT statement returns the following error it means that no savepoint with the specified name exists ERROR 1305 42000 SAVEPOINT identifier does not exist The RELEASE SAVEPOINT statement removes the named savepoint from the set of savepoints of the current transaction No commit or rollback o...

Страница 1135: ...The table can be accessed freely by the session within which it was created regardless of what other locking may be in effect No lock is necessary because no other session can see the table For information about other conditions on the use of LOCK TABLES and statements that cannot be used while LOCK TABLES is in effect see Section 13 3 5 3 Table Locking Restrictions and Conditions Rules for Lock A...

Страница 1136: ...alias you must lock the table using that same alias It does not work to lock the table without specifying the alias mysql LOCK TABLE t READ mysql SELECT FROM t AS myalias ERROR 1100 Table myalias was not locked with LOCK TABLES Conversely if you lock a table using an alias you must refer to it in your statements using that alias mysql LOCK TABLE t AS myalias READ mysql SELECT FROM t ERROR 1100 Tab...

Страница 1137: ...nt had an active transaction the server rolls back the transaction upon disconnect and if reconnect occurs the new session begins with autocommit enabled For this reason clients may wish to disable auto reconnect With auto reconnect in effect the client is not notified if reconnect occurs but any table locks or current transaction will have been lost With auto reconnect disabled if the connection ...

Страница 1138: ...a table explicitly with LOCK TABLES any tables used in triggers are also locked implicitly The locks are taken as the same time as those acquired explicitly with the LOCK TABLES statement The lock on a table used in a trigger depends on whether the table is used only for reading If so a read lock suffices Otherwise a write lock is used If a table is locked explicitly for reading with LOCK TABLES b...

Страница 1139: ...r a nontransactional storage engine you must use LOCK TABLES if you want to ensure that no other session modifies the tables between a SELECT and an UPDATE The example shown here requires LOCK TABLES to execute safely LOCK TABLES trans READ customer WRITE SELECT SUM value FROM trans WHERE customer_id some_id UPDATE customer SET total_value sum_from_previous_statement WHERE customer_id some_id UNLO...

Страница 1140: ...crucial data where ACID compliance is important Or you can relax the consistency rules with READ COMMITTED 1121 or even READ UNCOMMITTED 1121 in situations such as bulk reporting where precise consistency and repeatable results are less important than minimizing the amount of overhead for locking SERIALIZABLE 1121 enforces even stricter rules than REPEATABLE READ 1120 and is used mainly in special...

Страница 1141: ... a consistent nonlocking read and need not block for other transactions To force a plain SELECT to block if other transactions have modified the selected rows disable autocommit 13 3 7 XA Transactions MySQL 5 0 3 and up provides server side support for XA transactions Currently this support is available for the InnoDB storage engine The MySQL XA implementation is based on the X Open CAE document D...

Страница 1142: ... implementation of XA MySQL enables a MySQL server to act as a Resource Manager that handles XA transactions within a global transaction A client program that connects to the MySQL server acts as the Transaction Manager To carry out a global transaction it is necessary to know which components are involved and bring each component to a point when it can be committed or rolled back Depending on wha...

Страница 1143: ...erated by one TM must be different from values generated by other TMs A given TM must be able to recognize its own xid values in a list of values returned by the XA RECOVER statement XA START xid starts an XA transaction with the given xid value Each XA transaction must have a unique xid value so the value must not currently be used by another XA transaction Uniqueness is assessed using the gtrid ...

Страница 1144: ...y XA RECOVER because the transaction terminates 4 For a PREPARED XA transaction you can issue an XA COMMIT statement to commit and terminate the transaction or XA ROLLBACK to roll back and terminate the transaction Here is a simple XA transaction that inserts a row into a table as part of a global transaction mysql XA START xatest Query OK 0 rows affected 0 00 sec mysql INSERT INTO mytable i VALUE...

Страница 1145: ... MySQL server The log consists of a set of binary log files plus an index file see Section 5 2 3 The Binary Log The PURGE BINARY LOGS statement deletes all the binary log files listed in the log index file prior to the specified log file name or date BINARY and MASTER are synonyms Deleted log files also are removed from the list recorded in the index file so that the given log file becomes the fir...

Страница 1146: ...letes all binary log files listed in the index file resets the binary log index file to be empty and creates a new binary log file This statement is intended to be used only when the master is started for the first time Important The effects of RESET MASTER differ from those of PURGE BINARY LOGS in 2 key ways 1 RESET MASTER removes all binary log files that are listed in the index file leaving onl...

Страница 1147: ...STER_SSL_KEY key_file_name MASTER_SSL_CIPHER cipher_list CHANGE MASTER TO changes the parameters that the slave server uses for connecting to the master server for reading the master binary log and reading the slave relay log It also updates the contents of the master info and relay log info files To use CHANGE MASTER TO the slave replication threads must be stopped use STOP SLAVE if necessary Opt...

Страница 1148: ...for more information see Section 16 1 2 Replication and Binary Logging Options and Variables MASTER_LOG_FILE and MASTER_LOG_POS are the coordinates at which the slave I O thread should begin reading from the master the next time the thread starts RELAY_LOG_FILE and RELAY_LOG_POS are the coordinates at which the slave SQL thread should begin reading from the relay log the next time the thread start...

Страница 1149: ...info and relay log info files and restart the server with its original options Specifying the MASTER_HOST option even with a dummy value is required to make the server think it is a slave 13 4 2 2 LOAD DATA FROM MASTER Syntax LOAD DATA FROM MASTER This feature is deprecated and should be avoided It is subject to removal in a future version of MySQL Since the current implementation of LOAD DATA FRO...

Страница 1150: ...on of LOAD DATA FROM MASTER and LOAD TABLE FROM MASTER is very limited these statements are deprecated as of MySQL 4 1 and removed in MySQL 5 5 The recommended alternative solution to using LOAD DATA FROM MASTER or LOAD TABLE FROM MASTER is using mysqldump or mysqlhotcopy The latter requires Perl and two Perl modules DBI and DBD mysql and works for MyISAM and ARCHIVE tables only With mysqldump you...

Страница 1151: ...rd Options for which values are not specified are cleared If the slave SQL thread was in the middle of replicating temporary tables when it was stopped and RESET SLAVE is issued these replicated temporary tables are deleted on the slave 13 4 2 6 SET GLOBAL sql_slave_skip_counter Syntax SET GLOBAL sql_slave_skip_counter N This statement skips the next N events from the master This is useful for rec...

Страница 1152: ...y be added to specify that the slave should start and run until the SQL thread reaches a given point in the master binary log or in the slave relay log When the SQL thread reaches that point it stops If the SQL_THREAD option is specified in the statement it starts only the SQL thread Otherwise it starts both slave threads If the SQL thread is running the UNTIL clause is ignored and a warning is is...

Страница 1153: ... Java programs and MySQL Connector Net For example the C API provides a set of function calls that make up its prepared statement API See Section 20 6 7 C API Prepared Statements Other language interfaces can provide support for prepared statements that use the binary protocol by linking in the C client library one example being the mysqli extension available in PHP 5 0 and later An alternative SQ...

Страница 1154: ... is similar but supplies the text of the statement as a user variable mysql SET s SELECT SQRT POW 2 POW 2 AS hypotenuse mysql PREPARE stmt2 FROM s mysql SET a 6 mysql SET b 8 mysql EXECUTE stmt2 USING a b hypotenuse 10 mysql DEALLOCATE PREPARE stmt2 Here is an additional example which demonstrates how to choose the table on which to perform a query at runtime by storing the name of the table as a ...

Страница 1155: ...ents cannot be used in nested fashion That is a statement passed to PREPARE cannot itself be a PREPARE EXECUTE or DEALLOCATE PREPARE statement SQL syntax for prepared statements is distinct from using prepared statement API calls For example you cannot use the mysql_stmt_prepare C API function to prepare a PREPARE EXECUTE or DEALLOCATE PREPARE statement SQL syntax for prepared statements cannot be...

Страница 1156: ... not available to other sessions When a session ends whether normally or abnormally its prepared statements no longer exist If auto reconnect is enabled the client is not notified that the connection was lost For this reason clients may wish to disable auto reconnect See Section 20 6 14 Controlling Automatic Reconnection Behavior A prepared statement created within a stored program continues to ex...

Страница 1157: ...ltiple statements enclosed by the BEGIN and END keywords statement_list represents a list of one or more statements each terminated by a semicolon statement delimiter The statement_list itself is optional so the empty compound statement BEGIN END is legal BEGIN END blocks can be nested Use of multiple statements requires that a client is able to send statement strings containing the statement deli...

Страница 1158: ...es See Section 13 6 4 Variables in Stored Programs Conditions and handlers See Section 13 6 7 Condition Handling Cursors See Section 13 6 6 Cursors DECLARE is permitted only inside a BEGIN END compound statement and must be at its start before any other statements Declarations must follow a certain order Cursor declarations must appear before handler declarations Variable and condition declaration...

Страница 1159: ...e same name Because local variables are in scope only during stored program execution references to them are not permitted in prepared statements created within a stored program Prepared statement scope is the current session not the stored program so the statement could be executed after the program ends at which point the variables would no longer be in scope For example SELECT INTO local_var ca...

Страница 1160: ...ondition THEN statement_list ELSE statement_list END CASE The CASE statement for stored programs implements a complex conditional construct Note There is also a CASE 883 expression which differs from the CASE statement described here See Section 12 4 Control Flow Functions The CASE statement cannot have an ELSE NULL clause and it is terminated with END CASE instead of END For the first syntax case...

Страница 1161: ...ams implements a basic conditional construct Note There is also an IF 883 function which differs from the IF statement described here See Section 12 4 Control Flow Functions The IF statement can have THEN ELSE and ELSEIF clauses and it is terminated with END IF If the search_condition evaluates to true the corresponding THEN or ELSEIF clause statement_list executes If no search_condition matches t...

Страница 1162: ... loop again For an example see Section 13 6 5 5 LOOP Syntax 13 6 5 4 LEAVE Syntax LEAVE label This statement is used to exit the flow control construct that has the given label If the label is for the outermost stored program block LEAVE exits the program LEAVE can be used within BEGIN END or loop constructs LOOP REPEAT WHILE For an example see Section 13 6 5 5 LOOP Syntax 13 6 5 5 LOOP Syntax beg...

Страница 1163: ...abel use see Section 13 6 2 Statement Label Syntax Example mysql delimiter mysql CREATE PROCEDURE dorepeat p1 INT BEGIN SET x 0 REPEAT SET x x 1 UNTIL x p1 END REPEAT END Query OK 0 rows affected 0 00 sec mysql CALL dorepeat 1000 Query OK 0 rows affected 0 00 sec mysql SELECT x x 1001 1 row in set 0 00 sec 13 6 5 7 RETURN Syntax RETURN expr The RETURN statement terminates execution of a stored fun...

Страница 1164: ...sensitive The server may or may not make a copy of its result table Read only Not updatable Nonscrollable Can be traversed only in one direction and cannot skip rows Cursor declarations must appear before handler declarations and after variable and condition declarations Example CREATE PROCEDURE curdemo BEGIN DECLARE done INT DEFAULT FALSE DECLARE a CHAR 16 DECLARE b c INT DECLARE cur1 CURSOR FOR ...

Страница 1165: ...for the SELECT statement associated with the specified cursor which must be open and advances the cursor pointer If a row exists the fetched columns are stored in the named variables The number of columns retrieved by the SELECT statement must match the number of output variables specified in the FETCH statement If no more rows are available a No Data condition occurs with SQLSTATE value 02000 To ...

Страница 1166: ...ogram code clearer For example this handler applies to attempts to drop a nonexistent table but that is apparent only if you know the meaning of MySQL error code 1051 DECLARE CONTINUE HANDLER FOR 1051 BEGIN body of handler END By declaring a name for the condition the purpose of the handler is more readily seen DECLARE no_such_table CONDITION FOR 1051 DECLARE CONTINUE HANDLER FOR no_such_table BEG...

Страница 1167: ...lues that begin with 01 NOT FOUND is shorthand for the class of SQLSTATE values that begin with 02 This is relevant within the context of cursors and is used to control what happens when a cursor reaches the end of a data set If no more rows are available a No Data condition occurs with SQLSTATE value 02000 To detect this condition you can set up a handler for it or for a NOT FOUND condition For a...

Страница 1168: ...tement associated with a handler cannot use ITERATE or LEAVE to refer to labels for blocks that enclose the handler declaration Consider the following example where the REPEAT block has a label of retry CREATE PROCEDURE p BEGIN DECLARE i INT DEFAULT 3 retry REPEAT BEGIN DECLARE CONTINUE HANDLER FOR SQLWARNING BEGIN ITERATE retry illegal END IF i 0 THEN LEAVE retry legal END IF SET i i 1 END UNTIL ...

Страница 1169: ...te to a new version of MySQL you should update your grant tables to make sure that they have the current structure so that you can take advantage of any new capabilities See Section 4 4 9 mysql_upgrade Check Tables for MySQL Upgrade 13 7 1 1 CREATE USER Syntax CREATE USER user_specification user_specification user_specification user IDENTIFIED BY PASSWORD password The CREATE USER statement creates...

Страница 1170: ...yntax DROP USER user user The DROP USER statement removes one or more MySQL accounts To use it you must have the global CREATE USER 576 privilege or the DELETE 577 privilege for the mysql database Each account name uses the format described in Section 6 2 3 Specifying Account Names For example DROP USER jeffrey localhost If you specify only the user name part of the account name a host name part o...

Страница 1171: ..._level TO user_specification user_specification REQUIRE NONE ssl_option AND ssl_option WITH with_option object_type TABLE FUNCTION PROCEDURE priv_level db_name db_name tbl_name tbl_name db_name routine_name user_specification user IDENTIFIED BY PASSWORD password ssl_option SSL X509 CIPHER cipher ISSUER issuer SUBJECT subject with_option GRANT OPTION MAX_QUERIES_PER_HOUR count MAX_UPDATES_PER_HOUR ...

Страница 1172: ... the structure of the grant tables to add new privileges or features Whenever you update to a new version of MySQL you should update your grant tables to make sure that they have the current structure so that you can take advantage of any new capabilities See Section 4 4 9 mysql_upgrade Check Tables for MySQL Upgrade Privileges Supported by MySQL The following table summarizes the permissible priv...

Страница 1173: ...dded in MySQL 5 0 1 CREATE USER 576 CREATE ROUTINE 576 and ALTER ROUTINE 576 were added in MySQL 5 0 3 In GRANT statements the ALL PRIVILEGES 576 privilege is named by itself and cannot be specified along with other privileges It stands for all privileges available for the level at which privileges are to be granted except for the GRANT OPTION 577 privilege USAGE 578 can be specified to create a u...

Страница 1174: ...rror occurs if there is no default database The CREATE DROP GRANT OPTION 577 and LOCK TABLES 577 privileges can be specified at the database level Table or routine privileges also can be specified at the database level in which case they apply to all tables or routines in the database MySQL stores database privileges in the mysql db table Table Privileges Table privileges apply to all columns in a...

Страница 1175: ...ence of the privilege at the database table or column level Details of the privilege checking procedure are presented in Section 6 2 5 Access Control Stage 2 Request Verification MySQL enables you to grant privileges on databases or tables that do not exist For tables the privileges to be granted must include the CREATE 576 privilege This behavior is by design and is intended to enable the databas...

Страница 1176: ...ss Control Stage 1 Connection Verification To determine whether the preceding warning applies to you execute the following query which lists any anonymous users SELECT Host User FROM mysql user WHERE User To avoid the problem just described delete the local anonymous user account using this statement DROP USER localhost GRANT supports host names up to 60 characters long Database table column and r...

Страница 1177: ... user can give to other users not only the SELECT 578 privilege but also INSERT 577 If you then grant the UPDATE 578 privilege to the user on the database the user can grant INSERT 577 SELECT 578 and UPDATE 578 For a nonadministrative user you should not grant the ALTER 576 privilege globally or for the mysql database If you do that the user can try to subvert the privilege system by renaming tabl...

Страница 1178: ...onally specify the ssl key 608 and ssl cert 608 options If neither ssl ca 608 option nor ssl capath 608 option is specified the client does not authenticate the server certificate REQUIRE X509 means that the client must have a valid certificate but that the exact certificate issuer and subject do not matter The only requirement is that it should be possible to verify its signature with one of the ...

Страница 1179: ...le column or routine privileges for even one user the server examines table column and routine privileges for all users and this slows down MySQL a bit Similarly if you limit the number of queries updates or connections for any users the server must monitor these values MySQL and Standard SQL Versions of GRANT The biggest differences between the MySQL and standard SQL versions of GRANT are MySQL a...

Страница 1180: ...ch the DEFINER attribute names the old user Attempts to access such objects may produce an error if they execute in definer security context For information about security context see Section 18 5 Access Control for Stored Programs and Views The privilege changes take effect as indicated in Section 6 2 6 When Privilege Changes Take Effect The RENAME USER statement was added in MySQL 5 0 2 13 7 1 5...

Страница 1181: ...ses the encrypted password string must be in the format required by the authentication method used for the account With no FOR user clause this statement sets the password for the current user To see which account the server authenticated you as invoke the CURRENT_USER 959 function Any client who successfully connects to the server using a nonanonymous account can change the password for that acco...

Страница 1182: ...e specific to MySQL Replication For more information see Bug 43439 13 7 2 Table Maintenance Statements 13 7 2 1 ANALYZE TABLE Syntax ANALYZE NO_WRITE_TO_BINLOG LOCAL TABLE tbl_name tbl_name ANALYZE TABLE analyzes and stores the key distribution for a table During the analysis the table is locked with a read lock for MyISAM BDB and InnoDB This statement works with MyISAM BDB InnoDB and NDB tables F...

Страница 1183: ...ead lock for all tables in the group BACKUP TABLE returns a result set with the following columns Column Value Table The table name Op Always backup Msg_type status error info note or warning Msg_text An informational message 13 7 2 3 CHECK TABLE Syntax CHECK TABLE tbl_name tbl_name option option FOR UPGRADE QUICK FAST MEDIUM EXTENDED CHANGED CHECK TABLE checks a table or tables for errors CHECK T...

Страница 1184: ...tbl_name to fix it Changes are sometimes made to character sets or collations that require table indexes to be rebuilt For details about these changes and when FOR UPGRADE detects them see Section 2 19 3 Checking Whether Tables or Indexes Must Be Rebuilt The other check options that can be given are shown in the following table These options are passed to the storage engine which may use them or n...

Страница 1185: ...ible to create a row where the AUTO_INCREMENT column is 0 by explicitly setting the column to 0 with an UPDATE statement This is not an error in itself but could cause trouble if you decide to dump the table and restore it or do an ALTER TABLE on the table In this case the AUTO_INCREMENT column changes value according to the rules of AUTO_INCREMENT columns which could cause problems such as a dupl...

Страница 1186: ...work for tables created using any other storage engine For MyISAM tables OPTIMIZE TABLE works as follows 1 If the table has deleted or split rows repair the table 2 If the index pages are not sorted sort them 3 If the table s statistics are not up to date and the repair could not be accomplished by sorting the index update them For BDB tables OPTIMIZE TABLE currently is mapped to ANALYZE TABLE See...

Страница 1187: ...nd then the next operation you perform could overwrite the data file This is an unlikely but possible scenario that underscores the value of making a backup first REPAIR TABLE returns a result set with the following columns Column Value Table The table name Op Always repair Msg_type status error info note or warning Msg_text An informational message The REPAIR TABLE statement might produce many ro...

Страница 1188: ...ns this message Table upgrade required Please do REPAIR TABLE tbl_name to fix it If USE_FRM is not used REPAIR TABLE checks the table to see whether an upgrade is required If so it performs the upgrade following the same rules as CHECK TABLE FOR UPGRADE See Section 13 7 2 3 CHECK TABLE Syntax for more information As of MySQL 5 0 62 REPAIR TABLE without USE_FRM upgrades the frm file to the current ...

Страница 1189: ...used before 5 0 67 applies The file must be located in a directory that is searched by your system s dynamic linker For more information see Section 21 2 2 5 Compiling and Installing User Defined Functions To create a function you must have the INSERT 577 privilege for the mysql database This is necessary because CREATE FUNCTION adds a row to the mysql func system table that records the function s...

Страница 1190: ... of MySQL employed SET OPTION but this syntax is deprecated in favor of SET without OPTION This section describes use of SET for assigning values to variables The SET statement can be used to assign values to these types of variables System variables See Section 5 1 4 Server System Variables System variables also can be set at server startup as described in Section 5 1 5 Using System Variables Use...

Страница 1191: ...ds or until you change the variable to a different value The change is not visible to other clients If you change a global system variable the value is remembered and used for new connections until the server restarts To make a global system variable setting permanent you should set it in an option file The change is visible to any client that accesses that global variable However the change affec...

Страница 1192: ...e following list describes SET options that have nonstandard syntax that is options that are not set with name value syntax CHARACTER SET charset_name DEFAULT This maps all strings from and to the client with the given mapping You can add new mappings by editing sql convert cc in the MySQL source distribution SET CHARACTER SET sets three session system variables character_set_client 441 and charac...

Страница 1193: ...ble_name Value character_set_connection latin5 collation_connection latin5_turkish_ci mysql SHOW VARIABLES LIKE _connection Variable_name Value character_set_connection latin1 collation_connection latin1_swedish_ci 13 7 5 SHOW Syntax SHOW has many forms that provide information about databases tables columns or status information about the server This section describes those following SHOW BINARY ...

Страница 1194: ...h you cannot easily do with results from SHOW statements See Chapter 19 INFORMATION_SCHEMA Tables 13 7 5 1 SHOW BINARY LOGS Syntax SHOW BINARY LOGS SHOW MASTER LOGS Lists the binary log files on the server This statement is used as part of the procedure described in Section 13 4 1 1 PURGE BINARY LOGS Syntax that shows how to determine which logs can be purged mysql SHOW BINARY LOGS Log_name File_s...

Страница 1195: ...ement lists collations supported by the server By default the output from SHOW COLLATION includes all available collations The LIKE 896 clause if present indicates which collation names to match The WHERE clause can be given to select rows using more general conditions as discussed in Section 19 18 Extensions to SHOW Statements For example mysql SHOW COLLATION LIKE latin1 Collation Charset Id Defa...

Страница 1196: ...under which this occurs are described in Section 13 1 10 3 Silent Column Specification Changes The FULL keyword causes the output to include the column collation and comments as well as the privileges you have for each column You can use db_name tbl_name as an alternative to the tbl_name FROM db_name syntax In other words these two statements are equivalent mysql SHOW COLUMNS FROM mytable FROM myd...

Страница 1197: ... contains any additional information that is available about a given column The value is auto_increment for columns that have the AUTO_INCREMENT attribute and empty otherwise Privileges indicates the privileges you have for the column This value is displayed only if you use the FULL keyword Comment indicates any comment the column has This value is displayed only if you use the FULL keyword SHOW F...

Страница 1198: ... PROCEDURE simpleproc OUT param1 INT BEGIN SELECT COUNT INTO param1 FROM t END mysql SHOW CREATE FUNCTION test hello G 1 row Function hello sql_mode Create Function CREATE FUNCTION hello s CHAR 20 RETURNS CHAR 50 RETURN CONCAT Hello s 13 7 5 9 SHOW CREATE TABLE Syntax SHOW CREATE TABLE tbl_name Shows the CREATE TABLE statement that creates the given table The statement requires the SELECT 578 priv...

Страница 1199: ... a b AS col1 1 row in set 0 00 sec The advantage of storing a view definition in canonical form is that changes made later to the value of sql_mode 495 will not affect the results from the view However an additional consequence is that comments prior to SELECT are stripped from the definition by the server 13 7 5 11 SHOW DATABASES Syntax SHOW DATABASES SCHEMAS LIKE pattern WHERE expr SHOW DATABASE...

Страница 1200: ...cluster status information Sample output from this statement is shown here mysql SHOW ENGINE NDB STATUS free_list created free sizeof NdbTransaction 5 0 208 NdbOperation 4 4 660 NdbIndexScanOperation 1 1 736 NdbIndexOperation 0 0 1060 NdbRecAttr 645 645 72 NdbApiSignal 16 16 136 NdbLabel 0 0 196 NdbBranch 0 0 24 NdbSubroutine 0 0 68 NdbCall 0 0 16 NdbBlob 2 2 204 NdbReceiver 2 0 68 12 rows in set ...

Страница 1201: ...ge engine is supported or to see what the default engine is SHOW TABLE TYPES is a synonym but is deprecated and is removed in MySQL 5 5 mysql SHOW ENGINES G 1 row Engine MyISAM Support DEFAULT Comment Default engine as of MySQL 3 23 with great performance 2 row Engine MEMORY Support YES Comment Hash based stored in memory useful for temporary tables 3 row Engine HEAP Support YES Comment Alias for ...

Страница 1202: ...rver was compiled without support for the engine so it cannot be activated at runtime A value of DISABLED occurs either because the server was started with an option that disables the engine or because not all options required to enable it were given In the latter case the error log file should contain a reason indicating why the option is disabled See Section 5 2 1 The Error Log You might also se...

Страница 1203: ...sued to duplicate the privileges that are granted to a MySQL user account The account is named using the same format as for the GRANT statement for example jeffrey localhost If you specify only the user name part of the account name a host name part of is used For additional information about specifying account names see Section 13 7 1 3 GRANT Syntax mysql SHOW GRANTS FOR root localhost Grants for...

Страница 1204: ...ues A Ascending or NULL Not sorted Cardinality An estimate of the number of unique values in the index This is updated by running ANALYZE TABLE or myisamchk a Cardinality is counted based on statistics stored as integers so the value is not necessarily exact even for small tables The higher the cardinality the greater the chance that MySQL uses the index when doing joins Sub_part The number of ind...

Страница 1205: ...ER STATUS Syntax SHOW MASTER STATUS This statement provides status information about the binary log files of the master It requires either the SUPER 578 or REPLICATION CLIENT 577 privilege Example mysql SHOW MASTER STATUS File Position Binlog_Do_DB Binlog_Ignore_DB mysql bin 003 73 test manual mysql 13 7 5 22 SHOW MUTEX STATUS Syntax SHOW MUTEX STATUS SHOW MUTEX STATUS displays InnoDB mutex statis...

Страница 1206: ...writer Consequently the output may appear to contain multiple rows for the same mutex File The source file where the mutex is implemented Line The line number in the source file where the mutex is created This may change depending on your version of MySQL OS_waits Same as OS_waits_time Information from this statement can be used to diagnose system problems For example large values of spin_waits an...

Страница 1207: ...mment To alter or drop stored functions procedures 3 row Privilege Create Context Databases Tables Indexes Comment To create new databases and tables 4 row Privilege Create routine Context Databases Comment To use CREATE FUNCTION PROCEDURE 5 row Privilege Create temporary tables Context Databases Comment To use CREATE TEMPORARY TABLE Privileges belonging to a specific user are displayed by the SHO...

Страница 1208: ...ROCEDURE STATUS Syntax SHOW PROCEDURE STATUS LIKE pattern WHERE expr This statement is a MySQL extension It returns characteristics of a stored procedure such as the database name type creator creation and modification dates and character set information A similar statement SHOW FUNCTION STATUS displays information about stored functions see Section 13 7 5 16 SHOW FUNCTION STATUS Syntax The LIKE 8...

Страница 1209: ...xample of SHOW PROCESSLIST output mysql SHOW FULL PROCESSLIST G 1 row Id 1 User system user Host db NULL Command Connect Time 1030455 State Waiting for master to send event Info NULL 2 row Id 2 User system user Host db NULL Command Connect Time 1004 State Has read all relay log waiting for the slave I O thread to update it Info NULL 3 row Id 3112 User replikator Host artemis 2204 db NULL Command B...

Страница 1210: ...col and Com_xxx status variables See Section 5 1 6 Server Status Variables Time The time in seconds that the thread has been in its current state State An action event or state that indicates what the thread is doing Descriptions for State values can be found at Section 8 10 Examining Thread Information Most states correspond to very quick operations If a thread stays in a given state for many sec...

Страница 1211: ...ay be given to limit the output to row_count rows If LIMIT is given OFFSET offset may be added to begin the output offset rows into the full set of rows By default SHOW PROFILE displays Status and Duration columns The Status values are like the State values displayed by SHOW PROCESSLIST although there might be some minor differences in interpretion for the two statements for some status values see...

Страница 1212: ... 0 000028 0 000028 After create 0 011363 0 000217 0 001571 query end 0 000375 0 000013 0 000028 freeing items 0 000089 0 000010 0 000014 logging slow query 0 000019 0 000009 0 000010 cleaning up 0 000005 0 000003 0 000002 7 rows in set 0 00 sec Note Profiling is only partially functional on some architectures For values that depend on the getrusage system call NULL is returned on systems such as W...

Страница 1213: ... as configured in the server s option file or on the command line with server id value 1442 Host The host name of the slave server as configured in the server s option file or on the command line with report host host_name 1460 Note that this can differ from the machine name as configured in the operating system Port The port the slave server is listening on Master_id The unique server ID of the m...

Страница 1214: ...ting for events from the master reconnecting to the master and so on For a listing of possible states see Section 8 10 6 Replication Slave I O Thread States For versions of MySQL prior to 5 0 12 it is necessary to check this field for connection problems In those versions the thread could be running while unsuccessfully trying to connect to the master only this field makes you aware of the problem...

Страница 1215: ...ONNECT The slave I O thread is running and is connected to a replication master For this state Slave_IO_Running is Yes Slave_SQL_Running Whether the SQL thread is started Replicate_Do_DB Replicate_Ignore_DB The lists of databases that were specified with the replicate do db 1457 and replicate ignore db 1457 options if any Replicate_Do_Table Replicate_Ignore_Table Replicate_Wild_Do_Table Replicate_...

Страница 1216: ...les Until_Condition Until_Log_File Until_Log_Pos The values specified in the UNTIL clause of the START SLAVE statement Until_Condition has these values None if no UNTIL clause was specified Master if the slave is reading until a given position in the master s binary log Relay if the slave is reading until a given position in its relay log Until_Log_File and Until_Log_Pos indicate the log file name...

Страница 1217: ... is sleeping for the number of seconds given by the CHANGE MASTER TO statement or master connect retry 1453 option default 60 before reconnecting the value is NULL This is because the slave cannot know what the master is doing and so cannot say reliably how late it is The value of Seconds_Behind_Master is based on the timestamps stored in events which are preserved through replication This means t...

Страница 1218: ...r these you get the same value for both GLOBAL and SESSION The scope for each status variable is listed at Section 5 1 6 Server Status Variables Note Before MySQL 5 0 2 SHOW STATUS returned global status values Because the default as of 5 0 2 is to return session values this is incompatible with previous versions To issue a SHOW STATUS statement that will retrieve global status values for all vers...

Страница 1219: ...he Rows value is NULL for tables in the INFORMATION_SCHEMA database Avg_row_length The average row length Data_length The length of the data file Max_data_length The maximum length of the data file This is the total number of bytes of data that can be stored in the table given the data pointer size used Index_length The length of the index file Data_free The number of allocated but unused bytes Au...

Страница 1220: ...hows appropriate values for the Avg_row_length and Data_length columns with the exception that BLOB columns are not taken into account In addition the number of replicas is now shown in the Comment column as number_of_replicas For views all the fields displayed by SHOW TABLE STATUS are NULL except that Name indicates the view name and Comment says view 13 7 5 34 SHOW TABLES Syntax SHOW FULL TABLES...

Страница 1221: ...sql_mode Definer myname localhost Note When using a LIKE 896 clause with SHOW TRIGGERS the expression to be matched expr is compared with the name of the table on which the trigger is declared and not with the name of the trigger mysql SHOW TRIGGERS LIKE ins Empty set 0 01 sec A brief explanation of the columns in the output of this statement is shown here Trigger The name of the trigger Event The...

Страница 1222: ...n mysqld starts and most can be changed at runtime with the SET statement See Section 5 1 5 Using System Variables and Section 13 7 4 SET Syntax Partial output is shown here The list of names and values may be different for your server Section 5 1 4 Server System Variables describes the meaning of each variable and Section 8 9 2 Tuning Server Parameters provides information about tuning them mysql...

Страница 1223: ... UPDATE and LOAD DATA INFILE as well as DDL statements such as CREATE TABLE and ALTER TABLE SHOW WARNINGS is also used following EXPLAIN EXTENDED to display the extra information generated by EXPLAIN when the EXTENDED keyword is used See Section 8 2 3 EXPLAIN EXTENDED Output Format The LIMIT clause has the same syntax as for the SELECT statement See Section 13 2 8 SELECT Syntax A related statement...

Страница 1224: ...ror_count 468 In the following example the ALTER TABLE statement produces three warning messages as shown by the value of warning_count 507 but only one is stored because max_error_count 468 has been set to 1 mysql SHOW VARIABLES LIKE max_error_count Variable_name Value max_error_count 64 1 row in set 0 00 sec mysql SET max_error_count 1 Query OK 0 rows affected 0 00 sec mysql ALTER TABLE t1 MODIF...

Страница 1225: ...us OK test t3 assign_to_keycache status OK The syntax of CACHE INDEX enables you to specify that only particular indexes from a table should be assigned to the cache The current implementation assigns all the table s indexes to the cache so there is no reason to specify anything other than the table name The key cache referred to in a CACHE INDEX statement can be created by setting its size with a...

Страница 1226: ...ost while connecting to the MySQL server MySQL assumes that something is wrong and blocks the host from further connection requests Flushing the host cache enables further connection attempts from the host The default value of max_connect_errors 467 is 10 To avoid this error message start the server with max_connect_errors 467 set to a large value LOGS Closes and reopens all log files If binary lo...

Страница 1227: ...ater in this section USER_RESOURCES Resets all per hour user resources to zero This enables clients that have reached their hourly connection query or update limits to resume activity immediately FLUSH USER_RESOURCES does not apply to the limit on maximum simultaneous connections See Section 6 3 4 Setting Account Resource Limits The mysqladmin utility provides a command line interface to some flus...

Страница 1228: ...es the connection associated with the given thread_id KILL QUERY terminates the statement that the connection is currently executing but leaves the connection itself intact If you have the PROCESS 577 privilege you can see all threads If you have the SUPER 578 privilege you can kill all threads and statements Otherwise you can see and kill only your own threads and statements You can also use the ...

Страница 1229: ...IGNORE LEAVES Table Op Msg_type Msg_text test t1 preload_keys status OK test t2 preload_keys status OK This statement preloads all index blocks from t1 It preloads only blocks for the nonleaf nodes from t2 The syntax of LOAD INDEX INTO CACHE enables you to specify that only particular indexes from a table should be preloaded The current implementation preloads all the table s indexes into the cach...

Страница 1230: ...E provides information about the columns in a table It is a shortcut for SHOW COLUMNS FROM As of MySQL 5 0 1 these statements also display information for views See Section 13 7 5 5 SHOW COLUMNS Syntax col_name can be a column name or a string containing the SQL and _ wildcard characters to obtain output only for the columns with names matching the string There is no need to enclose the string wit...

Страница 1231: ...rator For example HELP rep returns a list of topics that begin with rep The HELP statement understands several types of search strings At the most general level use contents to retrieve a list of the top level help categories HELP contents For a list of topics in a given help category such as Data Types use the category name HELP data types For help on a specific help topic such as the ASCII 886 f...

Страница 1232: ...rgument to the HELP statement should yield a single row result set containing a description for the named item Example HELP status Yields name is_it_category SHOW N SHOW ENGINE N SHOW INNODB STATUS N SHOW MASTER STATUS N SHOW PROCEDURE STATUS N SHOW SLAVE STATUS N SHOW STATUS N SHOW TABLE STATUS N Result set containing multiple rows with three columns This means the search string matches a categor...

Страница 1233: ... USE db_name statement tells MySQL to use the db_name database as the default current database for subsequent statements The database remains the default until the end of the session or another USE statement is issued USE db1 SELECT COUNT FROM mytable selects from db1 mytable USE db2 SELECT COUNT FROM mytable selects from db2 mytable Making a particular database the default by means of the USE sta...

Страница 1234: ...1214 ...

Страница 1235: ...ms Supported by BDB 1308 14 5 2 Installing BDB 1308 14 5 3 BDB Startup Options 1309 14 5 4 Characteristics of BDB Tables 1310 14 5 5 Restrictions on BDB Tables 1312 14 5 6 Errors That May Occur When Using BDB Tables 1312 14 6 The EXAMPLE Storage Engine 1313 14 7 The FEDERATED Storage Engine 1313 14 7 1 Description of the FEDERATED Storage Engine 1313 14 7 2 How to Use FEDERATED Tables 1314 14 7 3 ...

Страница 1236: ...QL 5 1 but contain the latest improvements and fixes for NDBCLUSTER The NDBCLUSTER storage engine is not supported in standard MySQL 5 1 releases The ARCHIVE storage engine is used for storing large amounts of data without indexes with a very small footprint The CSV storage engine stores data in text files using comma separated values format The BLACKHOLE storage engine accepts but does not store ...

Страница 1237: ...s installed on Windows using the MySQL Configuration Wizard the InnoDB or MyISAM storage engine can be selected as the default See Section 2 10 3 5 The Database Usage Dialog To convert a table from one storage engine to another use an ALTER TABLE statement that indicates the new engine ALTER TABLE t ENGINE MYISAM ALTER TABLE t TYPE BDB See Section 13 1 10 CREATE TABLE Syntax and Section 13 1 4 ALT...

Страница 1238: ...s based on the older and no longer available ISAM storage engine but has many useful extensions Each MyISAM table is stored on disk in three files The files have names that begin with the table name and have an extension to indicate the file type An frm file stores the table format The data file has an MYD MYData extension The index file has an MYI MYIndex extension To specify explicitly that you ...

Страница 1239: ...the index tree Internal handling of one AUTO_INCREMENT column per table is supported MyISAM automatically updates this column for INSERT and UPDATE operations This makes AUTO_INCREMENT columns faster at least 10 Values at the top of the sequence are not reused after being deleted When an AUTO_INCREMENT column is defined as the last column of a multiple column index reuse of values deleted from the...

Страница 1240: ...tions to mysqld can be used to change the behavior of MyISAM tables For additional information see Section 5 1 3 Server Command Options Table 14 1 MyISAM Option Variable Reference Name Cmd Line Option file System Var Status Var Var Scope Dynamic bulk_insert_buffer_size 441 Yes Yes Yes Both Yes concurrent_insert 445 Yes Yes Yes Global Yes delay key write 406 Yes Yes Global Yes Variable delay_key_wr...

Страница 1241: ...eating a MyISAM index during REPAIR TABLE ALTER TABLE or LOAD DATA INFILE If the file size would be larger than this value the index is created using the key cache instead which is slower The value is given in bytes myisam_sort_buffer_size 476 Set the size of the buffer used when recovering tables Automatic recovery is activated if you start mysqld with the myisam recover 415 option In this case w...

Страница 1242: ...entical prefix 14 1 3 MyISAM Table Storage Formats MyISAM supports three different storage formats Two of them fixed and dynamic format are chosen automatically depending on the type of columns you are using The third compressed format can be created only with the myisampack utility see Section 4 6 5 myisampack Generate Compressed Read Only MyISAM Tables When you use CREATE TABLE or ALTER TABLE fo...

Страница 1243: ...r as a result of an update You can use OPTIMIZE TABLE or myisamchk r to defragment a table If you have fixed length columns that you access or change frequently in a table that also contains some variable length columns it might be a good idea to move the variable length columns to other tables just to avoid fragmentation Dynamic format tables have these characteristics All string columns are dyna...

Страница 1244: ... Numbers with a value of zero are stored using one bit If values in an integer column have a small range the column is stored using the smallest possible type For example a BIGINT column eight bytes can be stored as a TINYINT column one byte if all its values are in the range from 128 to 127 If a column has only a small set of possible values the data type is converted to ENUM A column may use any...

Страница 1245: ...s Crashing and MySQL Internals Porting to Other Systems 14 1 4 2 Problems from Tables Not Being Closed Properly Each MyISAM index file MYI file has a counter in the header that can be used to check whether a table has been closed properly If you get the following warning from CHECK TABLE or myisamchk it means that this counter has gone out of sync clients are using or haven t closed the table prop...

Страница 1246: ... from for example MyISAM tables where each table is stored using separate files InnoDB tables can be very large even on operating systems where file size is limited to 2GB The Windows Essentials installer makes InnoDB the MySQL default storage engine on Windows if the server being installed supports InnoDB InnoDB is used in production at numerous large database sites requiring high performance The...

Страница 1247: ...ib_logfile1 in the MySQL data directory Their size is given by the size of the innodb_log_file_size 1247 system variable To get good performance explicitly provide InnoDB parameters as discussed in the following examples Naturally edit the settings to suit your hardware and requirements Caution It is not a good idea to configure InnoDB to use data files or log files on NFS volumes Otherwise the fi...

Страница 1248: ...InnoDB does not create directories so make sure that the ibdata directory exists before you start the server This is also true of any log file directories that you configure Use the Unix or DOS mkdir command to create any necessary directories Make sure that the MySQL server has the proper access rights to create files in the data directory More generally the server must have access rights in any ...

Страница 1249: ...espace You can place InnoDB options in the mysqld group of any option file that your server reads when it starts The locations for option files are described in Section 4 2 3 3 Using Option Files If you installed MySQL on Windows using the installation and configuration wizards the option file is the my ini file located in your MySQL installation directory See Section 2 10 3 1 Starting the MySQL S...

Страница 1250: ...e binlog_cache_size max_connections 2MB Each thread uses a stack often 2MB but only 256KB in MySQL binaries provided by Oracle Corporation and in the worst case also uses sort_buffer_size read_buffer_size additional memory By compiling MySQL yourself you can use up to 64GB of physical memory in 32 bit Windows See the description for innodb_buffer_pool_awe_mem_mb 1238 in Section 14 2 2 InnoDB Start...

Страница 1251: ...cess tables that exist in the shared tablespace If you start the server without this option new tables are created in the shared tablespace but you can still access any tables that were created using multiple tablespaces Note InnoDB always needs the shared tablespace because it puts its internal data dictionary and undo logs there The ibd files are not sufficient for InnoDB to operate To move an i...

Страница 1252: ...changes are lost As a safety measure InnoDB prevents users from modifying data when any partition with newraw is specified After InnoDB has initialized the new partition stop the server change newraw in the data file specification to raw mysqld innodb_data_home_dir innodb_data_file_path dev hdd1 3Graw dev hdd2 2Graw Then restart the server and InnoDB permits changes to be made On Windows you can a...

Страница 1253: ...espace and log files You can connect to the MySQL server with the usual MySQL client programs like mysql When you shut down the MySQL server with mysqladmin shutdown the output is like this 010321 18 33 34 mysqld Normal shutdown 010321 18 33 34 mysqld Shutdown Complete InnoDB Starting shutdown InnoDB Shutdown completed You can look at the data file and log directories and you see the files created...

Страница 1254: ...y of the system variables can be changed at runtime see Section 5 1 5 2 Dynamic System Variables Table 14 2 InnoDB Option Variable Reference Name Cmd Line Option file System Var Status Var Var Scope Dynamic Com_show_innodb_status 523 Yes Both No foreign_key_checks 451 Yes Session Yes have_innodb 455 Yes Global No innodb 1236 Yes Yes innodb_adaptive_hash_index 1236 Yes Yes Yes Global No innodb_addi...

Страница 1255: ...wait_timeout 1244 Yes Yes Yes Global No innodb_locks_unsafe_for_binlog 1244 Yes Yes Yes Global No innodb_log_arch_dir 1246 Yes Yes Yes Global No innodb_log_archive 1247 Yes Yes Yes Global No innodb_log_buffer_size 1247 Yes Yes Yes Global No innodb_log_file_size 1247 Yes Yes Yes Global No innodb_log_files_in_group 1247 Yes Yes Yes Global No innodb_log_group_home_dir 1248 Yes Yes Yes Global No Innod...

Страница 1256: ...ardinality_algorithm 1252 Yes Yes Yes Global Yes timed_mutexes 501 Yes Yes Yes Global Yes unique_checks 504 Yes Session Yes InnoDB Command Options innodb 1236 Enables the InnoDB storage engine if the server was compiled with InnoDB support To disable InnoDB use skip innodb 1236 In this case the server will not start if the default storage engine is set to InnoDB Use default storage engine 405 to s...

Страница 1257: ...ic Variable No Deprecated 5 6 3 Permitted Values Type numeric Default 1048576 Range 524288 4294967295 The size in bytes of a memory pool InnoDB uses to store data dictionary information and other internal data structures The more tables you have in your application the more memory you need to allocate here If InnoDB runs out of memory in this pool it starts to allocate memory from the operating sy...

Страница 1258: ...s os0proc c source file This variable is relevant only in 32 bit Windows If your 32 bit Windows operating system supports more than 4GB memory using so called Address Windowing Extensions you can allocate the InnoDB buffer pool into the AWE physical memory using this variable innodb_buffer_pool_size Command Line Format innodb_buffer_pool_size Option File Format innodb_buffer_pool_size Option Sets ...

Страница 1259: ...Range 0 1000 The number of threads that can commit at the same time A value of 0 the default permits any number of transactions to commit simultaneously This variable was added in MySQL 5 0 12 innodb_concurrency_tickets Version Introduced 5 0 3 Command Line Format innodb_concurrency_tickets Option File Format innodb_concurrency_tickets Option Sets Variable Yes innodb_concurrency_tickets 1239 Varia...

Страница 1260: ...home_dir Command Line Format innodb_data_home_dir path Option File Format innodb_data_home_dir Option Sets Variable Yes innodb_data_home_dir 1240 Variable Name innodb_data_home_dir Variable Scope Global Dynamic Variable No Permitted Values Type file name The common part of the directory path for all InnoDB data files in the shared tablespace This setting does not affect the location of per file ta...

Страница 1261: ... cold as if MySQL had crashed no committed transaction will be lost but crash recovery will be done at the next startup The value of 2 can be used as of MySQL 5 0 5 except that it cannot be used on NetWare innodb_file_io_threads Command Line Format innodb_file_io_threads Option File Format innodb_file_io_threads Option Sets Variable Yes innodb_file_io_threads 1241 Variable Name innodb_file_io_thre...

Страница 1262: ...nce per second also when the value is 2 Note that the once per second flushing is not 100 guaranteed to happen every second due to process scheduling issues The default value of 1 is the value required for ACID compliance You can achieve better performance by setting the value different from 1 but then you can lose at most one second worth of transactions in a crash With a value of 0 any mysqld pr...

Страница 1263: ...n the data files and uses fsync to flush both the data and log files Note that InnoDB uses fsync instead of fdatasync and it does not use O_DSYNC by default because there have been problems with it on many varieties of Unix This variable is relevant only for Unix On Windows the flush method is always async_unbuffered and cannot be changed Different values of this variable can have a marked effect ...

Страница 1264: ...ang for at most this many seconds before issuing the following error ERROR 1205 HY000 Lock wait timeout exceeded try restarting transaction When a lock wait timeout occurs the current statement is not executed The current transaction is not rolled back Until MySQL 5 0 13 InnoDB rolled back the entire transaction if a lock wait timeout happened You can restore this behavior by starting the server w...

Страница 1265: ...s_unsafe_for_binlog 1244 can be set only at server startup whereas the isolation level can be set at startup or changed at runtime READ COMMITTED 1121 therefore offers finer and more flexible control than innodb_locks_unsafe_for_binlog 1244 For additional details about the effect of isolation level on gap locking see Section 13 3 6 SET TRANSACTION Syntax Enabling innodb_locks_unsafe_for_binlog 124...

Страница 1266: ...acquires x locks and does not release any of them x lock 1 2 retain x lock x lock 2 3 update 2 3 to 2 5 retain x lock x lock 3 2 retain x lock x lock 4 3 update 4 3 to 4 5 retain x lock x lock 5 2 retain x lock The second UPDATE blocks as soon as it tries to acquire any locks because first update has retained locks on all rows and does not proceed until the first UPDATE commits or rolls back x loc...

Страница 1267: ...enables large transactions to run without a need to write the log to disk before the transactions commit Thus if you have big transactions making the log buffer larger saves disk I O innodb_log_file_size Command Line Format innodb_log_file_size Option File Format innodb_log_file_size Option Sets Variable Yes innodb_log_file_size 1247 Variable Name innodb_log_file_size Variable Scope Global Dynamic...

Страница 1268: ...he default is to create two files named ib_logfile0 and ib_logfile1 in the MySQL data directory Their size is given by the size of the innodb_log_file_size 1247 system variable innodb_max_dirty_pages_pct Command Line Format innodb_max_dirty_pages_pct Option File Format innodb_max_dirty_pages_pct Option Sets Variable Yes innodb_max_dirty_pages_pct 1248 Variable Name innodb_max_dirty_pages_pct Varia...

Страница 1269: ...y 100 bytes in size and it is permissible to have 100MB of unpurged InnoDB table rows The lag value is displayed as the history list length in the TRANSACTIONS section of InnoDB Monitor output For example if the output includes the following lines the lag value is 20 TRANSACTIONS Trx id counter 0 290328385 Purge done for trx s n o 0 290315608 undo n o 0 17 History list length 20 innodb_mirrored_lo...

Страница 1270: ...he binary log is smaller or shorter than it should be See Section 5 2 3 The Binary Log This variable was removed in MySQL 5 0 3 having been made obsolete by the introduction of XA transaction support You should set innodb_support_xa 1250 to ON or 1 to ensure consistency See innodb_support_xa 1250 innodb_support_xa Version Introduced 5 0 3 Command Line Format innodb_support_xa Option File Format in...

Страница 1271: ... Scope Global Dynamic Variable Yes The number of times a thread waits for an InnoDB mutex to be freed before the thread is suspended The default value is 20 This variable was added in MySQL 5 0 3 innodb_table_locks Command Line Format innodb_table_locks Option File Format innodb_table_locks Option Sets Variable Yes innodb_table_locks 1251 Variable Name innodb_table_locks Variable Scope Global Sess...

Страница 1272: ...rency before MySQL 5 0 19 From 5 0 19 on you can disable thread concurrency checking by setting the value to 0 Disabling thread concurrency checking enables InnoDB to create as many threads as it needs The default value has changed several times 8 before MySQL 5 0 8 20 infinite from 5 0 8 through 5 0 18 0 infinite from 5 0 19 to 5 0 20 and 8 finite from 5 0 21 on innodb_thread_sleep_delay Version ...

Страница 1273: ...lue of the variable is 1 ON to use the original algorithm for compatibility with existing applications The variable can be set to 0 OFF to use the new algorithm with improved randomness sync_binlog 1472 Version Introduced 5 0 1 Command Line Format sync binlog Option File Format sync_binlog Option Sets Variable Yes sync_binlog 1472 Variable Name sync_binlog Variable Scope Global Dynamic Variable Ye...

Страница 1274: ... TABLE STATUS FROM test LIKE customers The statistics SHOW displays for InnoDB tables are only approximate They are used in SQL optimization Table and index reserved sizes in bytes are accurate though 14 2 3 1 How to Use Transactions in InnoDB with Different APIs By default each client that connects to the MySQL server begins with autocommit mode enabled which automatically commits every SQL state...

Страница 1275: ...ight be good to insert big tables in pieces INSERT INTO newtable SELECT FROM oldtable WHERE yourkey something AND yourkey somethingelse After all records have been inserted you can rename the tables During the conversion of big tables you should increase the size of the InnoDB buffer pool to reduce disk I O Do not use more than 80 of the physical memory though You can also increase the sizes of th...

Страница 1276: ...CREMENT column in an INSERT InnoDB treats the row as if the value had not been specified and generates a new value for it The behavior of the auto increment mechanism is not defined if a user assigns a negative value to the column or if the value becomes bigger than the maximum integer that can be stored in the specified integer type When accessing the auto increment counter InnoDB uses a special ...

Страница 1277: ...ential ON DELETE CASCADE Cascading operations may not be nested more than 15 levels deep Like MySQL in general in an SQL statement that inserts deletes or updates many rows InnoDB checks UNIQUE and FOREIGN KEY constraints row by row When performing foreign key checks InnoDB sets shared row level locks on child or parent records it has to look at InnoDB checks foreign key constraints immediately th...

Страница 1278: ...fy data A transaction that fails for example because of a foreign key violation or because it is rolled back is not written to the binary log so it is not sent to slaves See Section 13 3 1 START TRANSACTION COMMIT and ROLLBACK Syntax Replication and CASCADE Cascading actions for InnoDB tables on the master are replicated on the slave only if the tables sharing the foreign key relation use InnoDB o...

Страница 1279: ...fc2 The slave s copy of fc2 still contains all of the rows that were originally inserted slave SELECT FROM fc2 m n 1 1 3 1 2 2 3 rows in set 0 00 sec This difference is due to the fact that the cascading deletes are handled internally by the InnoDB storage engine which means that none of the changes are logged 14 2 4 Adding Removing or Resizing InnoDB Data and Log Files This section describes what...

Страница 1280: ... ibdata2 50M autoextend When you add a new file to the tablespace configuration make sure that it does not exist InnoDB will create and initialize the file when you restart the server Currently you cannot remove a data file from the tablespace To decrease the size of your tablespace use this procedure 1 Use mysqldump to dump all your InnoDB tables 2 Stop the server 3 Remove all the existing tables...

Страница 1281: ...e the format is simpler the chance for serious data corruption is smaller mysqldump also has a single transaction 304 option for making a consistent snapshot without locking out other clients See Section 7 3 1 Establishing a Backup Policy Replication works with InnoDB tables so you can use MySQL replication capabilities to keep a copy of your database at database sites requiring high availability ...

Страница 1282: ...tion do not depend on the redo log other than for logging the writes and are performed in parallel with normal processing These include Rolling back incomplete transactions Any transactions that were active at the time of crash or fast shutdown Insert buffer merge Applying changes from the insert buffer tree from the shared tablespace to leaf pages of secondary indexes as the index pages are read ...

Страница 1283: ...able that is causing the runaway rollback 14 2 5 3 InnoDB Checkpoints InnoDB implements a checkpoint mechanism known as fuzzy checkpointing InnoDB flushes modified database pages from the buffer pool in small batches There is no need to flush the buffer pool in one single batch which would in practice stop processing of user SQL statements during the checkpointing process During crash recovery Inn...

Страница 1284: ...pically several users are permitted to lock every row in InnoDB tables or any random subset of the rows without causing InnoDB memory exhaustion In InnoDB all user activity occurs inside a transaction If autocommit mode is enabled each SQL statement forms a single transaction on its own By default MySQL starts the session for each new connection with autocommit enabled so MySQL does a commit after...

Страница 1285: ...larity locking which permits coexistence of record locks and locks on entire tables To make locking at multiple granularity levels practical additional types of locks called intention locks are used Intention locks are table locks in InnoDB The idea behind intention locks is for a transaction to indicate which type of lock shared or exclusive it will require later for a row in that table There are...

Страница 1286: ... DELETE FROM t WHERE i 1 ERROR 1213 40001 Deadlock found when trying to get lock try restarting transaction Deadlock occurs here because client A needs an X lock to delete the row However that lock request cannot be granted because client B already has a request for an X lock and is waiting for client A to release its S lock Nor can the S lock held by A be upgraded to an X lock because of the prio...

Страница 1287: ...ou do not see the row as having been deleted Inserts and updates are treated similarly You can advance your timepoint by committing your transaction and then doing another SELECT or START TRANSACTION WITH CONSISTENT SNAPSHOT This is called multi versioned concurrency control In the following example session A sees the row inserted by B only when B has committed the insert and A has committed as we...

Страница 1288: ...set by LOCK IN SHARE MODE and FOR UPDATE reads are released when the transaction is committed or rolled back As an example of a situation in which a locking read is useful suppose that you want to insert a new row into a table child and make sure that the child row has a parent row in table parent The following discussion describes how to implement referential integrity in application code Suppose...

Страница 1289: ...or a lock on the gap before the first or after the last index record Next key lock This is a combination of a record lock on the index record and a gap lock on the gap before the index record Record locks always lock index records even if a table is defined with no indexes For such cases InnoDB creates a hidden clustered index and uses this index for record locking See Section 14 2 9 1 Clustered a...

Страница 1290: ...conflicting Gap locking can be disabled explicitly This occurs if you change the transaction isolation level to READ COMMITTED 1121 or enable the innodb_locks_unsafe_for_binlog 1244 system variable Under these circumstances gap locking is disabled for searches and index scans and is used only for foreign key constraint checking and duplicate key checking There is also another effect of using the R...

Страница 1291: ...nt that would exclude the row InnoDB does not remember the exact WHERE condition but only knows which index ranges were scanned The locks are normally next key locks that also block inserts into the gap immediately before the record However gap locking can be disabled explicitly which causes next key locking not to be used For more information see Section 14 2 7 4 InnoDB Record Gap and Next Key Lo...

Страница 1292: ...tween 4 and 7 with insert intention locks prior to obtaining the exclusive lock on the inserted row but do not block each other because the rows are nonconflicting If a duplicate key error occurs a shared lock on the duplicate index record is set This use of a shared lock can result in deadlock should there be multiple sessions trying to insert the same row if another session already has an exclus...

Страница 1293: ...way it was done originally CREATE TABLE SELECT performs the SELECT with shared next key locks or as a consistent read as for INSERT SELECT For REPLACE INTO T SELECT FROM S WHERE InnoDB sets shared next key locks on rows from S While initializing a previously specified AUTO_INCREMENT column on a table InnoDB sets an exclusive lock on the end of the index associated with the AUTO_INCREMENT column In...

Страница 1294: ...value of the innodb_lock_wait_timeout 1244 system variable When InnoDB performs a complete rollback of a transaction all locks set by the transaction are released However if just a single SQL statement is rolled back as a result of an error some of the locks set by the statement may be preserved This happens because InnoDB stores row locks in a format such that it cannot know afterward which lock ...

Страница 1295: ...he tablespace This information is stored in a data structure called a rollback segment after an analogous data structure in Oracle Internally InnoDB adds three fields to each row stored in the database A 6 byte DB_TRX_ID field indicates the transaction identifier for the last transaction that inserted or updated the row Also a deletion is treated internally as an update where a special bit in the ...

Страница 1296: ...IMARY KEY for your table MySQL picks the first UNIQUE index that has only NOT NULL columns as the primary key and InnoDB uses it as the clustered index If the table has no PRIMARY KEY or suitable UNIQUE index InnoDB internally generates a hidden clustered index on a synthetic column containing row ID values The rows are ordered by the ID that InnoDB assigns to the rows in such a table The row ID i...

Страница 1297: ... significant slowdown on disk bound queries Another significant background I O operation is the purge thread see Section 14 2 8 InnoDB Multi Versioning 14 2 9 4 Adaptive Hash Indexes If a table fits almost entirely in main memory the fastest way to perform queries on it is to use hash indexes InnoDB has a mechanism that monitors index searches made to the indexes defined for a table If InnoDB noti...

Страница 1298: ... N the bit vector occupies CEILING N 8 bytes For example if there are anywhere from 9 to 15 columns that can be NULL the bit vector uses two bytes Columns that are NULL do not occupy space other than the bit in this vector The variable length part of the header also contains the lengths of variable length columns Each length takes one or two bytes depending on the maximum length of the column If a...

Страница 1299: ...bles are allocated However in a newly created tablespace InnoDB allocates space starting from the first data file The tablespace consists of database pages with a default size of 16KB The pages are grouped into extents of size 1MB 64 consecutive pages The files inside a tablespace are called segments in InnoDB The term rollback segment is somewhat confusing because it actually contains many tables...

Страница 1300: ...h as this takes more time than it should take SELECT COUNT FROM t WHERE a_non_indexed_column 12345 In the preceding query we are fooling the SQL optimizer into scanning the clustered index rather than a secondary index Most disks can read 10MB s to 50MB s which can be used to estimate how fast a table scan should be It can speed up index scans if you periodically perform a null ALTER TABLE operati...

Страница 1301: ...ks are not released in a rollback of a single SQL statement During implicit rollbacks as well as during the execution of an explicit ROLLBACK SQL statement SHOW PROCESSLIST displays Rolling back in the State column for the relevant connection 14 2 11 1 InnoDB Error Codes The following is a nonexhaustive list of common InnoDB specific errors that you may encounter with information about why each oc...

Страница 1302: ...EPERM Operation not permitted 2 ENOENT No such file or directory 3 ESRCH No such process 4 EINTR Interrupted system call 5 EIO I O error 6 ENXIO No such device or address 7 E2BIG Arg list too long 8 ENOEXEC Exec format error 9 EBADF Bad file number 10 ECHILD No child processes 11 EAGAIN Try again 12 ENOMEM Out of memory 13 EACCES Permission denied 14 EFAULT Bad address 15 ENOTBLK Block device requ...

Страница 1303: ...RROR_INVALID_DRIVE The system cannot find the drive specified 16 ERROR_CURRENT_DIRECTORY The directory cannot be removed 17 ERROR_NOT_SAME_DEVICE The system cannot move the file to a different disk drive 18 ERROR_NO_MORE_FILES There are no more files 19 ERROR_WRITE_PROTECT The media is write protected 20 ERROR_BAD_UNIT The system cannot find the device specified 21 ERROR_NOT_READYThe device is not...

Страница 1304: ...ariable length character sets such as utf8 or sjis CHAR N will occupy a variable amount of space at least N bytes Transaction Management Tips Wrap several modifications into a single transaction to reduce the number of flush operations InnoDB must flush the log to disk at each transaction commit if that transaction made modifications to the database The rotation speed of a disk is typically at mos...

Страница 1305: ...ather than setting innodb_flush_method 1243 if you want direct I O for the log files Users of the Veritas file system VxFS should use the convosync direct mount option You are advised to perform tests with and without raw partitions or direct I O file systems to verify whether performance is improved on your system Other MySQL data files such as those for MyISAM tables should not be placed on a di...

Страница 1306: ...les If you often have recurring queries for tables that are not updated frequently enable the query cache mysqld query_cache_type 1 query_cache_size 10M 14 2 12 2 SHOW ENGINE INNODB STATUS and the InnoDB Monitors InnoDB Monitors provide information about the InnoDB internal state This information is useful for performance tuning Each Monitor can be enabled by creating a table with a special name w...

Страница 1307: ...every 15 seconds Server output usually is directed to the error log see Section 5 2 1 The Error Log This data is useful in performance tuning On Windows you must start the server from a command prompt in a console window with the console 404 option if you want to direct the output to the window rather than to the error log InnoDB sends diagnostic output to stderr or to files rather than to stdout ...

Страница 1308: ...ns 108462 OS waits 37964 RW excl spins 681824 OS waits 375485 LATEST FOREIGN KEY ERROR 030709 13 00 59 Transaction TRANSACTION 0 290328284 ACTIVE 0 sec process no 3195 OS thread id 34831 inserting 15 lock struct s heap size 2496 undo log entries 9 MySQL thread id 25 query id 4668733 localhost heikki update insert into ibtest11a D B C values 5 khDk khDk Foreign key constraint fails for table test i...

Страница 1309: ...jgghggjgjgjgjgjggjgjgjgjgjgggjgjg jlhhgghggggghhjhghgggggghjhghghghghghhhhghghghjhhjghjghjkghjghjghjghjfhjfh TRANSACTION 0 290328383 ACTIVE 0 sec process no 3180 OS thread id 28684 committing 1 lock struct s heap size 320 undo log entries 1 MySQL thread id 19 query id 4668734 localhost heikki update insert into speedcm values 1603393 1 hgjhjgghggjgjgjgjgjggjgjgjgjgjgggjgj gjlhhgghggggghhjhghgggggg...

Страница 1310: ...43 in additional pool allocated 1402624 Buffer pool size 3200 Free buffers 110 Database pages 3074 Modified db pages 2674 Pending reads 0 Pending writes LRU 0 flush list 0 single page 0 Pages read 171380 created 51968 written 194688 28 72 reads s 20 72 creates s 47 55 writes s Buffer pool hit rate 999 1000 ROW OPERATIONS 0 queries inside InnoDB 0 queries in queue Main thread process no 3004 id 717...

Страница 1311: ...stem variable INSERT BUFFER AND ADAPTIVE HASH INDEX This section shows the status of the InnoDB insert buffer and adaptive hash index See Section 14 2 9 3 Insert Buffering and Section 14 2 9 4 Adaptive Hash Indexes The contents include the number of operations performed for each plus statistics for hash index performance LOG This section displays information about the InnoDB log The contents inclu...

Страница 1312: ... 0 fragm pages 1 free extents 0 not full extents 0 pages 0 NUMBER of file segments 73 Validating tablespace Validation ok END OF INNODB TABLESPACE MONITOR OUTPUT The Tablespace Monitor output includes information about the shared tablespace as a whole followed by a list containing a breakdown for each segment within the tablespace The tablespace consists of database pages with a default size of 16...

Страница 1313: ...ent to ensure good sequentiality of data For the example segment shown earlier it has 32 fragment pages plus 2 full extents 64 pages each for a total of 160 pages used out of 160 pages allocated The following segment has 32 fragment pages and one partially full extent using 14 pages for a total of 46 pages used out of 96 pages allocated SEGMENT id 0 1 space 0 page 2 res 96 used 46 full ext 0 fragm...

Страница 1314: ... DATA_SYS prtype 257 len 6 prec 0 DB_ROLL_PTR DATA_SYS prtype 258 len 7 prec 0 INDEX name ID_IND id 0 14 fields 2 6 type 3 root page 49 appr key vals 1 leaf pages 1 size pages 1 FIELDS ID POS DB_TRX_ID DB_ROLL_PTR FOR_COL_NAME REF_COL_NAME TABLE name test child id 0 14 columns 11 indexes 2 appr rows 210 COLUMNS par_id DATA_INT len 4 prec 0 child_id DATA_INT len 4 prec 0 name DATA_VARCHAR prtype 52...

Страница 1315: ...ATA_xxx symbols for a given column prtype The column s precise type This field includes information such as the column data type character set code nullability signedness and whether it is a binary string This field is described in the innobase include data0type h source file len The column length in bytes prec The precision of the type Each INDEX part of the table section provides the name and ch...

Страница 1316: ...ENGINE INNODB STATUS and the InnoDB Monitors If the problem is performance related or your server appears to be hung you should use the standard Monitor to print information about the internal state of InnoDB If the problem is with locks use the Lock Monitor If the problem is in creation of tables or other data dictionary operations use the Table Monitor to print the contents of the InnoDB interna...

Страница 1317: ...in backticks Thus you can drop such an orphaned table like any other orphaned table using the method described earlier To copy or rename a file in the Unix shell you need to put the file name in double quotation marks if the file name contains With innodb_file_per_table 1241 enabled the following message might occur if the frm or ibd files or both are missing InnoDB in InnoDB data dictionary has t...

Страница 1318: ...ing systems files must be less than 2GB This is not a limitation of InnoDB itself but if you require a large tablespace you will need to configure it using several smaller data files rather than one or a file large data files The combined size of the InnoDB log files must be less than 4GB The minimum tablespace size is 10MB The maximum tablespace size is four billion database pages 64TB This is al...

Страница 1319: ...of some table index In MySQL 5 0 before MySQL 5 0 3 InnoDB does not support the AUTO_INCREMENT table option for setting the initial sequence value in a CREATE TABLE or ALTER TABLE statement To set the value with InnoDB insert a dummy row with a value one less and delete that dummy row or insert the first row with an explicit value specified While initializing a previously specified AUTO_INCREMENT ...

Страница 1320: ...saction and using stored routines to reduce client server latency delays Applications should commit transactions before doing time consuming client side operations 14 3 The MERGE Storage Engine The MERGE storage engine also known as the MRG_MyISAM engine is a collection of identical MyISAM tables that can be used as one Identical means that all tables have identical column and index information Yo...

Страница 1321: ... the set of underlying tables Similarly a column with a UNIQUE index in the underlying tables should be indexed in the MERGE table but not as a UNIQUE index After creating the MERGE table you can use it to issue queries that operate on the group of tables as a whole mysql SELECT FROM total a message 1 Testing 2 table 3 t1 1 Testing 2 table 3 t2 To remap a MERGE table to a different collection of M...

Страница 1322: ... 36 see Section 14 3 2 MERGE Table Problems As of MySQL 5 0 44 if a MERGE table cannot be opened or used because of a problem with an underlying table CHECK TABLE displays information about which table caused the problem Additional Resources A forum dedicated to the MERGE storage engine is available at http forums mysql com list php 93 14 3 1 MERGE Table Advantages and Disadvantages MERGE tables c...

Страница 1323: ...nts Index reads are slower When you read an index the MERGE storage engine needs to issue a read on all underlying tables to check which one most closely matches a given index value To read the next index value the MERGE storage engine needs to search the read buffers to find the next value Only when one index buffer is used up does the storage engine need to read the next index block This makes M...

Страница 1324: ...le including column changes column ordering and engine alterations will cause the statement to fail Prior to MySQL 5 0 36 table checks are applied as follows When you create or alter MERGE table there is no check to ensure that the underlying tables are existing MyISAM tables and have identical structures When the MERGE table is used MySQL checks that the row length for all mapped tables is equal ...

Страница 1325: ...on To specify that you want to create a MEMORY table indicate that with an ENGINE table option CREATE TABLE t i INT ENGINE MEMORY The older term TYPE is supported as a synonym for ENGINE for backward compatibility but ENGINE is the preferred term and TYPE is deprecated As indicated by the engine name MEMORY tables are stored in memory They use hash indexes by default which makes them very fast and...

Страница 1326: ...rary tables are MEMORY tables are never converted to disk tables If an internal temporary table becomes too large the server automatically converts it to on disk storage as described in Section 8 8 5 How MySQL Uses Internal Temporary Tables The maximum size of MEMORY tables is limited by the max_heap_table_size 468 system variable which has a default value of 16MB To have larger or smaller MEMORY ...

Страница 1327: ... Do not change the global max_heap_table_size 468 value unless you intend the value to be used for MEMORY tables created by all clients The following example creates two MEMORY tables with a maximum size of 1MB and 2MB respectively mysql SET max_heap_table_size 1024 1024 Query OK 0 rows affected 0 00 sec mysql CREATE TABLE t1 id INT UNIQUE id ENGINE MEMORY Query OK 0 rows affected 0 01 sec mysql S...

Страница 1328: ...e following error occurs when you start mysqld it means that the BDB storage engine is not supported for your architecture bdb architecture lacks fast mutexes applications cannot be threaded Can t init databases In this case you must rebuild MySQL without BDB support or start the server with the skip bdb 420 option 14 5 2 Installing BDB If you have downloaded a binary version of MySQL that include...

Страница 1329: ... No bdb logdir 1309 Yes Yes Global No Variable bdb_logdir Yes Global No bdb_max_lock 439 Yes Yes Yes Global No bdb no recover 1310 Yes Yes bdb shared data 1310 Yes Yes Global No Variable bdb_shared_data Yes Global No bdb tmpdir 1310 Yes Yes Global No Variable bdb_tmpdir Yes Global No have_bdb 454 Yes Global No skip bdb 420 Yes Yes skip sync bdb logs 1310 Yes Yes Yes Global No sync bdb logs 1310 Ye...

Страница 1330: ...upted See Section 2 18 1 3 Starting and Troubleshooting the MySQL Server With the bdb_max_lock 439 variable you can specify the maximum number of locks that can be active on a BDB table The default is 10 000 You should increase this if errors such as the following occur when you perform long transactions or when mysqld has to examine many rows to execute a query bdb Lock table is out of available ...

Страница 1331: ...rimary index but in secondary indexes as well If all columns that you access in a BDB table are part of the same index or part of the primary key MySQL can execute the query without having to access the actual row In a MyISAM table this can be done only if the columns are part of the same index Sequential scanning is slower for BDB tables than for MyISAM tables because the data in BDB tables is st...

Страница 1332: ...onsequence of this it is not possible to move BDB table files from one database directory to another When making backups of BDB tables you must either use mysqldump or else make a backup that includes the files for each BDB table the frm and db files as well as the BDB log files The BDB storage engine stores unfinished transactions in its log files and requires them to be present when mysqld start...

Страница 1333: ...bases rather than in local tables The FEDERATED storage engine is available beginning with MySQL 5 0 3 This storage engine enables data to be accessed from a remote MySQL database on a local server without using replication or cluster technology When using a FEDERATED table queries on the local server are automatically executed on the remote federated tables No data is stored on the local tables T...

Страница 1334: ...et each column is converted to internal storage engine format that the FEDERATED engine expects and can use to display the result to the client that issued the original statement The local server communicates with the remote server using MySQL client C API functions It invokes mysql_real_query to send the statement To read a result set it uses mysql_store_result and fetches rows one at a time usin...

Страница 1335: ...t number are optional Sample connection strings CONNECTION mysql username password hostname port database tablename CONNECTION mysql username hostname database tablename CONNECTION mysql username password hostname database tablename The use of CONNECTION for specifying the connection string is nonoptimal and is likely to change in future Keep this in mind for applications that use FEDERATED tables...

Страница 1336: ... the failed one instead of rolling back the statement completely This occurred because the rows were treated as individual inserts As of MySQL 5 0 46 FEDERATED performs bulk insert handling such that multiple rows are sent to the remote table in a batch This provides a performance improvement Also if the remote table is transactional it enables the remote storage engine to perform statement rollba...

Страница 1337: ... be seen partially A SELECT never causes a flush of a bulk insert unless a normal insert occurs while it is loading Retrieval On retrieval rows are uncompressed on demand there is no row cache A SELECT operation performs a complete table scan When a SELECT occurs it finds out how many rows are currently available and reads that number of rows SELECT is performed as a consistent read Note that lots...

Страница 1338: ...ords 2 Duplicates 0 Warnings 0 mysql SELECT FROM test Empty set 0 00 sec The BLACKHOLE storage engine is included in MySQL binary distributions To enable this storage engine if you build MySQL from source invoke configure with the with blackhole storage engine option To examine the source for the BLACKHOLE engine look in the sql directory of a MySQL source distribution When you create a BLACKHOLE ...

Страница 1339: ... of dump file syntax Measurement of the overhead from binary logging by comparing performance using BLACKHOLE with and without binary logging enabled BLACKHOLE is essentially a no op storage engine so it could be used for finding performance bottlenecks not related to the storage engine itself Blackhole Engine and Auto Increment Columns The Blackhole engine is a no op engine Any operations perform...

Страница 1340: ...ll therefore fail due to trying insert a row with a duplicate value for a primary key column In row based replication the value that the engine returns for the row always be the same for each insert This will result in the slave attempting to replay two insert log entries using the same value for the primary key column and so replication will fail ...

Страница 1341: ...me can result in significant loss of revenue and reputation There is no one size fits all approach to delivering High Availability HA Unique application attributes business requirements operational capabilities and legacy infrastructure can all influence HA technology selection And technology is only one element in delivering HA people and processes are just as critical as the technology itself My...

Страница 1342: ...tions Each architecture used to achieve highly available database services is differentiated by the levels of uptime it offers These architectures can be grouped into three main categories Data Replication Clustered Virtualized Systems Shared Nothing Geographically Replicated Clusters As illustrated in the following figure each of these architectures offers progressively higher levels of uptime wh...

Страница 1343: ...ion No Asynchronous and Semisynchronous Yes N A Shared Storage Yes Shared Storage No Distributed No Distributed Yes No Distributed Geographic redundancy support Yes Yes via MySQL Replication Yes via MySQL Replication Yes via MySQL Replication Update Schema On Line No No No Yes Scalability Number of Nodes One Master Multiple Slaves One Active primary one Passive secondary Node One Active primary on...

Страница 1344: ... within a server pool during maintenance operations Instructions for the creation deployment and use of the Oracle VM Template for MySQL Enterprise Edition are available from The Oracle VM Template for MySQL Enterprise Edition whitepaper http www mysql com why mysql white papers mysql_wp_oracle vm template for mee php The README file accompanying the download of the Template To download the Oracle...

Страница 1345: ...t and in standby mode on the other Pacemaker and Corosync combine to provide the clustering layer that sits between the services and the underlying hosts and operating systems Pacemaker is responsible for starting and stopping services ensuring that they are running on exactly one host thus delivering high availability and avoiding data corruption Corosync provides the underlying messaging infrast...

Страница 1346: ...e core Pacemaker process does not have built in knowledge of the specific services to be managed instead it uses agents that provide a wrapper for the service specific actions For example in this solution we use agents for Virtual IP Addresses MySQL and DRBD these are all existing agents and come packaged with Pacemaker ...

Страница 1347: ...ies Pacemaker and Corosync cluster messaging and management processes Oracle Linux operating system Download the guide at http www mysql com why mysql white papers mysql high availability drbd configuration deployment guide Support for DRBD The complete DRBD stack for MySQL has been certified by Oracle and commercial support is available as part of MySQL Enterprise Edition and Oracle Linux Premier...

Страница 1348: ...nce MySQL recovery has completed and it starts accepting connections MySQL with Windows Failover Clustering requires at least 2 servers within the cluster together with shared storage for example FC AL SAN or iSCSI disks The MySQL binaries and data files are stored in the shared storage and Windows Failover Clustering ensures that only one of the cluster nodes will access those files at any point ...

Страница 1349: ...ation and the applications you can deploy and create any environment you choose This includes a basic MySQL server in addition to more extensive replication HA and scalability scenarios that enable you to take advantage of the EC2 environment and the ability to deploy additional instances as the demand for your MySQL services and applications grow To aid the deployment and distribution of work thr...

Страница 1350: ... the write performance of the new device is significantly lower on the initial writes until the initialization process has finished To avoid this problem when setting up a new instance you should start the initialization process before populating your MySQL database One way to do this is to use dd to write to the file system root shell dd if dev zero of initialize bs 1024M count 50 The preceding c...

Страница 1351: ...ice However if you use EBS you can attach an EBS storage volume to an EC2 instance and that EBS volume is persistent Like a disk an EBS volume can fail but it is possible to create point in time snapshots of the volume Snapshots are persisted to Amazon S3 and can be used to restore data in the event of volume failure To replicate your EC2 instances to a non EC2 environment be aware of the transfer...

Страница 1352: ...es to one or more slaves three in this example with a web server running on each replication slave You can reproduce this structure completely within the EC2 environment using an EC2 instance for the master and one instance for each of the web and MySQL slave servers Note Within the EC2 environment internal private IP addresses used by the EC2 instances are constant Always use these internal addre...

Страница 1353: ...y allocating individual machines or machine groups to provide a unique set of data according to an appropriate group For example you might put all users with a surname ending in the letters A D onto a single server When a user connects to the application and their surname is known queries can be redirected to the appropriate MySQL server When using sharding with EC2 separate the web server and MyS...

Страница 1354: ...aker Corosync Oracle Linux The ZFS file system provides functionality to create a snapshot of the file system contents transfer the snapshot to another machine and extract the snapshot to recreate the file system You can create a snapshot at any time and you can create as many snapshots as you like By continually creating transferring and restoring snapshots you can provide synchronization between...

Страница 1355: ...time and metadata of when the snapshot was created As more changes to the original file system are made the size of the snapshot increases because more space is required to keep the record of the old blocks If you create lots of snapshots say one per day and then delete the snapshots from earlier in the week the size of the newer snapshots might also increase as the changes that make up the newer ...

Страница 1356: ...pool snapshot2 ssh id host pfexec zfs recv slavepool This operation only succeeds if the file system on the slave machine has not been modified at all You cannot apply the incremental changes to a destination file system that has changed In the example above the ls command would cause problems by changing the metadata such as the last access time for files or directories To prevent changes on the ...

Страница 1357: ...d up from our mid INSERT snapshot InnoDB The log sequence number in ibdata files does not match InnoDB the log sequence number in the ib_logfiles 081109 15 59 59 InnoDB Database was not shut down normally InnoDB Starting crash recovery InnoDB Reading tablespace information from the ibd files InnoDB Restoring possible half written data pages from the doublewrite InnoDB buffer 081109 16 00 03 InnoDB...

Страница 1358: ...contacted keeping the process lightweight The same algorithm is used again when a client requests the same key The same key generates the same hash and the same memcached server is selected as the source for the data Using this method the cached data is spread among all of the memcached servers and the cached information is accessible from any client The result is a distributed memory based cache ...

Страница 1359: ...d To install memcached on a Gentoo host use emerge root shell emerge install memcached Building memcached from Source On other Unix based platforms including Solaris AIX HP UX and Mac OS X and Linux distributions not mentioned already you must install from source For Linux make sure you have a 2 6 based kernel which includes the improved epoll interface For all platforms ensure that you have libev...

Страница 1360: ...start the memcached service on one or more servers Running memcached sets up the server allocates the memory and starts listening for connections from clients Note You do not need to be a privileged user root to run memcached except to listen on one of the privileged TCP IP ports below 1024 You must however use a user that has not had their memory limits restricted using setrlimit or similar To st...

Страница 1361: ...page disk faults cpu r b w swap free re mf pi po fr de sr s1 s2 in sy cs us sy id 0 0 0 5170504 3450392 2 7 2 0 0 0 4 0 0 0 0 296 54 199 0 0 100 For example to allocate 3GB of RAM shell memcached m 3072 On 32 bit x86 systems where you are using PAE to access memory above the 4GB limit you cannot allocate RAM beyond the maximum process size You can get around this by running multiple instances of m...

Страница 1362: ...to reduce the number of connections to prevent overloading memcached service or to increase the number to make more effective use of the server running memcached server t threads Specify the number of threads to use when processing incoming requests By default memcached is configured to use 4 concurrent threads The threading improves the performance of storing and retrieving data in the cache usin...

Страница 1363: ...ng an object within the memcached instance The size supports a unit postfix k for kilobytes m for megabytes For example to increase the maximum supported object size to 32MB shell memcached I 32m The maximum object size you can specify is 128MB the default remains at 1MB This option was added in 1 4 2 b Set the backlog queue limit The backlog queue configures how many network connections can be wa...

Страница 1364: ...nd topologies The exact strategy to use depends on your application and environment When developing a system for deploying memcached within your system keep in mind the following points memcached is only a caching mechanism It shouldn t be used to store information that you cannot otherwise afford to lose and then load from a different location There is no security built into the memcached protoco...

Страница 1365: ...ugh space within a suitable slab to store the value then an existing least recently used LRU object is removed evicted from the cache to make room for the new item The LRU algorithm ensures that the object that is removed is one that is either no longer in active use or that was used so long ago that its data is potentially out of date or of little value However in a system where the memory alloca...

Страница 1366: ...s You can summarize the process in pseudocode as memcservers a memc b memc c memc value hash key chosen value length memcservers Replacing the above with values memcservers a memc b memc c memc value hash myid chosen 7009 3 In the above example the client hashing algorithm chooses the server at index 1 7009 3 1 and store or retrieve the key and value with that server Note This selection and hashin...

Страница 1367: ... from the ID The problem with client side selection of the server is that the list of the servers including their sequential order must remain consistent on each client using the memcached servers and the servers must be available If you try to perform an operation on a key when A new memcached instance has been added to the list of available instances A memcached instance has been removed from th...

Страница 1368: ...t list of servers The consistency is enforced only within a single client With a modula hashing algorithm the client selects a server by first computing the hash and then choosing a server from the list of configured servers As the list of servers changes so the server selected when using a modula hashing algorithm also changes The result is the behavior described above changes to the list of serv...

Страница 1369: ...Fired when a connection is dispatched from the main or connection management thread to a worker thread Arguments connid The connection ID threadid The thread ID slabs allocate size slabclass slabsize ptr Allocate memory from the slab allocator Arguments size The requested size slabclass The allocation is fulfilled in this class slabsize The size of each item in this class ptr A pointer to allocate...

Страница 1370: ...de an insight into how well the hash function operates Traversals are a sign of a less optimal function wasting CPU capacity Arguments key The key searched for depth The depth in the list of hash table assoc insert key nokeys Fired when a new item has been inserted Arguments key The key just inserted nokeys The total number of keys currently being stored including the key for which insert was call...

Страница 1371: ... The item s key size The size of the data item replace oldkey oldsize newkey newsize Fired when an item is being replaced with another item Arguments oldkey The key of the item to replace oldsize The size of the old item newkey The key of the new item newsize The size of the new item process command start connid request size Fired when the processing of a command starts Arguments connid The connec...

Страница 1372: ...ents connid The connection ID key The requested key size The size of the key s data or 1 if not found casid The casid for the item command add connid key size Fired for a add command Arguments connid The connection ID key The requested key size The new size of the key s data or 1 if not found command set connid key size Fired for a set command Arguments connid The connection ID key The requested k...

Страница 1373: ...ments connid The connection ID key The requested key size The new size of the key s data or 1 if not found command cas connid key size casid Fired for a cas command Arguments connid The connection ID key The requested key size The size of the key s data or 1 if not found casid The cas ID requested command incr connid key val Fired for incr command Arguments connid The connection ID key The request...

Страница 1374: ...locks then a new slab is created divided up into blocks of a suitable size If an existing slab with the right block size already exists but there are no free blocks a new slab is created If you update an existing item with data that is larger than the existing block allocation for that key then the key is re allocated into a suitable slab For example the default size for the smallest block is 88 b...

Страница 1375: ...mentation within when building memcached from source then memcached uses multiple threads in addition to the libevent system to handle requests When enabled the threading implementation operates as follows Threading is handled by wrapping functions within the code to provide basic protection from updating the same global structures at the same time Each thread uses its own instance of the libevent...

Страница 1376: ...n information about the listen queues and buffers used to send information A sample of the output generated for a TCP IP based system with the default memory and growth factors is given below shell memcached vv slab class 1 chunk size 80 perslab 13107 slab class 2 chunk size 104 perslab 10082 slab class 3 chunk size 136 perslab 7710 slab class 4 chunk size 176 perslab 5957 slab class 5 chunk size ...

Страница 1377: ...to suit the data you are storing in the cache For example if you set the growth factor to 4 quadrupling the size of each slab shell memcached f 4 m 1g vv slab class 1 chunk size 80 perslab 13107 slab class 2 chunk size 320 perslab 3276 slab class 3 chunk size 1280 perslab 819 slab class 4 chunk size 5120 perslab 204 slab class 5 chunk size 20480 perslab 51 slab class 6 chunk size 81920 perslab 12 ...

Страница 1378: ...read to conn_closing 32 connection closed All of the verbosity levels in memcached are designed to be used during debugging or examination of issues The quantity of information generated particularly when using vvv is significant particularly on a busy server Also be aware that writing the error information out especially to disk may negate some of the performance gains you achieve by using memcac...

Страница 1379: ...ative language interface When practical use memcached to store full items rather than caching a single column value from the database For example when displaying a record about an object invoice user history or blog post load all the data for the associated entry from the database and compile it into the internal structure that would normally be required by the application Save the complete object...

Страница 1380: ...alue is available to the next client that requests it from the cache For a flow diagram of this sequence see Figure 15 8 Typical memcached Application Flowchart Figure 15 8 Typical memcached Application Flowchart Adapting Database Best Practices to memcached Applications The most direct way to cache MySQL data is to use a 2 column table where the first column is a primary key Because of the unique...

Страница 1381: ... the servers configured within the main memcached_st structure or separately populate a list of servers and then add this list to the memcached_st structure The latter method is used in the following example Once the server list has been set you can call the functions to store or retrieve data A simple application for setting a preset value to localhost is provided here include stdio h include str...

Страница 1382: ...ers defined in the structure 15 6 3 3 2 libmemcached Server Functions The libmemcached API uses a list of servers stored within the memcached_server_st structure to act as the list of servers used by the rest of the functions To use memcached you first create the server list and then apply the list of servers to a valid libmemcached object Because the list of servers and the list of servers within...

Страница 1383: ...ndividual servers are of the form server port The return value is a server list structure 15 6 3 3 3 libmemcached Set Functions The set related functions within libmemcached provide the same functionality as the core functions supported by the memcached protocol The full definition for the different functions is the same for all the base functions add replace prepend append For example the functio...

Страница 1384: ...ver memcached_prepend_by_key memc master_key master_key_length key key_length value value_length expiration flags Similar to the memcached_prepend but has the option of an additional master key that can be used to identify an individual server memcached_append_by_key memc master_key master_key_length key key_length value value_length expiration flags Similar to the memcached_append but has the opt...

Страница 1385: ...corresponding value char memcached_fetch memcached_st ptr const char key size_t key_length size_t value_length uint32_t flags memcached_return error The function returns the key value with the key key_length and value_length parameters being populated with the corresponding key and length information The function returns NULL when there are no more values to be returned A full example including th...

Страница 1386: ...rned green 15 6 3 3 5 Controlling libmemcached Behaviors The behavior of libmemcached can be modified by setting one or more behavior flags These can either be set globally or they can be applied during the call to individual functions Some behaviors also accept an additional setting such as the hashing mechanism used when selecting servers To set global behaviors memcached_return memcached_behavi...

Страница 1387: ...peration or closing the connection causes the data to be flushed MEMCACHED_BEHAVIOR_VERIFY_KEY Forces libmemcached to verify that a specified key is valid MEMCACHED_BEHAVIOR_SORT_HOSTS If set hosts added to the list of configured hosts for a memcached_st structure are placed into the host list in sorted order This breaks consistent hashing if that behavior has been enabled MEMCACHED_BEHAVIOR_CONNE...

Страница 1388: ...192 168 0 101 11211 192 168 0 102 11211 Note When using the Cache Memcached interface with multiple servers the API automatically performs certain operations across all the servers in the group For example getting statistical information through Cache Memcached returns a hash that contains data on a host by host basis as well as generalized statistics for all the servers in the group You can set a...

Страница 1389: ...delete Generic delete incr Generic incr decr Generic decr Below is a complete example for using memcached with Perl and the Cache Memcached module usr bin perl use Cache Memcached use DBI use Data Dumper Configure the memcached server my cache new Cache Memcached servers localhost 11211 Get the film name from the command line memcached keys must not contain spaces so create a key name by replacing...

Страница 1390: ...base and cached When accessing a film that has already been added to the cache shell memcached sakila pl ROCK INSTINCT Film data loaded from Memcached 15 6 3 5 Using MySQL and memcached with Python The Python memcache module interfaces to memcached servers and is written in pure Python that is without using one of the C APIs You can download and install a copy from Python Memcached To install down...

Страница 1391: ...instance the core functions provide the same functionality as in the generic interface specification The following table provides a summary of the supported functions Python memcache Function Equivalent Generic Function get Generic get get_multi keys Gets multiple values from the supplied array of keys Returns a hash reference of key value pairs set Generic set set_multi dict expiry key_prefix Set...

Страница 1392: ... 60 second expiry time the data is loaded from memcached and dumped shell python memc_python py Loaded data from memcached 2 ACE GOLDFINGER 7 AIRPLANE SIERRA 8 AIRPORT POLLOCK 10 ALADDIN CALENDAR 13 ALI FOREVER The serialization and deserialization happens automatically Because serialization of Python data may be incompatible with other interfaces and languages you can change the serialization mod...

Страница 1393: ...or example php cache new Memcache cache connect localhost 11211 This opens an immediate connection to the specified server To use multiple memcached servers you need to add servers to the memcache object using addServer bool Memcache addServer string host int port bool persistent int weight int timeout int retry_interval bool status callback failure_callback The server management mechanism within ...

Страница 1394: ...d into the memcached instance is recorded as a mysqli result row and the API automatically serializes the information for you php memc new Memcache memc addServer localhost 11211 if empty _POST film html xmlns http www w3 org 1999 xhtml xml lang en lang en head meta http equiv Content Type content text html charset utf 8 title Simple Memcache Lookup title head body form method post p b Film b inpu...

Страница 1395: ...ternal libraries such as libmemcached You can obtain the installer package from http www deveiate org projects RMemCache To install extract the package and then run install rb shell install rb If you have RubyGems you can install the Ruby MemCache gem shell gem install Ruby MemCache Bulk updating Gem source index for http gems rubyforge org Install required dependency io reactor Yn y Successfully ...

Страница 1396: ...ween Java and other interfaces are not compatible If this is a problem use JSON or a similar nonbinary serialization format On most systems you can download the package and use the jar directly To use the com danga MemCached interface you create a MemCachedClient instance and then configure the list of servers by configuring the SockIOPool Through the pool specification you set up the server list ...

Страница 1397: ... get Generic get getMulti keys Get the values of multiple keys returning the information as Hash map using java lang String for the keys and java lang Object for the corresponding values set Generic set add Generic add replace Generic replace delete Generic delete incr Generic incr decr Generic decr 15 6 3 9 Using the memcached TCP Text Protocol Communicating with a memcached server can be achieve...

Страница 1398: ...fied key to the supplied value only if the supplied casunique matches This is effectively the equivalent of change the information if nobody has updated it since I last fetched it key The key All data is stored using a the specific key The key cannot contain control characters or whitespace and can be up to 250 characters in size flags The flags for the operation as an integer Flags in memcached a...

Страница 1399: ...ion commands take the form delete key time noreply Where key The key name time The time in seconds or a specific Unix time for which the client wishes the server to refuse add or replace commands on this key All add replace get and gets commands fail during this period set operations succeed After this period the key is deleted permanently and all commands are accepted If not supplied the value is...

Страница 1400: ...eturn If not specified the general statistics are returned value A specific value to be used when performing certain statistics operations The return value is a list of statistics data formatted as follows STAT name value The statistics are terminated with a single line END For more information see Section 15 6 4 Getting memcached Statistics For reference a list of the different commands supported...

Страница 1401: ...me conditions the server may disconnect the client after this error occurs VALUE keys flags length The requested key has been found and the stored key flags and data block are returned of the specified length DELETED The requested key was deleted from the server STAT name value A line of statistics data END The end of the statistics data 15 6 4 Getting memcached Statistics The memcached system has...

Страница 1402: ...ched module the stats function returns information about all the servers currently configured in the connection object and total statistics for all the memcached servers as a whole For example the following Perl script obtains the stats and dumps the hash reference that is returned use Cache Memcached use Data Dumper my memc new Cache Memcached memc set_servers ARGV print Dumper memc stats When ex...

Страница 1403: ...s see Section 15 6 4 4 memcached Size Statistics Detailed status detail see Section 15 6 4 5 memcached Detail Statistics 15 6 4 1 memcached General Statistics The output of the general statistics provides an overview of the performance and use of the memcached instance The statistics returned by the command and their meaning is shown in the following table The following terms are used to define th...

Страница 1404: ...ete and not found 1 3 x incr_hits 64u Number of keys that have been incremented and found present 1 3 x incr_misses 64u Number of items that have been incremented and not found 1 3 x decr_hits 64u Number of keys that have been decremented and found present 1 3 x decr_misses 64u Number of items that have been decremented and not found 1 3 x cas_hits 64u Number of keys that have been compared and sw...

Страница 1405: ...nks_per_page 10082 STAT 1 total_pages 1 STAT 1 total_chunks 10082 STAT 1 used_chunks 10081 STAT 1 free_chunks 1 STAT 1 free_chunks_end 10079 STAT 9 chunk_size 696 STAT 9 chunks_per_page 1506 STAT 9 total_pages 63 STAT 9 total_chunks 94878 STAT 9 used_chunks 94878 STAT 9 free_chunks 0 STAT 9 free_chunks_end 0 STAT active_slabs 2 STAT total_malloced 67083616 END Individual stats for each slab class ...

Страница 1406: ... relatively few chunks actually in use within each slab Increasing the growth factor creates fewer slab classes and therefore makes better use of the allocated pages 15 6 4 3 memcached Item Statistics To get the items statistics use the stats items command or the API equivalent The items statistics give information about the individual items allocated within a given slab class STAT items 2 number ...

Страница 1407: ...64 448 51 480 30 512 54 544 39 576 10065 Caution Running this statistic locks up your cache as each item is read from the cache and its size calculated On a large cache this may take some time and prevent any set or get operations until the process completes The item size statistics are useful only to determine the sizes of the objects you are storing Since the actual memory allocation is relevant...

Страница 1408: ...ng memcached tool The memcached tool located within the scripts directory within the memcached source directory The tool provides convenient access to some reports and statistics from any memcached instance The basic format of the command is shell memcached tool hostname port command The default output produces a list of the slab allocations and usage For example shell memcached tool localhost 112...

Страница 1409: ...s in this slab Full Whether the slab is fully populated Evicted The number of objects evicted from this slab Evict_Time The time in seconds since the last eviction OOM The number of items that have triggered an out of memory error You can also obtain a dump of the general statistics for the server using the stats command shell memcached tool localhost 11211 stats localhost 11211 Field Value accept...

Страница 1410: ...atabase coordinated across multiple instances of memcached 16 6 5 12 1392 Is compression available 16 6 5 13 1392 Can we implement different types of memcached as different nodes in the same server so can there be deterministic and non deterministic in the same server 16 6 5 14 1392 What are best practices for testing an implementation to ensure that it improves performance and to measure the impa...

Страница 1411: ...servers and keys will automatically be redistributed to another memcached server in the list If retaining the cache content on all your servers is important make sure you use an API that supports a consistent hashing algorithm For more information see Section 15 6 2 4 memcached Hashing Distribution Types 16 6 5 6 What is a recommended hardware configuration for a memcached server memcached has a v...

Страница 1412: ...ion during storage 16 6 5 13 Can we implement different types of memcached as different nodes in the same server so can there be deterministic and non deterministic in the same server Yes You can run multiple instances of memcached on a single server and in your client configuration you choose the list of servers you want to use 16 6 5 14 What are best practices for testing an implementation to en...

Страница 1413: ...ime or progress and separately log the results The proxy enables you to perform additional monitoring filtering or manipulation of queries without requiring you to make any modifications to the client and without the client even being aware that it is communicating with anything but a genuine MySQL server This documentation covers MySQL Proxy 0 8 2 And MySQL Proxy contains third party code For lic...

Страница 1414: ...ed directory then modify your PATH environment variable so that you can use the mysql proxy command directly shell cd usr local shell tar zxf mysql proxy 0 8 2 platform tar gz shell PATH PATH usr local mysql proxy 0 8 2 platform sbin To update the path globally on a system you might need administrator privileges to modify the appropriate etc profile etc bashrc or other system configuration file On...

Страница 1415: ...are installed into usr local share 15 7 2 3 Installing MySQL Proxy from the Bazaar Repository The MySQL Proxy source is available through a public Bazaar repository and is the quickest way to get the latest releases and fixes A build from the Bazaar repository requires that the following prerequisite components be installed Bazaar 1 10 0 or later libtool 1 5 or higher autoconf 2 56 or higher autom...

Страница 1416: ...DisplayName MySQL Proxy start auto binPath C Program Files MySQL mysql proxy 0 8 2 bin mysql proxy svc exe proxy backend addresses 127 0 0 1 3306 Note The space following the equal sign after each property is required failure to include it results in an error The preceding command creates a new service called Proxy You can start and stop the service using the net start stop command with the servic...

Страница 1417: ...escription help 1399 Show help options help admin 1399 Show admin module options help all 1399 Show all help options help proxy 1399 Show proxy module options Table 15 5 mysql proxy Admin Options Format Option File Description admin address host port 1399 admin address host port 1399 The admin module listening host and port admin lua script file_name 1399 admin lua script file_name 1399 Script to ...

Страница 1418: ...00 keepalive 1400 Try to restart the proxy if a crash occurs log backtrace on crash 1401 log backtrace on crash 1401 Try to invoke the debugger and generate a backtrace on crash log file file_name 1401 log file file_name 1401 The file where error messages are logged log level level 1401 log level level 1401 The logging level log use syslog 1401 log use syslog 1401 Log errors to syslog lua cpath di...

Страница 1419: ...t 1399 Command Line Format admin address host port Option File Format admin address host port Permitted Values Type string Default 4041 The host name or IP address and port for the administration port The default is localhost 4041 admin lua script file_name 1399 Command Line Format admin lua script file_name Option File Format admin lua script file_name Permitted Values Type file name Default The ...

Страница 1420: ...sedir dir_name Option File Format basedir dir_name Permitted Values Type directory name The base directory to use as a prefix for all other file name configuration options The base name should be an absolute not relative directory If you specify a relative directory mysql proxy generates an error during startup daemon 1400 Command Line Format daemon Option File Format daemon Starts the proxy in da...

Страница 1421: ...1401 Command Line Format log file file_name Option File Format log file file_name Permitted Values Type file name The file to use to record log information If this option is not given mysql proxy logs to the standard error output log level level 1401 Command Line Format log level level Option File Format log level level Permitted Values Type enumeration Valid Values error warning info message debu...

Страница 1422: ...imum number of open files and sockets supported by the mysql proxy process Certain scripts might require a higher value no proxy 1402 Command Line Format no proxy Option File Format no proxy Disable the proxy module plugin dir dir_name 1402 Command Line Format plugin dir dir_name Option File Format plugin dir dir_name Permitted Values Type directory name The directory to use when loading plugins f...

Страница 1423: ...ault is for this information not to be set Note Setting this value only configures the servers within the corresponding internal structure see proxy global backends 1411 You can determine the backend type by checking the type field for each connection You should therefore only use this option in combination with a script designed to make use of the different backend types When using this option on...

Страница 1424: ... no change user Disable use of the MySQL protocol CHANGE_USER command when reusing a connection from the pool of connections specified by the proxy backend addresses list proxy skip profiling 1404 Command Line Format proxy skip profiling Option File Format proxy skip profiling Disable query profiling statistics time tracking The default is for tracking to be enabled proxy fix bug 25371 1404 Versio...

Страница 1425: ...o your MySQL server through the proxy by specifying the host name and port details shell mysql host localhost port 4040 If your server requires authentication information this will be passed through natively without alteration by mysql proxy so you must also specify the required authentication information shell mysql host localhost port 4040 user user_name password password You can also connect to...

Страница 1426: ...MySQL Proxy Scripting 1406 The following diagram shows an overview of the classes exposed by MySQL Proxy ...

Страница 1427: ...MySQL Proxy Scripting 1407 ...

Страница 1428: ...If you have not explicitly injected queries within the read_query function this function is not triggered You can use this to edit the result set or to remove or filter the result sets generated from additional queries you injected into the queue when using read_query The following table lists MySQL proxy and server communication functions the supplied information and the direction of information ...

Страница 1429: ...r each result set and each invocation can decide which result set to return to the client For example you can queue additional queries into the global query queue to be processed by the server This can be used to add statistical information by adding queries before and after the original query changing the original query SELECT FROM City Into a sequence of queries SELECT NOW SELECT FROM City SELEC...

Страница 1430: ...ption connection A structure containing the active client connections For a list of attributes see proxy connection 1410 servers A structure containing the list of configured backend servers For a list of attributes see proxy global backends 1411 queries A structure containing the queue of queries that will be sent to the server during a single client query For a list of attributes see proxy queri...

Страница 1431: ...ndx which is the index into this table of the backend server being used by the active connection The attributes for each entry within the proxy global backends table are shown in the following table Attribute Description dst name The combined address port of the backend server dst address The IP address of the backend server dst port The port of the backend server connected_clients The number of c...

Страница 1432: ... if you only want to monitor the queries sent and the basic statistics To perform any kind of manipulation on the returned data you must set the flag to true which will Store the result set so that it can be processed Enable modification of the result set before it is returned to the client Enable you to discard the result set instead of returning it to the client proxy response The proxy response...

Страница 1433: ...RR proxy response errmsg my first error return proxy PROXY_SEND_RESULT proxy response resultset The proxy response resultset structure should be populated with the rows and columns of data to return The structure contains the information about the entire result set with the individual elements of the data shown in the following table The following table describes the attributes of the proxy respon...

Страница 1434: ...describe the status of a network packet These items are entries within the main proxy table Constant Description MYSQLD_PACKET_OK The packet is OK MYSQLD_PACKET_ERR The packet contains error information MYSQLD_PACKET_RAW The packet contains raw data Backend State Type Constants The following constants are used either to define the status or type of the backend MySQL server to which the proxy is co...

Страница 1435: ...CT_OUT Connect out COM_REGISTER_SLAVE Register slave COM_STMT_PREPARE Prepare server side statement COM_STMT_EXECUTE Execute server side statement COM_STMT_SEND_LONG_DATALong data COM_STMT_CLOSE Close server side statement COM_STMT_RESET Reset statement COM_SET_OPTION Set option COM_STMT_FETCH Fetch statement COM_DAEMON Daemon MySQL 5 1 only COM_ERROR Error MySQL Type Constants These constants are...

Страница 1436: ... the proxy accepts a connection from a MySQL client the connect_server function is called There are no arguments to the function but you can use and if necessary manipulate the information in the proxy connection table which is unique to each client session For example if you have multiple backend servers you can specify which server that connection should use by setting the value of proxy connect...

Страница 1437: ... proxy response errmsg only local connects are allowed print we don t like this client return proxy PROXY_SEND_RESULT end end Note that you must return an error packet to the client by using proxy PROXY_SEND_RESULT 15 7 4 5 Examining the Authentication Credentials with read_auth The read_auth function is triggered when an authentication handshake is initiated by the client In the execution sequenc...

Страница 1438: ...ants 1414 we extract the query from the packet and print it The structure of the packet type supplied is important In the case of a COM_QUERY packet the remaining contents of the packet are the text of the query string In this example no changes have been made to the query or the list of queries that will ultimately be sent to the MySQL server To modify a query or add new queries you must populate...

Страница 1439: ...e number of microseconds required to receive the last row of the result set since the query was sent to the server resultset The content of the result set data By accessing the result information from the MySQL server you can extract the results that match the queries that you injected return different result sets for example from a modified query and even create your own result sets The following...

Страница 1440: ...s to a single server To use MySQL Proxy in this mode you just have to specify on the command line the backend server to which the proxy should connect shell mysql proxy proxy backend addresses sakila 3306 If you specify multiple backend MySQL servers the proxy connects each client to each server in a round robin fashion Suppose that you have two MySQL servers A and B The first client to connect is...

Страница 1441: ...used as the interface to the administration service by using the admin lua script 1399 script option to point to a Lua script For example you can create a basic interface to the internal components of the mysql proxy system using the following script written by Diego Medina Copyright 2008 2010 Oracle and or its affiliates All rights reserved This program is free software you can redistribute it an...

Страница 1442: ...D_PACKET_OK proxy response resultset fields type proxy MYSQL_TYPE_LONG name query_counter rows proxy global query_counter we have our result send it back return proxy PROXY_SEND_RESULT elseif command show and option myerror then proxy response type proxy MYSQLD_PACKET_ERR proxy response errmsg my first error return proxy PROXY_SEND_RESULT elseif string sub packet 2 lower select help then return sh...

Страница 1443: ... dataset local header Id IP Address Time local rows for t_i t_v in pairs proxy global process do for s_i s_v in pairs t_v do table insert rows t_i s_v ip os date c s_v ts end end return make_dataset header rows end function show_process_help local dataset local header command description local rows SELECT HELP This command SHOW PROXY PROCESSLIST Show all connections and their true IP Address retur...

Страница 1444: ...this program if not write to the Free Software Foundation Inc 51 Franklin Street Fifth Floor Boston MA 02110 1301 USA reporter lua See http www chriscalender com p 41 Thanks to Chris Calender See http datacharmer blogspot com 2009 01 mysql proxy is back html Thanks Giuseppe Maxia proxy global query_counter proxy global query_counter or 0 function proxy global initialize_process_table if proxy glob...

Страница 1445: ...r lua In a different window connect to the MySQL server through the proxy shell mysql user root password password port 4040 Welcome to the MySQL monitor Commands end with or g Your MySQL connection id is 1798669 Server version 5 0 70 log Gentoo Linux mysql 5 0 70 r1 Type help or h for help Type c to clear the buffer mysql In another different window connect to the mysql proxy admin service using t...

Страница 1446: ... Proxy currently accomplish this My goal is to minimize connection latency while keeping temporary tables available 16 7 6 13 1428 Are these reserved function names for example error_result that get automatically called 16 7 6 14 1428 As the script is re read by MySQL Proxy does it cache this or is it looking at the file system with each request 16 7 6 15 1428 Given that there is a connect_server ...

Страница 1447: ...nd MySQL servers are read only shell mysql proxy proxy backend addresses 10 0 1 2 3306 proxy read only backend addresses 10 0 1 3 3306 16 7 6 2 How do I use a socket with MySQL Proxy Proxy change logs mention that support for UNIX sockets has been added Specify the path to the socket proxy backend addresses path to socket 16 7 6 3 Can I use MySQL Proxy with all versions of MySQL MySQL Proxy is des...

Страница 1448: ...ion latency while keeping temporary tables available Yes 16 7 6 13 Are these reserved function names for example error_result that get automatically called Only functions and values starting with proxy are provided by the proxy All others are user provided 16 7 6 14 As the script is re read by MySQL Proxy does it cache this or is it looking at the file system with each request It looks for the scr...

Страница 1449: ...ed that none of the MySQL servers are listening on the same port 16 7 6 24 What about caching the authorization information so clients connecting are given back end connections that were established with identical authorization information thus saving a few more round trips There is an proxy pool no change user 1404 option that provides this functionality 16 7 6 25 Is there any big web site using ...

Страница 1450: ...efault value is version dependent 16 7 6 31 Would the Java only connection pooling solution work for multiple web servers With this I would assume that you can pool across many web servers at once Yes But you can also start one proxy on each application server to get a similar behavior as you have it already ...

Страница 1451: ... not be connected permanently to receive updates from the master This means that updates can occur over long distance connections and even over temporary or intermittent connections such as a dial up service Depending on the configuration you can replicate all databases selected databases or even selected tables within a database For answers to some questions often asked by those who are new to My...

Страница 1452: ... binary log is stored in different logging formats according to the database changes being recorded Slaves are configured to read the binary log from the master and to execute the events in the binary log on the slave s local database The master is dumb in this scenario Once binary logging has been enabled all statements are recorded in the binary log Each slave receives a copy of the entire conte...

Страница 1453: ... If you already have data on your master and you want to use it to synchronize your slave you will need to create a data snapshot You can create a snapshot using mysqldump see Section 16 1 1 5 Creating a Data Snapshot Using mysqldump or by copying the data files directly see Section 16 1 1 6 Creating a Data Snapshot Using Raw Data Files You will need to configure the slave with settings for connec...

Страница 1454: ...st but are commented out uncomment the options and alter them according to your needs For example to enable binary logging using a log file name prefix of mysql bin and configure a server ID of 1 use these lines mysqld log bin mysql bin server id 1 After making the changes restart the server Note If you omit server id 1442 or set it explicitly to its default value of 0 a master refuses connections...

Страница 1455: ...acccount use CREATE USER To grant this account the privileges required for replication use the GRANT statement If you create an account solely for the purposes of replication that account needs only the REPLICATION SLAVE 577 privilege For example to set up a new user repl that can connect for replication from any host within the mydomain com domain issue these statements on the master mysql CREATE...

Страница 1456: ...ave the client running so that the lock remains in place and then proceed to Section 16 1 1 5 Creating a Data Snapshot Using mysqldump or Section 16 1 1 6 Creating a Data Snapshot Using Raw Data Files The idea here is to prevent any further changes so that the data copied to the slaves is in synchrony with the master If you are setting up a brand new master and slave replication group you can exit...

Страница 1457: ...d_file 453 ft_min_word_len 452 or ft_max_word_len 452 and you are copying tables having full text indexes If you are using InnoDB tables you can use the MySQL Enterprise Backup tool to obtain a consistent snapshot This tool records the log name and offset corresponding to the snapshot to be later used on the slave MySQL Enterprise Backup is a nonfree commercial tool that is not included in the sta...

Страница 1458: ...efore starting the slave replication process 16 1 1 7 Setting Up Replication with New Master and Slaves The easiest and most straightforward method for setting up replication is to use new master and slave servers You can also use this method if you are setting up new servers but have an existing dump of the databases from a different server that you want to load into your replication configuratio...

Страница 1459: ...od opportunity to take a snapshot of its databases You should obtain the master status see Section 16 1 1 4 Obtaining the Replication Master Binary Log Coordinates before taking down the master updating the configuration and taking a snapshot For information on how to create a snapshot using raw data files see Section 16 1 1 6 Creating a Data Snapshot Using Raw Data Files 3 If your master server i...

Страница 1460: ...ues specified in the statement to update the status files automatically Note The content of master info overrides some of the server options specified on the command line or in my cnf See Section 16 1 2 Replication and Binary Logging Options and Variables for more details A single snapshot of the master suffices for multiple slaves To set up additional slaves use the same master snapshot and follo...

Страница 1461: ...is section 3 Copy the master info and relay log info files from the existing slave to the new slave if they were not located in the data directory These files hold the current log coordinates for the master s binary log and the slave s relay log 4 Start the existing slave 5 On the new slave edit the configuration and give the new slave a unique server id 1442 not used by the master or any of the e...

Страница 1462: ...On the master and each slave you must use the server id 1442 option to establish a unique replication ID in the range from 1 to 2 32 1 Unique means that each ID must be different from every other ID in use by any other replication master or slave Example server id 3 If you omit server id 1442 the default ID is 0 in which case a master refuses connections from all slaves and a slave refuses to conn...

Страница 1463: ...N Y N Y N Global abort slave event count 1451 Y N N Y N Global disconnect slave event count 1451 Y N N Y Y Global init_slave 1464 Y N Y Y Y Global log slave updates 1451 Y N N Y Y Global log_slave_updates 1471 Y N N Y N Global master connect retry 1453 Y N N Y N Global master host 1453 Y N N Y N Global master info file 1453 Y N N Y N Global master password 1453 Y N N Y N Global master port 1453 Y ...

Страница 1464: ...ndex 1455 Y N N Y N Global relay log info file 1456 Y N N Y Y Global relay_log_info_file 1465 Y N N Y Y Global relay_log_index 1464 Y N N Y Y Global relay_log_purge 489 Y N Y Y Y Global relay_log_space_limit 490 Y N N Y N Global replicate do db 1457 Y N N Y N Global replicate do table 1458 Y N N Y N Global replicate ignore db 1457 Y N N Y N Global replicate ignore table 1458 Y N N Y N Global repli...

Страница 1465: ...obal slave_compressed_protocol 1465 Y N Y Y Y Global slave_net_timeout 1462 Y N Y Y Y Global slave_transaction_retries 1466 Y N Y N Y Global sql_slave_skip_counter 1467 N N Y Section 16 1 2 2 Replication Master Options and Variables provides more detailed information about options and variables relating to replication master servers For more information about options and variables relating to repl...

Страница 1466: ...sqld see Section 5 1 1 Server Option and Variable Reference 16 1 2 2 Replication Master Options and Variables This section describes the server options and system variables that you can use on replication master servers You can specify the options either on the command line or in an option file You can specify system variable values using SET On the master and each slave you must use the server id...

Страница 1467: ...35 instead Attempting to set the value of auto_increment_increment 1446 or auto_increment_offset 1449 to a noninteger value gives rise to an error and the actual value of the variable remains unchanged These two variables affect AUTO_INCREMENT column behavior as follows auto_increment_increment 1446 controls the interval between successive column values For example mysql SHOW VARIABLES LIKE auto_i...

Страница 1468: ...nc2 col 5 15 25 35 4 rows in set 0 02 sec If the value of auto_increment_offset 1449 is greater than that of auto_increment_increment 1446 the value of auto_increment_offset 1449 is ignored Should one or both of these variables be changed and then new rows inserted into a table containing an AUTO_INCREMENT column the results may seem counterintuitive because the series of AUTO_INCREMENT values is ...

Страница 1469: ...ting the session value or until mysqld is restarted If the local value is set the new value affects AUTO_INCREMENT columns for all tables into which new rows are inserted by the current user for the duration of the session unless the values are changed during that session The auto_increment_increment 1446 variable was added in MySQL 5 0 2 Its default value is 1 See Section 16 4 1 1 Replication and...

Страница 1470: ...2 Replication Relay and Status Logs If you upgrade an older server before MySQL 4 1 1 to a newer version the new server upgrades the master info file to the new format automatically when it starts However if you downgrade a newer server to a version older than 4 1 1 you should manually remove the first line before starting the older server for the first time Note that in this case the downgraded s...

Страница 1471: ... slave servers Many of these options can be set while the server is running by using the CHANGE MASTER TO statement Others such as the replicate options can be set only when the slave server starts Replication related system variables are discussed later in this section abort slave event count 1451 Command Line Format abort slave event count Option File Format abort slave event count Permitted Val...

Страница 1472: ...oth a master and a slave You must start both A and B with log bin 1467 to enable binary logging and B with the log slave updates 1451 option so that updates received from A are logged by B to its binary log log warnings level 414 Command Line Format log warnings W Option File Format log warnings Option Sets Variable Yes log_warnings 464 Variable Name log_warnings Variable Scope Global Session Dyna...

Страница 1473: ...17 Permitted Values Type string The host name or IP address of the master replication server The value in master info takes precedence if it can be read If no master host is specified the slave thread does not start master info file file_name 1453 Command Line Format master info file file_name Option File Format master info file file_name Permitted Values Type file name Default master info The nam...

Страница 1474: ...ttempted at intervals set by the master connect retry 1453 option or the MASTER_CONNECT_RETRY option of the CHANGE MASTER TO statement and reconnects are triggered when data reads by the slave time out according to the slave net timeout 1462 option The default value is 86400 A value of 0 means infinite the slave attempts to connect forever master ssl 1454 master ssl ca file_name master ssl capath ...

Страница 1475: ...tes the file in the data directory unless the basename is given with a leading absolute path name to specify a different directory The server creates relay log files in sequence by adding a numeric suffix to the basename Due to the manner in which MySQL parses server options if you specify this option you must supply a value the default basename is used only if the option is not actually specified...

Страница 1476: ...file Option Sets Variable Yes relay_log_info_file 1465 Permitted Values Type file name Default relay log info The name to use for the file in which the slave records information about the relay logs The default name is relay log info in the data directory For information about the format of this file see Section 16 2 2 2 Slave Status Logs relay log purge 0 1 1456 Disable or enable automatic purgin...

Страница 1477: ...000 The main reason for this check just the default database behavior is that it is difficult from the statement alone to know whether it should be replicated for example if you are using multiple table DELETE or multiple table UPDATE statements that go across multiple databases It is also faster to check only the default database rather than all databases if there is no need If you need cross dat...

Страница 1478: ...ow Servers Evaluate Replication Filtering Rules This option affects only statements that apply to tables It does not affect statements that apply only to other database objects such as stored routines To filter statements operating on stored routines use one or more of the replicate db options replicate ignore table db_name tbl_name 1458 Command Line Format replicate ignore table name Option File ...

Страница 1479: ...nt to use replicate same server id 1459 be sure to start the slave with this option before you make the slave read its own events that you want the slave SQL thread to execute replicate wild do table db_name tbl_name 1459 Command Line Format replicate wild do table name Option File Format replicate wild do table Permitted Values Type string Tells the slave thread to restrict replication to stateme...

Страница 1480: ...nd the table name starts with bar For information about how matching works see the description of the replicate wild do table 1459 option The rules for including literal wildcard characters in the option value are the same as for replicate wild ignore table 1460 as well report host host_name 1460 Command Line Format report host host_name Option File Format report host Option Sets Variable Yes repo...

Страница 1481: ...o be reported to the master during slave registration Set this only if the slave is listening on a nondefault port or if you have a special tunnel from the master or other clients to the slave If you are not sure do not use this option report user user_name 1461 Command Line Format report user name Option File Format report user Option Sets Variable Yes report_user Variable Name report user Variab...

Страница 1482: ...e_name 1462 The name of the directory where the slave creates temporary files This option is by default equal to the value of the tmpdir 502 system variable When the slave SQL thread replicates a LOAD DATA INFILE statement it extracts the file to be loaded from the relay log into temporary files and then loads these into the table If the file loaded on the master is huge the temporary files on the...

Страница 1483: ...pportunity to resolve the inconsistency in the data manually This option tells the slave SQL thread to continue replication when a statement returns any of the errors listed in the option value Do not use this option unless you fully understand why you are getting errors If there are no bugs in your replication setup and client programs and no bugs in MySQL itself an error that stops replication s...

Страница 1484: ...a slave server each time the SQL thread starts The format of the string is the same as for the init_connect 456 variable Note The SQL thread sends an acknowledgment to the client before it executes init_slave 1464 Therefore it is not guaranteed that init_slave 1464 has been executed when START SLAVE returns See Section 13 4 2 7 START SLAVE Syntax for more information relay_log 1464 Command Line Fo...

Страница 1485: ...ay logs The default name is relay log info in the data directory rpl_recovery_rank 1465 This variable is unused and is removed in MySQL 5 6 slave_compressed_protocol 1465 Command Line Format slave_compressed_protocol Option File Format slave_compressed_protocol Option Sets Variable Yes slave_compressed_protocol 1465 Variable Name slave_compressed_protocol Variable Scope Global Dynamic Variable Yes...

Страница 1486: ...y slave_skip_errors 1466 Command Line Format slave skip errors name Option File Format slave skip errors Option Sets Variable Yes slave_skip_errors 1466 Variable Name slave_skip_errors Variable Scope Global Dynamic Variable No Permitted Values Type string Default OFF Valid Values list of error codes all Normally replication stops when an error occurs on the slave This gives you the opportunity to ...

Страница 1487: ...the master that a slave server should skip Important If skipping the number of events specified by setting this variable would cause the slave to begin in the middle of an event group the slave continues to skip until it finds the beginning of the next event group and begins from that point For more information see Section 13 4 2 6 SET GLOBAL sql_slave_skip_counter Syntax 16 1 2 4 Binary Log Optio...

Страница 1488: ...d Line Format log bin index name Option File Format log bin index Permitted Values Type file name Default OFF The index file for binary log file names See Section 5 2 3 The Binary Log If you omit the file name and if you did not specify one with log bin 1467 MySQL uses host_name bin index as the file name log bin trust function creators 0 1 1468 Version Introduced 5 0 16 Command Line Format log bi...

Страница 1489: ...d Variables binlog do db db_name 1469 Command Line Format binlog do db name Option File Format binlog do db Permitted Values Type string This option affects binary logging in a manner similar to the way that replicate do db 1457 affects replication Tell the server to restrict binary logging to updates for which the default database is db_name that is the database selected by USE All other database...

Страница 1490: ...o suppress binary logging of updates for which the default database is db_name that is the database selected by USE If you use this option you should ensure that you do updates only in the default database As with the binlog do db 1469 option there is an exception for the CREATE DATABASE ALTER DATABASE and DROP DATABASE statements The server uses the database named in the statement not the default...

Страница 1491: ...y log is enabled If the log bin 1467 option is used then the value of this variable is ON otherwise it is OFF This variable reports only on the status of binary logging enabled or disabled it does not actually report the value to which log bin 1467 is set See Section 5 2 3 The Binary Log log_slave_updates 1471 Command Line Format log slave updates Option File Format log_slave_updates Option Sets V...

Страница 1492: ...max_binlog_size 1472 Variable Name max_binlog_size Variable Scope Global Dynamic Variable Yes Permitted Values Type numeric Default 1073741824 Range 4096 1073741824 If a write to the binary log causes the current log file size to exceed the value of this variable the server rotates the binary logs closes the current file and opens the next one The minimum value is 4096 bytes The maximum and defaul...

Страница 1493: ...on has been started it should execute without requiring much regular administration Depending on your replication environment you will want to check the replication status of each slave periodically daily or even more frequently 16 1 3 1 Checking Replication Status The most common task when managing a replication process is to ensure that replication is taking place and that there have been no err...

Страница 1494: ...on accurately When the slave SQL thread has caught up on I O Seconds_Behind_Master displays 0 but when the slave I O thread is still queuing up a new event Seconds_Behind_Master may show a large value until the SQL thread finishes executing the new event This is especially likely when the events have old timestamps in such cases if you execute SHOW SLAVE STATUS several times in a relatively short ...

Страница 1495: ...a backup or other task The I O thread will continue to read events from the master but they are not executed This makes it easier for the slave to catch up when you restart the SQL thread Stopping only the I O thread enables the events in the relay log to be executed by the SQL thread up to the point where the relay log ends This can be useful when you want to pause execution to catch up with even...

Страница 1496: ...ter creates a thread to send the binary log contents to a slave when the slave connects This thread can be identified in the output of SHOW PROCESSLIST on the master as the Binlog Dump thread The binlog dump thread acquires a lock on the master s binary log for reading each event that is to be sent to the slave As soon as the event has been read the lock is released even before the event is sent t...

Страница 1497: ...at replication is not running that is no slaves are currently connected On a slave server the output from SHOW PROCESSLIST looks like this mysql SHOW PROCESSLIST G 1 row Id 10 User system user Host db NULL Command Connect Time 11 State Waiting for master to send event Info NULL 2 row Id 11 User system user Host db NULL Command Connect Time 11 State Has read all relay log waiting for the slave I O ...

Страница 1498: ...ted using successive sequence numbers beginning with 000001 The slave uses an index file to track the relay log files currently in use The default relay log index file name is host_name relay bin index in the data directory The default relay log file and relay log index file names can be overridden with respectively the relay log 1455 and relay log index 1455 server options see Section 16 1 2 Repl...

Страница 1499: ...om the master and in processing its own relay logs The master info log should be protected because it contains the password for connecting to the master See Section 6 1 2 3 Passwords and Logging The slave I O thread updates the master info log The following table shows the correspondence between the lines in the master info file and the columns displayed by SHOW SLAVE STATUS Line in master info SH...

Страница 1500: ...does not write a statement to its binary log the statement is not replicated If the server does log the statement the statement is sent to all slaves and each slave determines whether to execute it or ignore it On the master you can control which databases to log changes for by using the binlog do db 1469 and binlog ignore db 1470 options to control binary logging For a description of the rules th...

Страница 1501: ...g case sensitivity in filenames whereas table level filtering options are not regardless of platform This is true regardless of the value of the lower_case_table_names 466 system variable 16 2 3 1 Evaluation of Database Level Replication and Binary Logging Options When evaluating replication options the slave begins by checking to see whether there are any replicate do db 1457 or replicate ignore ...

Страница 1502: ... exit 2 Is there a default database has any database been selected by USE Yes Continue to step 3 No Ignore the statement and exit 3 There is a default database Are there any binlog do db 1469 options Yes Do any of them match the database Yes Log the statement and exit No Ignore the statement and exit No Continue to step 4 4 Do any of the binlog ignore db 1470 options match the database Yes Ignore ...

Страница 1503: ... occurs within a stored function in which case the slave executes the statement and exits Having reached this point if there are no table options the slave simply executes all statements If there are any replicate do table 1458 or replicate wild do table 1459 options the statement must match one of these if it is to be executed otherwise it is ignored If there are any replicate ignore table 1458 o...

Страница 1504: ...Rules 1484 The master info file should be protected because it contains the password for connecting to the master See Section 6 1 2 3 Passwords and Logging The following steps describe this evaluation in more detail 1 Are there any table options ...

Страница 1505: ...t and exit No Continue to step 5 No Continue to step 5 5 Are there any replicate wild ignore table 1460 options Yes Does the table match any of them Yes Ignore the statement and exit No Continue to step 6 No Continue to step 6 6 Are there any replicate do table 1458 or replicate wild do table 1459 options Yes Ignore the statement and exit No Execute the statement and exit 16 2 3 3 Replication Rule...

Страница 1506: ...iately moves to the next statement executed on the master 16 3 Replication Solutions Replication can be used in many different environments for a range of purposes This section provides general notes and advice on using replication for specific solution types For information on using replication in a backup environment including notes on the setup backup procedure and files to back up see Section ...

Страница 1507: ... that you need access to the data in an emergency However if the size of your data set is very large mysqldump may be impractical When using mysqldump you should stop replication on the slave before starting the dump process to ensure that the dump contains a consistent set of data 1 Stop the slave from processing requests You can stop replication completely on the slave using mysqladmin shell mys...

Страница 1508: ... data If you lose the relay logs but still have the relay log info file you can check it to determine how far the SQL thread has executed in the master binary logs Then you can use CHANGE MASTER TO with the MASTER_LOG_FILE and MASTER_LOG_POS options to tell the slave to re read the binary logs from that point This requires that the binary logs still exist on the master server If your slave is repl...

Страница 1509: ...ve replication process again mysql START SLAVE Although the storage_engine 497 and table_type 499 variables are not replicated be aware that CREATE TABLE and ALTER TABLE statements that include the engine specification will be correctly replicated to the slave For example if you have a CSV table and you execute mysql ALTER TABLE csvtable Engine MyISAM The above statement will be replicated to the ...

Страница 1510: ...l error conditions You can use different names for the functions The important thing is to have a unified interface for connecting for reads connecting for writes doing a read and doing a write Then convert your client code to use the wrapper library This may be a painful and scary process at first but it pays off in the long run All applications that use the approach just described are able to ta...

Страница 1511: ...e each replication slave as follows before executing START SLAVE Replication slave 1 should use replicate wild do table databaseA Replication slave 2 should use replicate wild do table databaseB Replication slave 3 should use replicate wild do table databaseC Each slave in this configuration receives the entire binary log from the master but executes only those events from the binary log that appl...

Страница 1512: ...vides the replication functionality to the remainder of the slaves in the replication structure Master 2 is the only machine permitted to connect to Master 1 Master 2 also has binary logging enabled and the log slave updates 1451 option so that replication instructions from Master 1 are also written to Master 2 s binary log so that they can then be replicated to the true slaves Slave 1 Slave 2 and...

Страница 1513: ...ecuting events from the specified binary log coordinates on the new master In a failover situation all the servers in the group are typically executing the same events from the same binary log file so changing the source of the events should not affect the database structure or integrity providing you are careful Run your slaves with the log bin 1467 option and without log slave updates 1451 In th...

Страница 1514: ...ves have processed any statements in their relay log On each slave issue STOP SLAVE IO_THREAD then check the output of SHOW PROCESSLIST until you see Has read all relay log When this is true for all slaves they can be reconfigured to the new setup On the slave Slave 1 being promoted to become the master issue STOP SLAVE and RESET MASTER On the other slaves Slave 2 and Slave 3 use STOP SLAVE and CH...

Страница 1515: ...er became unavailable Note that there is no synchronization between the different slaves to a master Some slaves might be ahead of others This means that the concept outlined in the previous example might not work In practice however the relay logs of different slaves will most likely not be far behind the master so it would work anyway but there is no guarantee A good way to keep your application...

Страница 1516: ... identifies the server private key On the slave you have two options available for setting the SSL information You can either add the slave certificates to the client section of the slave s my cnf file or you can explicitly specify the SSL information using the CHANGE MASTER TO statement To add the slave certificates using an option file add the following lines to the client section of the slave s...

Страница 1517: ...hen using pre production releases of MySQL For example the SLEEP 967 function is available beginning with MySQL 5 0 12 If you use this function on the master you cannot replicate to a slave that uses MySQL 5 0 11 or earlier For this reason use Generally Available GA releases of MySQL for statement based replication in a production setting since we do not introduce new SQL statements or change thei...

Страница 1518: ...ELECT FROM t1 ORDER BY col1 col2 Important To guarantee the same ordering on both master and slave the ORDER BY clause must name all columns of t1 The instructions just given are subject to the limitations of CREATE TABLE LIKE Foreign key definitions are ignored as are the DATA DIRECTORY and INDEX DIRECTORY table options If a table definition includes any of those characteristics create t2 using a...

Страница 1519: ...ays replicated even if the database table or view to be dropped does not exist on the master This is to ensure that the object to be dropped no longer exists on either the master or the slave once the slave has caught up with the master Beginning with MySQL 5 0 82 DROP IF EXISTS statements for stored programs stored procedures and functions triggers and events are also replicated even if the store...

Страница 1520: ...tions are replicated without change and thus do not work reliably on the slave For NOW 926 the binary log includes the timestamp This means that the value as returned by the call to this function on the master is replicated to the slave This can lead to a possibly unexpected result when replicating between MySQL servers in different time zones Suppose that the master is located in New York the sla...

Страница 1521: ...t you can do this SET my_uuid1 UUID my_uuid2 UUID INSERT INTO t VALUES my_uuid1 my_uuid2 However if the number of rows is large or unknown the workaround is difficult or impracticable For example you cannot convert the following statement to one in which a given individual user variable is associated with each row INSERT INTO t2 SELECT UUID FROM t1 Non delayed INSERT statements that refer to RAND ...

Страница 1522: ...IR TABLE to repair it you should first stop replication if it is still running before using REPAIR TABLE then afterward compare the master s and slave s copies of the table and be prepared to correct any discrepancies manually before restarting replication 16 4 1 13 Replication and Master or Slave Shutdowns It is safe to shut down a master server and restart it later When a slave loses its connect...

Страница 1523: ... to the slave Then it is safe to restart the slave The size of MEMORY tables is limited by the value of the max_heap_table_size 468 system variable which is not replicated see Section 16 4 1 28 Replication and Variables A change in max_heap_table_size takes effect for MEMORY tables that are created or updated using ALTER TABLE ENGINE MEMORY or TRUNCATE TABLE following the change or for all MEMORY ...

Страница 1524: ...lave recognizes that privilege related SQL statements have no effect and thus it does not execute those statements See Section 16 4 1 16 Replication of the mysql System Database for more information 16 4 1 18 Replication and the Query Optimizer It is possible for the data on the master and slave to become different if a statement is written in such a way that the data modification is nondeterminis...

Страница 1525: ...t or if a long update statement is killed after updating some of the rows If that happens on the master the slave expects execution of the statement to result in the same error code If it does not the slave SQL thread stops as described previously If you are replicating between tables that use different storage engines on the master and slave keep in mind that the same statement might produce a di...

Страница 1526: ...action are nontransactional they are written to the binary log immediately The remaining statements in the transaction are cached and not written to the binary log until the transaction is committed If the transaction is rolled back the cached statements are written to the binary log only if they make nontransactional changes that cannot be rolled back Otherwise they are discarded To apply this ru...

Страница 1527: ...even if the view contains a table that would normally be filtered out by replication ignore table rules Care should therefore be taken to ensure that views do not replicate table data that would normally be filtered for security reasons 16 4 1 28 Replication and Variables The foreign_key_checks 451 unique_checks 504 and sql_auto_is_null 493 variables are all replicated sql_mode 495 is also replica...

Страница 1528: ...oth master and slave In particular when a case sensitive file system is used and this variable set to 1 on the slave but to a different value on the master names of databases are not converted to lowercase which can cause replication to fail This is a known issue which is fixed in MySQL 5 6 16 4 2 Replication Compatibility Between MySQL Versions MySQL supports replication from one major version to...

Страница 1529: ...Section 16 4 3 Upgrading a Replication Setup for more information Use of row based replication Row based replication was implemented in MySQL 5 1 5 so you cannot replicate using row based replication from any MySQL 5 0 or later master to a slave older than MySQL 5 1 5 Note Row based replication is not available in MySQL 5 0 For more information about row based replication in MySQL 5 1 see Replicat...

Страница 1530: ...nnect using TCP IP use the skip networking 421 option when you restart the master 3 With the binary log disabled perform any table repair or rebuilding operations needed to re create database objects The binary log must be disabled during this step to prevent these operations from being logged and sent to the slaves later 4 Re enable the binary log on the master If you set sql_log_bin 494 to 0 ear...

Страница 1531: ...on the slave try the following procedure if it is not feasible to do a full database resynchronization by deleting the slave s databases and copying a new snapshot from the master 1 Determine whether the affected table on the slave is different from the master table Try to understand how this happened Then make the slave s table identical to the master s and run START SLAVE 2 If the preceding step...

Страница 1532: ...ptions cause the slave to log the updates that it receives from the master into its own binary logs 3 Save all evidence before resetting the replication state If we have no information or only sketchy information it becomes difficult or impossible for us to track down the problem The evidence you should collect is All binary log files from the master All binary log files from the slave The output ...

Страница 1533: ... 4 5 ndb_cpcd Automate Testing for NDB Development 1631 17 4 6 ndb_delete_all Delete All Rows from an NDB Table 1631 17 4 7 ndb_desc Describe NDB Tables 1632 17 4 8 ndb_drop_index Drop Index from an NDB Table 1633 17 4 9 ndb_drop_table Drop an NDB Table 1634 17 4 10 ndb_error_reporter NDB Error Reporting Utility 1635 17 4 11 ndb_print_backup_file Print NDB Backup File Contents 1635 17 4 12 ndb_pri...

Страница 1534: ...MySQL Cluster NDB 7 1 MySQL Cluster is available for production use on Microsoft Windows MySQL Cluster is not available for Microsoft Windows in MySQL 5 0 For more information see MySQL Cluster NDB 6 1 7 1 This chapter represents a work in progress and its contents are subject to revision as MySQL Cluster continues to evolve Additional information regarding MySQL Cluster can be found on the MySQL ...

Страница 1535: ...hould not be a source of problems Individual nodes can be stopped and restarted and can then rejoin the system cluster Rolling restarts in which all nodes are restarted in turn are used in making configuration changes and software upgrades see Section 17 5 5 Performing a Rolling Restart of a MySQL Cluster For more information about data nodes how they are organized in a MySQL Cluster and how they ...

Страница 1536: ...th the command ndb_mgmd Data node This type of node stores cluster data There are as many data nodes as there are replicas times the number of fragments see Section 17 1 2 MySQL Cluster Nodes Node Groups Replicas and Partitions For example with two replicas each having two fragments you need four data nodes One replica is sufficient for data storage but provides no redundancy therefore it is recom...

Страница 1537: ...nts using Connector J 5 0 6 and later can use jdbc mysql loadbalance URLs improved in Connector J 5 1 7 to achieve load balancing transparently Management clients These clients connect to the management server and provide commands for starting and stopping nodes gracefully starting and stopping message tracing debug versions only showing node versions and status starting and stopping backups and s...

Страница 1538: ...arameter as shown here number_of_node_groups number_of_data_nodes NoOfReplicas Thus a MySQL Cluster with 4 data nodes has 4 node groups if NoOfReplicas is set to 1 in the config ini file 2 node groups if NoOfReplicas is set to 2 and 1 node group if NoOfReplicas is set to 4 Replicas are discussed later in this section for more information about NoOfReplicas see Section 17 3 2 5 Defining MySQL Clust...

Страница 1539: ...lica is on node 3 and its backup replica is on node 4 Partition 2 is stored on node group 0 However the placing of its two replicas is reversed from that of Partition 0 for Partition 2 the primary replica is stored on node 2 and the backup on node 1 Partition 3 is stored on node group 1 and the placement of its two replicas are reversed from those of partition 1 That is its primary replica is loca...

Страница 1540: ... relatively small The software requirements for MySQL Cluster are also modest Host operating systems do not require any unusual modules services applications or configuration to support MySQL Cluster For supported operating systems a standard installation should be sufficient The MySQL software requirements are simple all that is needed is a production release of MySQL 5 0 to have Cluster support ...

Страница 1541: ...rates with reduced redundancy Heartbeating relies on timely generation of heartbeat signals by all nodes This may not be possible if the node is overloaded has insufficient machine CPU due to sharing with other programs or is experiencing delays due to swapping If heartbeat generation is sufficiently delayed other nodes treat the node that is slow to respond as failed This treatment of a slow node...

Страница 1542: ...usly by a factor of as much as 5 to 10 times times the number of data nodes because multiple CPUs can work on the query in parallel You can use EXPLAIN to determine when condition pushdown is being used See Section 13 8 2 EXPLAIN Syntax Decreased IndexMemory Usage In MySQL 5 0 each record consumes approximately 25 bytes of index memory and every unique index uses 25 bytes per record of index memor...

Страница 1543: ...umn width Attempting to create an index on an NDB table column whose width is greater than 3072 bytes succeeds but only the first 3072 bytes are actually used for the index In such cases a warning Specified key was too long max key length is 3072 bytes is issued and a SHOW CREATE TABLE statement shows the length of the index as 3072 TEXT and BLOB columns You cannot create indexes on NDB table colu...

Страница 1544: ...table Note Recall that TRUNCATE TABLE drops and re creates the table See Section 13 1 21 TRUNCATE TABLE Syntax Limits imposed by the cluster s configuration A number of hard limits exist which are configurable but available main memory in the cluster sets limits See the complete list of configuration parameters in Section 17 3 2 MySQL Cluster Configuration Files Most configuration parameters can b...

Страница 1545: ... up and restoring Cluster databases Transactions and BLOB or TEXT columns NDBCLUSTER stores only part of a column value that uses any of MySQL s BLOB or TEXT data types in the table visible to MySQL the remainder of the BLOB or TEXT is stored in a separate internal table that is not accessible to MySQL This gives rise to two related issues of which you should be aware whenever executing SELECT sta...

Страница 1546: ...r to perform a number of small transactions with a few operations each than to attempt a single large transaction containing a great many operations Among other considerations large transactions require very large amounts of memory Because of this the transactional behavior of a number of MySQL statements is effected as described in the following list TRUNCATE TABLE is not transactional when used ...

Страница 1547: ...of tables in a Cluster database in MySQL 5 0 is limited to 1792 The maximum number of all NDBCLUSTER database objects in a single MySQL Cluster including databases tables and indexes is limited to 20320 Attributes per table The maximum number of attributes that is columns and indexes per table is limited to 128 Attributes per key The maximum number of attributes per key is 32 Row size The maximum ...

Страница 1548: ...All machines used in the cluster must have the same architecture That is all machines hosting nodes must be either big endian or little endian and you cannot use a mixture of both For example you cannot have a management node running on a PowerPC which directs a data node that is running on an x86 machine This restriction does not apply to machines simply running mysql or other clients that may be...

Страница 1549: ...iscovery of databases is not supported for multiple MySQL servers accessing the same MySQL Cluster However autodiscovery of tables is supported in such cases What this means is that after a database named db_name is created or imported using one MySQL server you should issue a CREATE DATABASE db_name statement on each additional MySQL server that accesses the same MySQL Cluster As of MySQL 5 0 2 y...

Страница 1550: ... shown below Character set support The NDBCLUSTER storage engine supports all character sets and collations available in MySQL 5 0 Character set directory Beginning with MySQL 5 0 21 it is possible to install MySQL with Cluster support to a nondefault location and change the search path for font description files using either the basedir 401 or character sets dir 402 options Previously ndbd in MyS...

Страница 1551: ...Ethernet network as shown here Node IP Address Management node mgmd 192 168 0 10 SQL node mysqld 192 168 0 20 Data node A ndbd 192 168 0 30 Data node B ndbd 192 168 0 40 This may be made clearer by the following diagram Network addressing In the interest of simplicity and reliability this How To uses only numeric IP addresses However if DNS resolution is available on your network it is possible to...

Страница 1552: ...g system with standard TCP IP networking capabilities should be sufficient Also for the sake of simplicity we also assume that the file systems on all hosts are set up identically In the event that they are not you should adapt these instructions accordingly Network hardware Standard 100 Mbps or 1 gigabit Ethernet cards are installed on each machine along with the proper drivers for the cards and ...

Страница 1553: ...ux This section covers the steps necessary to install the correct executables for each type of Cluster node from precompiled binaries supplied by Oracle For setting up a cluster using precompiled binaries the first step in the installation process for each cluster host is to download the latest MySQL 5 0 binary archive from the MySQL downloads page We assume that you have placed this file in each ...

Страница 1554: ...is required This binary can also be found in the tar gz archive Again we assume that you have placed this archive in var tmp As system root that is after using sudo su root or your system s equivalent for temporarily assuming the system administrator account s privileges perform the following steps to install the data node binaries on the data node hosts 1 Change location to the var tmp directory ...

Страница 1555: ... MySQL server 5 0 96 0 glibc23 i386 rpm which supplies the core files needed to run a MySQL Server If you do not have your own client application capable of administering a MySQL server you should also obtain and install the Client RPM such as MySQL client 5 0 96 0 sles10 i586 rpm The NDB Cluster Storage engine RPM for example MySQL ndb storage 5 0 96 0 glibc23 i386 rpm which supplies the MySQL Cl...

Страница 1556: ... installs the mysql client program Management nodes To install the MySQL Cluster management server it is necessary only to use the NDB Cluster Storage engine management RPM Copy this RPM to the computer intended to host the management node and then install it by running the following command as the system root user replace the name shown for the RPM as necessary to match that of the Storage engine...

Страница 1557: ...irectory usr local mysql libexec For installing on multiple data node hosts only ndbd need be copied to the other host machine or machines This assumes that all data node hosts use the same architecture and operating system otherwise you may need to compile separately for each different platform ndbd need not be in any particular location on the host s file system as long as the location is known ...

Страница 1558: ... Otherwise these statements will fail with an error This is by design Configuring the management node The first step in configuring the management node is to create the directory in which the configuration file can be found and then to create the file itself For example running as root shell mkdir var lib mysql cluster shell cd var lib mysql cluster shell vi config ini For our representative setup...

Страница 1559: ...on for MySQL Cluster Backups Note The default port for Cluster management nodes is 1186 the default port for data nodes is 2202 Beginning with MySQL 5 0 3 this restriction is lifted and the cluster automatically allocates ports for data nodes from those that are already free 17 2 3 Initial Startup of MySQL Cluster Starting the cluster is not very difficult after it has been configured Each cluster...

Страница 1560: ...orking with database tables and data in MySQL Cluster is not much different from doing so in standard MySQL There are two key points to keep in mind For a table to be replicated in the cluster it must use the NDBCLUSTER storage engine To specify this use the ENGINE NDBCLUSTER or ENGINE NDB option when creating the table CREATE TABLE tbl_name col_name column_definitions ENGINE NDBCLUSTER Alternativ...

Страница 1561: ...o accomplish this is to do a search and replace on the file that contains the definitions and replace all instances of TYPE engine_name or ENGINE engine_name with ENGINE NDBCLUSTER If you do not want to modify the file you can use the unmodified file to create the tables and then use ALTER TABLE to change their storage engine The particulars are given later in this section Assuming that you have a...

Страница 1562: ...not interaction between nodes See Section 17 5 10 2 MySQL Cluster and MySQL Privileges for more information If you did not modify the ENGINE clauses in the table definitions prior to importing the SQL script you should run the following statements at this point mysql USE world mysql ALTER TABLE City ENGINE NDBCLUSTER mysql ALTER TABLE Country ENGINE NDBCLUSTER mysql ALTER TABLE CountryLanguage ENG...

Страница 1563: ... free the result set and the mysqli connection object result close link close body html We assume that the process running on the Web server can reach the IP address of the SQL node In a similar fashion you can use the MySQL C API Perl DBI Python mysql or MySQL Connectors to perform the tasks of data definition and manipulation just as you would normally with MySQL 17 2 5 Safe Shutdown and Restart...

Страница 1564: ...rmation about MySQL Cluster software and table file compatibility between MySQL 5 0 releases with regard to performing upgrades and downgrades as well as a compatibility matrix and notes You are expected already to be familiar with installing and configuring a MySQL Cluster prior to attempting an upgrade or downgrade See Section 17 3 MySQL Cluster Configuration For information regarding the rollin...

Страница 1565: ...eries Direct upgrades or downgrades between MySQL Cluster 4 1 and 5 0 are not supported you must dump all NDBCLUSTER tables using mysqldump install the new version of the software and then reload the tables from the dump Online downgrades from MySQL Cluster 5 0 12 to 5 0 11 or earlier are not supported ...

Страница 1566: ...luster storage engine is available in binary distributions for Linux Mac OS X and Solaris We are working to support MySQL Cluster on all operating systems supported by MySQL including Windows For information about installing MySQL Cluster see Section 17 2 MySQL Cluster Installation and Upgrades 17 3 1 Quick Test Setup of MySQL Cluster To familiarize you with the basics we will describe the simples...

Страница 1567: ...the ndb_mgmd and ndbd servers explicitly Normally these will be found in usr local mysql bin Finally change location to the MySQL data directory usually var lib mysql or usr local mysql data and make sure that the my cnf file contains the option necessary to enable the NDB storage engine mysqld ndbcluster You can now start the MySQL server as usual shell mysqld_safe user mysql Wait a moment to mak...

Страница 1568: ... in the cluster by using any table created with ENGINE NDBCLUSTER or its alias ENGINE NDB 17 3 2 MySQL Cluster Configuration Files Configuring MySQL Cluster requires working with two files my cnf Specifies options for all MySQL Cluster executables This file with which you should be familiar with from previous work with MySQL must be accessible by each executable running in the cluster config ini T...

Страница 1569: ...ovide connectstring for management server host default port 1186 ndb_mgm connect string ndb_mgmd mysql com provide location of cluster configuration file ndb_mgmd config file etc config ini For more information on connectstrings see Section 17 3 2 2 The MySQL Cluster Connectstring my cnf example additions to my cnf for MySQL Cluster will work on all versions enable ndbcluster storage engine and pr...

Страница 1570: ... apply to a particular data node whereas an ndbd default section contains parameters that apply to all data nodes Suppose that all data nodes should use the same data memory size To configure them all create an ndbd default section that contains a DataMemory line to specify the data memory size The global configuration file must define the computers and nodes involved in the cluster and on which c...

Страница 1571: ...n cluster data nodes Such connections require software which while freely available is not part of the MySQL Cluster distribution as well as specialized hardware See Section 17 3 2 10 SCI Transport Connections in MySQL Cluster for detailed information about SCI interconnects You can define default values for each section All Cluster parameter names are case insensitive which differs from parameter...

Страница 1572: ...fining Computers in a MySQL Cluster The computer section has no real significance other than serving as a way to avoid the need of defining host names for each node in the system All parameters mentioned here are required Id Effective Version Type Units Default Range Values MySQL 5 0 0 string none Restart Type IN This is a unique identifier used to refer to the host computer elsewhere in the confi...

Страница 1573: ...lable as a synonym for Id In MySQL Cluster NDB 6 2 and later Id is deprecated in favor of NodeId for identifying management nodes ExecuteOnComputer Effective Version Type Units Default Range Values MySQL 5 0 0 name none Restart Type S This refers to the Id set for one of the computers defined in a computer section of the config ini file PortNumber Effective Version Type Units Default Range Values ...

Страница 1574: ...ze in bytes to which the file can grow before logging rolls over to a new file When this occurs the old log file is renamed by appending N to the file name where N is the next number not yet used with this name maxfiles The maximum number of log files FILE filename cluster log maxsize 1000000 maxfiles 6 The default value for the FILE parameter is FILE filename ndb_node_id_cluster log maxsize 10000...

Страница 1575: ...ult value for this parameter is the directory in which ndb_mgmd is located Note After making changes in a management node s configuration it is necessary to perform a rolling restart of the cluster for the new configuration to take effect To add new management servers to a running MySQL Cluster it is also necessary to perform a rolling restart of all cluster nodes after modifying any existing conf...

Страница 1576: ...ode in the cluster must have a unique identifier In MySQL 5 0 15 and later NodeId is a synonym for this parameter and is the preferred form In MySQL Cluster NDB 6 2 and later Id is deprecated in favor of NodeId for identifying data nodes NodeId Effective Version Type Units Default Range Values MySQL 5 0 15 unsigned none 1 48 Restart Type N Beginning with MySQL 5 0 15 NodeId is available as a synon...

Страница 1577: ...d default section and defines the number of replicas for each table stored in the cluster This parameter also specifies the size of node groups A node group is a set of nodes all storing the same information Node groups are formed implicitly The first node group is formed by the set of data nodes with the lowest node IDs the next node group by the set of the next lowest node identities and so on B...

Страница 1578: ...s directory must exist before the ndbd process is initiated The recommended directory hierarchy for MySQL Cluster includes var lib mysql cluster under which a directory for the node s file system is created The name of this subdirectory contains the node ID For example if the node ID is 2 this subdirectory is named ndb_2_fs BackupDataDir Effective Version Type Units Default Range Values MySQL 5 0 ...

Страница 1579: ...y MySQL Cluster can use a maximum of 512 MB for hash indexes per partition which means in some cases it is possible to get Table is full errors in MySQL client applications even when ndb_mgm e ALL REPORT MEMORYUSAGE shows significant free DataMemory 1559 This can also pose a problem with data node restarts on nodes that are heavily loaded with data You can force NDB to create extra partitions for ...

Страница 1580: ...commit to any one process 32 bit operating systems are generally limited to 2 4GB per process 64 bit operating systems can use more For large databases it may be preferable to use a 64 bit operating system for this reason IndexMemory Effective Version Type Units Default Range Values MySQL 5 0 0 bytes 18M 1M 1T Restart Type N This parameter controls the amount of storage used for hash indexes in My...

Страница 1581: ...le plus the two ordered index tables You can see that hash indexes takes up a fair amount of memory space however they provide very fast access to the data in return They are also used in MySQL Cluster to handle uniqueness constraints Currently the only partitioning algorithm is hashing and ordered indexes are local to each node Thus ordered indexes cannot be used to handle uniqueness constraints ...

Страница 1582: ... involving 10 tables requires 11 transaction records if there are 10 such joins in a transaction then 10 11 110 transaction records are required for this transaction per MySQL server or 110 10 1100 transaction records total Each data node can be expected to handle TotalNoOfConcurrentTransactions number of data nodes For a MySQL Cluster having 4 data nodes this would mean setting MaxNoOfConcurrentT...

Страница 1583: ...s also cause operation records to be created Some extra space is allocated within individual nodes to accommodate cases where the distribution is not perfect over the nodes When queries make use of the unique hash index there are actually two operation records used per record in the transaction The first record represents the read in the index table and the second handles the operation on the base...

Страница 1584: ...ndexes should it be necessary to increase this value Using a smaller value is possible and can save memory if the DBA is certain that a high degree of parallelism is not required for the cluster MaxNoOfFiredTriggers Effective Version Type Units Default Range Values MySQL 5 0 0 integer 4000 0 4G Restart Type N The default value of MaxNoOfFiredTriggers is 4000 which is sufficient for most situations...

Страница 1585: ... partitions in parallel Each partition scan uses a scan record in the node where the partition is located the number of records being the value of this parameter times the number of nodes The cluster should be able to sustain MaxNoOfConcurrentScans scans concurrently from all nodes in the cluster Scans are actually performed in two cases The first of these cases occurs when no hash or ordered inde...

Страница 1586: ...ord is not removed until three local checkpoints have been completed since that log record was inserted Checkpointing frequency is determined by its own set of configuration parameters discussed elsewhere in this chapter How these parameters interact and proposals for how to configure them are discussed in Section 17 3 2 11 Configuring MySQL Cluster Parameters for Local Checkpoints The default par...

Страница 1587: ... intended to function as a hard upper limit A known issue in MySQL Cluster in MySQL 5 0 is that this parameter is occasionally treated as a hard limit for certain operations This can lead to confusion when it is sometimes possible or not possible depending on the circumstances to create more than MaxNoOfAttributes attributes This is fixed in MySQL Cluster NDB 6 3 and later Bug 61684 The default va...

Страница 1588: ...uster NDB 6 3 and later Bug 61684 For each attribute that has a BLOB data type an extra table is used to store most of the BLOB data These tables also must be taken into account when defining the total number of tables The default value of this parameter is 128 The minimum is 8 and the maximum is 20320 This is a change from MySQL 4 1 Each table object consumes approximately 20KB per node Note The ...

Страница 1589: ...rigger object Backups also use three trigger objects for each normal table in the cluster This parameter sets the maximum number of trigger objects in the cluster The default value is 768 MaxNoOfIndexes This parameter is deprecated You should use MaxNoOfOrderedIndexes and MaxNoOfUniqueHashIndexes instead This parameter is used only by unique hash indexes There needs to be one record in this pool f...

Страница 1590: ...e ulimit l and http linux die net man 2 mlock Important Beginning with glibc 2 10 glibc uses per thread arenas to reduce lock contention on a shared pool which consumes real memory In general a data node process does not need per thread arenas since it does not perform any memory allocation after startup This difference in allocators does not appear to affect performance significantly The glibc be...

Страница 1591: ...en building the debug version where it is possible to insert errors in the execution of individual blocks of code as part of testing This feature is disabled by default Controlling Timeouts Intervals and Disk Paging There are a number of ndbd parameters specifying timeouts and intervals between various actions in Cluster data nodes Most of the timeout values are specified in milliseconds Any excep...

Страница 1592: ...art of the cluster The default timeout is 60000 milliseconds 60 seconds StartFailureTimeout Effective Version Type Units Default Range Values MySQL 5 0 0 milliseconds 0 0 4G Restart Type N If a data node has not completed its startup sequence within the time specified by this parameter the node startup fails Setting this parameter to 0 the default value means that no data node timeout is applied F...

Страница 1593: ...he MySQL servers connected to it independently of all other data nodes For more information see Network communication and latency TimeBetweenLocalCheckpoints Effective Version Type Units Default Range Values MySQL 5 0 0 number of 4 byte words as a base 2 logarithm 20 0 31 Restart Type N This parameter is an exception in that it does not specify a time to wait before starting a new local checkpoint...

Страница 1594: ...ype Units Default Range Values MySQL 5 0 0 milliseconds 1000 1000 4G Restart Type N Timeout handling is performed by checking a timer on each transaction once for every interval specified by this parameter Thus if this parameter is set to 1000 milliseconds every transaction will be checked for timing out once per second The default value is 1000 milliseconds 1 second TransactionInactiveTimeout Eff...

Страница 1595: ...per 100 milliseconds are to be written In this context a page is defined as 8KB This parameter is specified in units of 80KB per second so setting NoOfDiskPagesToDiskAfterRestartTUP to a value of 20 entails writing 1 6MB in data pages to disk each second during a local checkpoint This value includes the writing of UNDO log records for data pages That is this parameter handles the limitation of wri...

Страница 1596: ...P and NoOfDiskPagesToDiskAfterRestartACC values for this parameter are expressed in terms of 8KB pages written per 100 milliseconds 80KB second The default value is 20 1 6MB per second ArbitrationTimeout Effective Version Type Units Default Range Values MySQL 5 0 0 milliseconds 3000 10 4G Restart Type N This parameter specifies how long data nodes wait for a response from the arbitrator to an arbi...

Страница 1597: ...arge transactions and large primary keys it may be necessary to increase the size of this buffer If this buffer is too small the NDB storage engine issues internal error code 677 Index UNDO buffers overloaded Important It is not safe to decrease the value of this parameter during a rolling restart UndoDataBuffer Effective Version Type Units Default Range Values MySQL 5 0 0 unsigned 16M 1M 4G Resta...

Страница 1598: ...s sent for various event types to stdout For each event category there are 16 possible event levels numbered 0 through 15 Setting event reporting for a given event category to level 15 means all event reports in that category are sent to stdout setting it to 0 means that there will be no event reports made in that category By default only the startup message is sent to stdout with the remaining ev...

Страница 1599: ...fault level is 0 LogLevelNodeRestart Effective Version Type Units Default Range Values MySQL 5 0 0 integer 0 0 15 Restart Type N The reporting level for events generated during node restart The default level is 0 LogLevelConnection Effective Version Type Units Default Range Values MySQL 5 0 0 integer 0 0 15 Restart Type N The reporting level for events generated by connections between cluster node...

Страница 1600: ...recorded by scanning a node s tables Once this buffer has been filled to the level specified as BackupWriteSize see below the pages are sent to disk While flushing data to disk the backup process can continue filling this buffer until it runs out of space When this happens the backup process pauses the scan and waits until some disk writes have completed freed up memory so that scanning may contin...

Страница 1601: ...e sum of BackupDataBufferSize and BackupLogBufferSize The default value is 2MB 2MB 4MB Important If BackupDataBufferSize and BackupLogBufferSize taken together exceed 4MB then this parameter must be set explicitly in the config ini file to their sum BackupWriteSize Effective Version Type Units Default Range Values MySQL 5 0 0 bytes 32K 2K 4G Restart Type N This parameter specifies the default size...

Страница 1602: ...lications other than mysqld processes accessing cluster data but the two designations are actually synonomous you can for instance list parameters for a MySQL server acting as an SQL node in an api section Note For a discussion of MySQL server options for MySQL Cluster see Section 17 3 4 2 mysqld Command Options for MySQL Cluster for information about MySQL server system variables relating to MySQ...

Страница 1603: ...localhost is assumed for HostName unless otherwise specified ArbitrationRank Effective Version Type Units Default Range Values MySQL 5 0 0 0 2 0 0 2 Restart Type N This parameter defines which nodes can act as arbitrators Both MGM nodes and SQL nodes can be arbitrators A value of 0 means that the given node is never used as an arbitrator a value of 1 gives the node high priority as an arbitrator a...

Страница 1604: ...ues MySQL 5 0 0 bytes 256K 32K 16M Restart Type N The batch size is the size of each batch sent from each data node Most scans are performed in parallel to protect the MySQL Server from receiving too much data from many nodes in parallel this parameter sets a limit to the total batch size over all nodes The default value of this parameter is set to 256KB Its maximum size is 16MB You can obtain som...

Страница 1605: ...as any connection parameters to override It is also possible to change the default values for these parameters by setting them in the tcp default section Important Any tcp sections in the config ini file should be listed last following all other sections in the file However this is not required for a tcp default section This requirement is a known issue with the way in which the config ini file is...

Страница 1606: ...necessary to set this parameter The minimum size is 64 KB the theoretical maximum is 4 GB SendSignalId Effective Version Type Units Default Range Values MySQL 5 0 0 boolean see text true false Restart Type N To be able to retrace a distributed message datagram it is necessary to identify each message When this parameter is set to Y message IDs are transported over the network This feature is disab...

Страница 1607: ... with one another directly using IP addresses in the 1 1 0 address range as shown Management Server ndb_mgmd Id 1 HostName 172 23 72 20 SQL Node mysqld Id 2 HostName 172 23 72 21 Data Nodes ndbd Id 3 HostName 172 23 72 22 ndbd Id 4 HostName 172 23 72 23 TCP IP Connections tcp NodeId1 3 NodeId2 4 HostName1 1 1 0 1 HostName2 1 1 0 2 The HostName1 1585 and HostName2 1586 parameters are used only when...

Страница 1608: ... 0 numeric none Restart Type N NodeId2 Effective Version Type Units Default Range Values MySQL 5 0 0 numeric none Restart Type N To identify a connection between two nodes it is necessary to provide node identifiers for each of them as NodeId1 and NodeId2 HostName1 Effective Version Type Units Default Range Values MySQL 5 0 0 name or IP address none Restart Type N HostName2 Effective Version Type ...

Страница 1609: ...k against data being corrupted during transport SigNum Effective Version Type Units Default Range Values MySQL 5 0 0 unsigned none 0 4G Restart Type N When using the shared memory transporter a process sends an operating system signal to the other process when there is new data available in the shared memory Should that signal conflict with with an existing signal this parameter can be used to cha...

Страница 1610: ...ach of them as NodeId1 and NodeId2 Host1SciId0 Effective Version Type Units Default Range Values MySQL 5 0 0 unsigned none 0 4G Restart Type N This identifies the SCI node ID on the first Cluster node identified by NodeId1 Host1SciId1 Effective Version Type Units Default Range Values MySQL 5 0 0 unsigned 0 0 4G Restart Type N It is possible to set up SCI Transporters for failover between two SCI c...

Страница 1611: ...B should be sufficient for most applications Using a smaller value can lead to problems when performing many parallel inserts if the shared buffer is too small this can also result in a crash of the ndbd process SendLimit Effective Version Type Units Default Range Values MySQL 5 0 0 unsigned 8K 128 32K Restart Type N A small buffer in front of the SCI media stores messages before transmitting them...

Страница 1612: ...un by the application affects the values of 5 columns No NULL values are inserted by the application A good starting point is to determine the amount of time that should elapse between local checkpoints LCPs It is worth noting that in the event of a system restart it takes 40 60 percent of this interval to execute the REDO log for example if the time between LCPs is 5 minutes 300 seconds then it s...

Страница 1613: ...lumns this works out to 72 20 160 252 bytes per operation and multiplying this by 5 operation per second yields 1260 bytes per second 15000 INSERT statements per hour is equivalent to 5 insert operations per second Each insert requires REDO log space of 72 bytes plus 4 bytes per record 40 columns plus 32 bytes per column 40 columns which is 72 160 1280 1512 bytes per operation This times 5 operati...

Страница 1614: ...ition it is the generally the case that configuration parameters relating to memory and disk usage can be raised using a simple node restart but they require an initial node restart to be lowered Because some of these parameters can be used for configuring more than one type of cluster node they may appear in more than one of the tables Note 4294967039 which often appears as a maximum value in the...

Страница 1615: ...tes 16M BackupDataBufferSize 1580 0 4G N all path FileSystemPath BackupDataDir 1558 IN all bytes 16M BackupLogBufferSize 1580 0 4G N all bytes 1M BackupMaxWriteSize 1581 2K 4G N all bytes 32M BackupMemory 1581 0 4G N all bytes 256K BackupWriteSize 1581 2K 4G N all integer 256 BatchSizePerLocalScan 1565 1 992 N all path DataDir 1558 IN all bytes 80M DataMemory 1559 1M 1024G N all true false 1 0 fal...

Страница 1616: ... 100 4G N all milliseconds 5000 HeartbeatIntervalDbDb 1572 10 4G N all name or IP address localhost HostName 1556 S all unsigned none Id 1556 1 48 N all bytes 18M IndexMemory 1560 1M 1T N all numeric 0 LockPagesInMainMemory 1569 0 2 N 5 0 36 log level 0 LogLevelCheckpoint 1579 0 15 N all levelr 0 LogLevelCongestion 1580 0 15 N 5 0 0 integer 0 LogLevelConnection 1579 0 15 N all integer 0 LogLevelEr...

Страница 1617: ...er 0 LogLevelStatistic 1579 0 15 N all bytes 4M LongMessageBuffer 1566 512K 4G N all integer 1000 MaxNoOfAttributes 1567 32 4G N all integer 8K MaxNoOfConcurrentIndexOperations 1564 0 4G N all integer 32K MaxNoOfConcurrentOperations 1562 32 4G N all integer 256 MaxNoOfConcurrentScans 1565 2 500 N all integer 4096 MaxNoOfConcurrentTransactions 1562 32 4G S all integer 4000 MaxNoOfFiredTriggers 1564...

Страница 1618: ...567 0 4G N all integer 128 MaxNoOfTables 1568 8 20320 N 5 0 0 integer 768 MaxNoOfTriggers 1569 0 4G N all integer 64 MaxNoOfUniqueHashIndexes 1568 0 4G N all unsigned none NodeId 1556 1 48 N 5 0 15 8K pages 100 milliseconds 20 NoOfDiskPagesToDiskAfterRestartACC 1575 1 4G N all 8K pages 100 milliseconds 40 NoOfDiskPagesToDiskAfterRestartTUP 1575 1 4G N all 8K pages 100 milliseconds 20 NoOfDiskPages...

Страница 1619: ... N all error code 2 RestartOnErrorInsert 1571 0 4 N all unsigned none ServerPort 1556 1 64K N all milliseconds 0 StartFailureTimeout 1572 0 4G N all milliseconds 30000 StartPartialTimeout 1571 0 4G N all milliseconds 60000 StartPartitionedTimeout 1572 0 4G N all boolean true StopOnError 1570 true false N all or bytes 25 StringMemory 1560 0 4G S all milliseconds 2000 TimeBetweenGlobalCheckpoints 15...

Страница 1620: ...L Cluster it is necessary to shut down the cluster completely update the config ini file and then restart the cluster starting all data node processes using the initial 1619 option that is you must perform a system restart It is possible to add new data node groups to a running cluster online using MySQL Cluster NDB 7 0 or later see Adding MySQL Cluster Data Nodes Online however we do not plan to ...

Страница 1621: ...meter I Initial restart Data nodes must be restarted using the initial 1619 option For more information about restart types see Section 17 3 3 Overview of MySQL Cluster Configuration Parameters Table 17 2 Management Node Configuration Parameters Type or Units Default Value Parameter Name Minimum Maximum or Permitted Values Restart Type In Version and later milliseconds 0 ArbitrationDelay 1555 0 4G...

Страница 1622: ... used in the mysqld and api sections of a config ini file for configuring MySQL Cluster SQL nodes and API nodes For detailed descriptions and other additional information about each of these parameters see Section 17 3 2 6 Defining SQL and Other API Nodes in a MySQL Cluster Note For a discussion of MySQL server options for MySQL Cluster see Section 17 3 4 2 mysqld Command Options for MySQL Cluster...

Страница 1623: ...tName 1583 S all unsigned none Id 1582 1 255 N all bytes 256K MaxScanBatchSize 1584 32K 16M N all unsigned none NodeId 1582 1 63 N 5 0 15 Note To add new SQL or API nodes to the configuration of a running MySQL Cluster it is necessary to perform a rolling restart of all cluster nodes after adding new mysqld or api sections to the config ini file or files if you are using more than one management s...

Страница 1624: ...ated in the summary tables as follows N Node restart The parameter can be updated using a rolling restart see Section 17 5 5 Performing a Rolling Restart of a MySQL Cluster S System restart The cluster must be shut down completely then restarted to effect a change in this parameter I Initial restart Data nodes must be restarted using the initial 1619 option For more information about restart types...

Страница 1625: ...Number 1586 0 64K N all string none Proxy N all bytes 2M ReceiveBufferMemory 1586 16K 4G N all unsigned 2M SendBufferMemory 1586 256K 4G N all boolean see text SendSignalId 1586 true false N all Table 17 6 Shared Memory Configuration Parameters Type or Units Default Value Parameter Name Minimum Maximum or Permitted Values Restart Type In Version and later boolean true Checksum 1589 true false N al...

Страница 1626: ...d none PortNumber 0 64K N all boolean false SendSignalId 1589 true false N all unsigned none ShmKey 1588 0 4G N all bytes 1M ShmSize 1588 64K 4G N all unsigned none Signum 1589 0 4G N all Table 17 7 SCI Configuration Parameters Type or Units Default Value Parameter Name Minimum Maximum or Permitted Values Restart Type In Version and later boolean false Checksum 1591 true false N all unsigned 15 Gr...

Страница 1627: ... NodeId2 1590 N all numeric none NodeIdServer N all unsigned none PortNumber 0 64K N all unsigned 8K SendLimit 1591 128 32K N all boolean true SendSignalId 1591 true false N all unsigned 10M SharedBufferSize 1591 64K 4G N all 17 3 4 MySQL Server Options and Variables for MySQL Cluster This section provides information about MySQL server options server and status variables that are specific to MySQ...

Страница 1628: ...ver 1615 N Y N The number of times that tables have been discovered Y Y Both ndb_autoincrement_prefetch_sz 1612 Y N Y NDB auto increment prefetch size Y Y Global ndb_cache_check_time 1612 Y N Y The number of milliseconds between checks of cluster SQL nodes made by the MySQL query cache Y Y Both ndb_force_send 1613 Y N Y Forces sending of buffers to NDB immediately without waiting for other threads...

Страница 1629: ...f records during SELECT COUNT query planning to speed up this type of query N N Both Ndb_cluster_node_id 1615 N Y N If the server is acting as a MySQL Cluster node then the value of this variable its node ID in the cluster N N Both Ndb_config_from_host 1616 N Y N The host name or IP address of the Cluster management server Formerly Ndb_connected_host N N Both Ndb_config_from_port 1616 N Y N The po...

Страница 1630: ...186 Can be used to set the host and port number of a single management server for the program to connect to If the program requires node IDs or references to multiple management servers or both in its connection information use the ndb connectstring 1610 option instead ndbcluster 1610 Command Line Format ndbcluster Option File Format ndbcluster Option Sets Variable Yes have_ndbcluster 1611 Disable...

Страница 1631: ...des in a MySQL Cluster skip ndbcluster Command Line Format skip ndbcluster Option File Format skip ndbcluster Disable the NDBCLUSTER storage engine This is the default for binaries that were built with NDBCLUSTER storage engine support the server allocates memory and other resources for this storage engine only if the ndbcluster 1610 option is given explicitly See Section 17 3 1 Quick Test Setup o...

Страница 1632: ...Variable Name ndb_autoincrement_prefetch_sz Variable Scope Global Session Dynamic Variable Yes Permitted Values 5 0 55 Type numeric Default 32 Range 1 256 Permitted Values 5 0 56 Type numeric Default 1 Range 1 256 Determines the probability of gaps in an autoincremented column Set it to 1 to minimize this Setting it to a high value for optimization makes inserts faster but decreases the likelihood...

Страница 1633: ...eater than 2000 ndb_force_send 1613 Command Line Format ndb force send Option File Format ndb_force_send Option Sets Variable Yes ndb_force_send 1613 Variable Name ndb_force_send Variable Scope Global Session Dynamic Variable Yes Permitted Values Type boolean Default TRUE Forces sending of buffers to NDB immediately without waiting for other threads Defaults to ON ndb_index_stat_cache_entries 1613...

Страница 1634: ...h the SQL node is considered to be closest to the SQL node the next closest in order of decreasing proximity are TCP connection to localhost SCI connection TCP connection from a host other than localhost This option is enabled by default Set to 0 or OFF to disable it in which case the SQL node uses each data node in the cluster in succession When this option is disabled each SQL thread attempts to...

Страница 1635: ...e this feature by setting the value of ndb_use_exact_count 1615 to OFF ndb_use_transactions 1615 Command Line Format ndb_use_transactions Option File Format ndb_use_transactions Variable Name ndb_use_transactions Variable Scope Global Session Dynamic Variable Yes Permitted Values Type boolean Default ON You can disable NDB transaction support by setting this variable s values to OFF not recommende...

Страница 1636: ...7 3 5 Using High Speed Interconnects with MySQL Cluster Even before design of NDBCLUSTER began in 1996 it was evident that one of the major problems to be encountered in building parallel databases would be communication between the nodes in the network For this reason NDBCLUSTER was designed from the very beginning to permit the use of a number of different data transport mechanisms In this Manua...

Страница 1637: ...rectory of the MySQL Cluster source trees it should not be difficult to adapt them for other platforms Generally all that is necessary is to compile MySQL Cluster with SCI Transporter support is to configure the MySQL Cluster build using with ndb sci opt DIS Once you have acquired the required Dolphin hardware and software you can obtain detailed information on how to adapt a MySQL Cluster configu...

Страница 1638: ... the VIA interface However we have tested MySQL Cluster so far only with SCI sockets See Section 17 3 5 1 Configuring MySQL Cluster to use SCI Sockets for information on how to set up SCI sockets using ordinary TCP IP for MySQL Cluster 17 4 MySQL Cluster Programs Using and managing a MySQL Cluster requires several specialized programs which we describe in this chapter We discuss the purposes of th...

Страница 1639: ...g purposes implies nodaemon All MySQL 5 0 based releases nowait nodes list 1620 Do not wait for these data nodes to start takes comma separated list of node IDs Also requires ndb nodeid to be used ADDED 5 0 21 initial start 1620 Perform partial initial start requires nowait nodes ADDED 5 0 21 bind address name 1619 Local bind address ADDED 5 0 29 bind address Version Introduced 5 0 29 Command Line...

Страница 1640: ...parameters from having any effect Important This option does not affect any backup files that have already been created by the affected node This option also has no effect on recovery of data by a data node that is just starting or restarting from data nodes that are already running This recovery of data occurs automatically and requires no user intervention in a MySQL Cluster that is running norm...

Страница 1641: ...hout one ndbd say for example that the host machine for node 3 has suffered a hardware failure then start nodes 2 4 and 5 with nowait nodes 3 Then the cluster will start as soon as nodes 2 4 and 5 connect and will not wait for node 3 to start When using this option you must also specify the node ID for the data node being started with the ndb nodeid 1652 option This option was added in MySQL 5 0 2...

Страница 1642: ...ata node process shuts down prematurely can be found in ndbd Error Messages Important The last entry in the error log file is not necessarily the newest one nor is it likely to be Entries in the error log are not listed in chronological order rather they correspond to the order of the trace files as determined in the ndb_node_id_trace log next file see below Error log entries are thus overwritten ...

Страница 1643: ...updates the ndbd process can consume up to 2 CPUs if permitted to do so For a machine with many CPUs it is possible to use several ndbd processes which belong to different node groups however such a configuration is still considered experimental and is not supported for MySQL 5 0 in a production setting See Section 17 1 5 Known Limitations of MySQL Cluster 17 4 2 ndb_mgmd The MySQL Cluster Managem...

Страница 1644: ... file it should use for its configuration file By default the management server looks for a file named config ini in the same directory as the ndb_mgmd executable otherwise the file name and location must be specified explicitly This option also can be given as c file_name but this shortcut is obsolete and should not be used in new installations mycnf Command Line Format mycnf Permitted Values Typ...

Страница 1645: ...e Section 17 3 2 2 The MySQL Cluster Connectstring for information about using connectstrings Section 17 4 2 ndb_mgmd The MySQL Cluster Management Server Daemon describes other options for ndb_mgmd The following files are created or used by ndb_mgmd in its starting directory and are placed in the DataDir as specified in the config ini configuration file In the list that follows node_id is the uniq...

Страница 1646: ... the table For options common to most MySQL Cluster programs including ndb_mgm see Section 17 4 20 Options Common to MySQL Cluster Programs Options Common to MySQL Cluster Programs Table 17 11 ndb_mgm Options and Variables MySQL 5 0 Format Description Added Removed try reconnect 1626 t 1626 Specify number of tries for connecting to ndb_mgmd 0 infinite All MySQL 5 0 based releases execute name 1626...

Страница 1647: ...programs including ndb_config see Section 17 4 20 Options Common to MySQL Cluster Programs Options Common to MySQL Cluster Programs Table 17 12 ndb_config Options and Variables MySQL 5 0 Format Description Added Removed nodes 1629 Print node information DB section only All MySQL 5 0 based releases query string 1629 q 1629 One or more query options attributes All MySQL 5 0 based releases host name ...

Страница 1648: ...s ndb_config to print a version information string and then exit ndb connectstring connect_string Specifies the connectstring to use in connecting to the management server The format for the connectstring is the same as described in Section 17 3 2 2 The MySQL Cluster Connectstring and defaults to localhost 1186 The use of c as a short version for this option is supported for ndb_config beginning w...

Страница 1649: ...Line Format host name Permitted Values Type string Default Specifies the host name of the node for which configuration information is to be obtained Note While the hostname localhost usually resolves to the IP address 127 0 0 1 this may not necessarily be true for all operating platforms and configurations This means that it is possible when localhost is used in config ini for ndb_config host loca...

Страница 1650: ... node_type ndbd mysqld or ndb_mgmd are returned fields delimiter f delimiter Command Line Format fields string f Permitted Values Type string Default Specifies a delimiter string used to separate the fields in the result The default is the comma character Note If the delimiter contains spaces or escapes such as n for the linefeed character then it must be quoted rows separator r separator Command ...

Страница 1651: ...al mysql cluster data 3 192 168 0 176 83886080 18874368 usr local mysql cluster data 4 192 168 0 119 83886080 18874368 usr local mysql cluster data In this example we used the short options f and r for setting the field delimiter and row separator respectively 4 To exclude results from any host except one in particular use the host option shell ndb_config host 192 168 0 176 f r n q id type 3 ndbd ...

Страница 1652: ... single transaction may run out of operations All MySQL 5 0 based releases tupscan Run tup scan All MySQL 5 0 based releases diskscan Run disk scan All MySQL 5 0 based releases transactional t Use of this option causes the delete operation to be performed as a single transaction Warning With very large tables using this option may cause the number of operations available to the cluster to be excee...

Страница 1653: ...on about interpreting this value see NDB Schema Object Versions The following table includes options that are specific to ndb_desc Additional descriptions follow the table For options common to most MySQL Cluster programs including ndb_desc see Section 17 4 20 Options Common to MySQL Cluster Programs Options Common to MySQL Cluster Programs Table 17 15 ndb_desc Options and Variables MySQL 5 0 Form...

Страница 1654: ...Dropping index dogs idx OK NDBT_ProgramExit 0 OK shell mysql u jon p ctest1 Enter password Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with A Welcome to the MySQL monitor Commands end with or g Your MySQL connection id is 7 to server version 5 0 96 Type help or h for help Type c to clear the buffer mysql SHOW TABLES Tabl...

Страница 1655: ...ion 17 4 20 Options Common to MySQL Cluster Programs Options Common to MySQL Cluster Programs Table 17 18 ndb_error_reporter Options and Variables MySQL 5 0 Format Description Added Removed fs 1635 Include file system data in error report can use a large amount of disk space All MySQL 5 0 based releases Usage ndb_error_reporter path to config file username fs This utility is intended for use on a ...

Страница 1656: ...ame is the name of a cluster schema file For more information about cluster schema files see MySQL Cluster Data Node FileSystemDir Files Like ndb_print_backup_file and ndb_print_sys_file and unlike most of the other NDB utilities that are intended to be run on a management server host or to connect to a management server ndb_schema_backup_file must be run on a cluster data node since it accesses t...

Страница 1657: ...gle User Mode for more information The following table includes options that are specific to the MySQL Cluster native backup restoration program ndb_restore Additional descriptions follow the table For options common to most MySQL Cluster programs including ndb_restore see Section 17 4 20 Options Common to MySQL Cluster Programs Options Common to MySQL Cluster Programs Table 17 19 ndb_restore Opti...

Страница 1658: ...nnectstrings If this option is not used then ndb_restore attempts to connect to a management server on localhost 1186 This utility acts as a cluster API node and so requires a free connection slot to connect to the cluster management server This means that there must be at least one api or mysqld section that can be used by it in the cluster config ini file It is a good idea to keep at least one e...

Страница 1659: ...ose that a backup with backup ID 12 created in a cluster with two database nodes having the node IDs 2 and 3 is to be restored to a cluster with four nodes Then ndb_restore must be run twice once for each database node in the cluster where the backup was taken However ndb_restore cannot always restore backups made from a cluster running one version of MySQL to a cluster running a different MySQL v...

Страница 1660: ...ions is in effect performing a dry run Including one or more of these options causes any output to be redirected to stdout in such cases ndb_restore makes no attempt to restore data or metadata to a MySQL Cluster print_data This option causes ndb_restore to direct its output to stdout TEXT and BLOB column values are always truncated to the first 256 bytes in the output this cannot currrently be ov...

Страница 1661: ... terminated by char Permitted Values Type string Default t tab The string passed to this option is used to separate column values The default value is a tab character t hex Version Introduced 5 0 40 Command Line Format hex If this option is used all binary values are output in hexadecimal format fields terminated by string Version Introduced 5 0 40 Command Line Format fields terminated by char Per...

Страница 1662: ...db_select_all Print Rows from an NDB Table ndb_select_all prints all rows from an NDB table to stdout Usage ndb_select_all c connect_string tbl_name d db_name file_name The following table includes options that are specific to the MySQL Cluster native backup restoration program ndb_select_all Additional descriptions follow the table For options common to most MySQL Cluster programs including ndb_s...

Страница 1663: ...he database in which the table is found The default value is TEST_DB parallelism p Specifies the degree of parallelism lock lock_type l lock_type Employs a lock when reading the table Possible values for lock_type are 0 Read lock 1 Read lock with hold 2 Exclusive read lock There is no default value for this option order index_name o index_name Orders the output according to the index named index_n...

Страница 1664: ...he table in the order of the tuples nodata Causes any table data to be omitted Sample Output Output from a MySQL SELECT statement mysql SELECT FROM ctest1 fish id name 3 shark 6 puffer 2 tuna 4 manta ray 5 grouper 1 guppy 6 rows in set 0 04 sec Output from the equivalent invocation of ndb_select_all shell ndb_select_all c localhost fish d ctest1 id name 3 shark 6 puffer 2 tuna 4 manta ray 5 groupe...

Страница 1665: ...escriptions follow the table For options common to most MySQL Cluster programs including ndb_select_count see Section 17 4 20 Options Common to MySQL Cluster Programs Options Common to MySQL Cluster Programs Table 17 21 ndb_select_count Options and Variables MySQL 5 0 Format Description Added Removed database dbname d Name of the database in which the table is found All MySQL 5 0 based releases pa...

Страница 1666: ...1647 u 1647 Do not qualify table names All MySQL 5 0 based releases parsable 1646 p 1646 Return output suitable for MySQL LOAD DATA INFILE statement All MySQL 5 0 based releases show temp status 1646 Show table temporary flag All MySQL 5 0 based releases Usage ndb_show_tables c connect_string database d Specifies the name of the database in which the tables are found loops l Specifies the number o...

Страница 1667: ... one or both of these libraries The ndb_size tmpl template file which you should be able to find in the share mysql directory of your MySQL installation This file should be copied or moved into the same directory as ndb_size pl if it is not there already before running the script A MySQL user account having the necessary privileges If you do not wish to use an existing account then creating one us...

Страница 1668: ...STARTED The node is operational and has joined the cluster SHUTTING_DOWN The node is shutting down SINGLE USER MODE This is shown for all cluster data nodes when the cluster is in single user mode The following table includes options that are specific to the MySQL Cluster native backup restoration program ndb_waiter Additional descriptions follow the table For options common to most MySQL Cluster ...

Страница 1669: ...aiter c localhost Connecting to mgmsrv at localhost State node 1 STARTED State node 2 NO_CONTACT State node 3 STARTED State node 4 NO_CONTACT Waiting for cluster enter state STARTED State node 1 STARTED State node 2 UNKNOWN State node 3 STARTED State node 4 NO_CONTACT Waiting for cluster enter state STARTED State node 1 STARTED State node 2 STARTING State node 3 STARTED State node 4 NO_CONTACT Wai...

Страница 1670: ...nt_sys_file to view a list of the options which the program supports The options in the following table are common to all MySQL Cluster executables except those noted previously in this section Table 17 24 Common MySQL Cluster Program Options and Variables MySQL 5 0 Format Description Added Removed help 1651 usage 1651 1651 Display help message and exit All MySQL 5 0 based releases ndb connectstri...

Страница 1671: ...age Prints a short list with descriptions of the available command options ndb connectstring connect_string connect string connect_string c connect_string Command Line Format ndb connectstring connectstring connect string connectstring c Permitted Values Type string Default localhost 1186 This option takes a MySQL Cluster connectstring that specifies the management server for the application to co...

Страница 1672: ...r For some systems there may be restrictions or limitations for example it might be necessary to execute ulimit c unlimited before starting the server Consult your system documentation for detailed information If MySQL Cluster was built using the debug option for configure then core file is enabled by default For regular builds core file is disabled by default debug options Command Line Format deb...

Страница 1673: ...MySQL Cluster This is covered in Section 17 3 MySQL Cluster Configuration and Section 17 4 MySQL Cluster Programs The next few sections cover the management of a running MySQL Cluster For information about security issues relating to management and deployment of a MySQL Cluster see Section 17 5 10 MySQL Cluster Security Issues There are essentially two methods of actively managing a running MySQL ...

Страница 1674: ... 3 Allocate ports to be used for inter node communications 4 Allocate memory according to settings obtained from the configuration file When a data node or SQL node first connects to the management node it reserves a cluster node ID To make sure that no other node allocates the same node ID this ID is retained until the node has managed to connect to the cluster and at least one ndbd reports that ...

Страница 1675: ... redo information until the latest restorable global checkpoint has been reached For a node restart find the tail of the redo log Phase 5 Most of the database related portion of a data node start is performed during this phase For an initial start or system restart a local checkpoint is executed followed by a global checkpoint Periodic checks of memory usage begin during this phase and any require...

Страница 1676: ...ackups with mysqldump see Section 4 5 4 mysqldump A Database Backup Program Restoration of MySQL Cluster backups is done using the ndb_restore utility provided with the MySQL Cluster distribution for information about ndb_restore and its use in restoring MySQL Cluster backups see Section 17 4 14 ndb_restore Restore a MySQL Cluster Backup 17 5 3 1 MySQL Cluster Backup Concepts A backup is a snapsho...

Страница 1677: ...y other options are used The maximum supported value for backup_id in MySQL 5 0 is 2147483648 2 31 Bug 43042 Note If you start a backup using ndb_mgm e START BACKUP the backup_id is required The wait_option can be used to determine when control is returned to the management client after a START BACKUP command is issued as shown in the following list WAIT COMPLETED is the default The procedure for ...

Страница 1678: ...ted in the message Backup backup_id started from node management_node_id 3 The management client will acknowledge the abort request with Abort of backup backup_id ordered Note At this point the management client has not yet received a response from the cluster data nodes to this request and the backup has not yet actually been aborted 4 After the backup has been aborted the management client will ...

Страница 1679: ...re these are written to disk BackupMemory The total memory allocated in a database node for backups This should be the sum of the memory allocated for the backup data buffer and the backup log buffer BackupWriteSize The default size of blocks written to disk This applies for both the backup data buffer and the backup log buffer BackupMaxWriteSize The maximum size of blocks written to disk This app...

Страница 1680: ...or NDBCLUSTER If you see NO in this row or if there is no such row displayed in the output you are not running an NDB enabled version of MySQL If you see DISABLED in this row you need to enable it in either one of the two ways just described To read cluster configuration data the MySQL server requires at a minimum three pieces of information The MySQL server s own cluster node ID The host name or ...

Страница 1681: ...e we refer to upgrades the information provided here also generally applies to downgrades as well There are a number of reasons why a rolling restart might be desirable These are described in the next few paragraphs Configuration change To make a change in the cluster s configuration such as adding an SQL node to the cluster or setting a configuration parameter to a new value MySQL Cluster softwar...

Страница 1682: ...rolling restart may be generalized as follows 1 Stop all cluster management nodes ndb_mgmd processes reconfigure them then restart them 2 Stop reconfigure then restart each cluster data node ndbd process in turn 3 Stop reconfigure then restart each cluster SQL node mysqld process in turn The specifics for implementing a given rolling upgrade depend upon the changes being made A more detailed view ...

Страница 1683: ...de ID of the management server in the same directory where the ndb_mgm binary resides Cluster logging information can also be sent to stdout or a syslog facility in addition to or instead of being saved to a file as determined by the values set for the DataDir and LogDestination configuration parameters See Section 17 3 2 4 Defining a MySQL Cluster Management Server for more information about thes...

Страница 1684: ...mSrvr INFO Node 4 Node 9 API version 5 1 15 2007 01 26 19 59 22 MgmSrvr ALERT Node 2 Node 7 Disconnected 2007 01 26 19 59 22 MgmSrvr ALERT Node 2 Node 7 Disconnected Each line in the cluster log contains the following information A timestamp in YYYY MM DD HH MM SS format The type of node which is performing the logging In the cluster log this is always MgmSrvr The severity of the event The ID of t...

Страница 1685: ...mmediately such as a corrupted system database 2 CRITICAL Critical conditions such as device errors or insufficient resources 3 ERROR Conditions that should be corrected such as configuration errors 4 WARNING Conditions that are not errors but that might require special handling 5 INFO Informational messages 6 DEBUG Debugging messages used for NDBCLUSTER development Event severity levels can be tu...

Страница 1686: ...ta node connection opened CHECKPOINT Events The logging messages shown here are associated with checkpoints Event Priority Severity Level Description LCP stopped in calc keep GCI 0 ALERT LCP stopped Local checkpoint fragment completed 11 INFO LCP on a fragment has been completed Global checkpoint completed 10 INFO GCP finished Global checkpoint started 9 INFO Start of GCP REDO log is written to di...

Страница 1687: ...ata node shutdown initiated 1 INFO Shutdown of data node has commenced data node shutdown aborted 1 INFO Unable to shut down data node normally NODERESTART Events The following events are generated when restarting a node and relate to the success or failure of the node restart process Event Priority Severity Level Description Node failure phase completed 8 ALERT Reports completion of node failure ...

Страница 1688: ...bitrator node X process failure state Y Lost arbitrator node X process exit state Y Lost arbitrator node X error msg state Y STATISTICS Events The following events are of a statistical nature They provide information such as numbers of transactions and other operations amount of data sent or received by individual nodes and memory usage Event Priority Severity Level Description Report job scheduli...

Страница 1689: ...ient s CLUSTERLOG STATISTICS command can provide a number of useful statistics in its output Counters providing information about the state of the cluster are updated at 5 second reporting intervals by the transaction coordinator TC and the local query handler LQH and written to the cluster log Transaction coordinator statistics Each transaction has one transaction coordinator which is chosen by o...

Страница 1690: ...nserts and updates this is proportional to the number of columns written and the size of their data For delete operations this is usually zero Unique index operations generate multiple PK operations and so increase this count However data words sent to describe the PK operation itself and the key information sent are not counted here Attribute information sent to describe columns to read for scans...

Страница 1691: ...y new incoming messages Process scheduler statistics include the following Mean Loop Counter This is the number of loops executed in the third step from the preceding list This statistic increases in size as the utilization of the TCP IP buffer improves You can use this to monitor changes in performance as you add new data node processes Mean send size and Mean receive size These statistics enable...

Страница 1692: ... Severity INFO Log Message Node data_node_id Communication to Node api_node_id opened Description The API node or SQL node having node ID api_node_id is now communicating with data node data_node_id Event Name CommunicationOpened Event Type Connection Priority 8 Severity INFO Log Message Node mgm_node_id Node api_node_id API version Description The API node having node ID api_node_id has connected...

Страница 1693: ...id fragment ID fragment_id has completed LCP on Node node_id maxGciStarted started_gci maxGciCompleted completed_gci Description A table fragment has been checkpointed to disk on node node_id The GCI in progress has the index started_gci and the most recent GCI to have been completed has the index completed_gci Event Name LCPFragmentCompleted Event Type Checkpoint Priority 11 Severity INFO Log Mes...

Страница 1694: ...ecting new candidate or No such cause Event Name CM_REGREF Event Type StartUp Priority 8 Severity INFO Log Message Node node_id We are Node own_id with dynamic ID dynamic_id our left neighbour is Node id_1 our right is Node id_2 Description The node has discovered its neighboring nodes in the cluster node id_1 and node id_2 node_id own_id and dynamic_id should always be the same if they are not th...

Страница 1695: ...nts referenced during a node start The redo log prior to keep_pos is dropped last_pos is the last global checkpoint in which data node the participated restore_pos is the global checkpoint which is actually used to restore all data nodes Event Name StartREDOLog Event Type StartUp Priority 4 Severity INFO Log Message startup_message Listed separately see below Description There are a number of poss...

Страница 1696: ...maining data nodes have detected the failure of data node node_id 3 The failure of data node node_id has been detected in the blockNDB kernel block where block is 1 of DBTC DBDICT DBDIH or DBLQH for more information see NDB Kernel Blocks Event Name NodeFailCompleted Event Type NodeRestart Priority 8 Severity ALERT Log Message Node mgm_node_id Node data_node_id has failed The Node state at failure ...

Страница 1697: ...gative reply from node node_id or Network partitioning no arbitrator available or Network partitioning no arbitrator configured or Arbitration failure error_message state state_code Description This message reports on the result of arbitration In the event of arbitration failure an error_message and an arbitration state_code are provided definitions for both of these are found in include kernel si...

Страница 1698: ...ions performed by this node provided approximately once every 10 seconds Event Name OperationReportCounters Event Type Statistic Priority 8 Severity INFO Log Message Node node_id Table with ID table_id created Description A table having the table ID shown has been created Event Name TableCreated Event Type Statistic Priority 7 Severity INFO Log Message Node node_id Mean loop Counter in doJob last ...

Страница 1699: ...of a potential transporter problem while communicating with node node2_id for a listing of transporter error codes and messages see NDB Transporter Errors for more information Event Name TransporterWarning Event Type Error Priority 8 Severity WARNING Log Message Node node1_id Node node2_id missed heartbeat heartbeat_id Description This node missed a heartbeat from node node2_id Event Name MissedHe...

Страница 1700: ...ackup has been started using the management node having mgm_node_id this message is also displayed in the cluster management client when the START BACKUP command is issued for more information see Section 17 5 3 2 Using The MySQL Cluster Management Client to Create a Backup Event Name BackupStarted Event Type Backup Priority 7 Severity INFO Log Message Node node_id Backup backup_id started from no...

Страница 1701: ...6 TE_COULD_NOT_BIND_SOCKET Error found while binding server socket 0x07 TE_LISTEN_FAILED Error found while listening to server socket 0x08 TE_ACCEPT_RETURN_ERROR Error found during accept accept return error 0x0b TE_SHM_DISCONNECT The remote node has disconnected 0x0c TE_SHM_IPC_STAT Unable to check shm segment 0x0d TE_SHM_UNABLE_TO_CREATE_SEGMENT Unable to create shm segment 0x0e TE_SHM_UNABLE_TO...

Страница 1702: ...O_UNMAP_SEGMENT Cannot free the resources used by this segment step 1 0x1f TE_SCI_UNABLE_TO_REMOVE_SEGMENT Cannot free the resources used by this segment step 2 0x20 TE_SCI_UNABLE_TO_DISCONNECT_SEGMENT Cannot disconnect from a remote segment 0x21 TE_SHM_IPC_PERMANENT Shm ipc Permanent error 0x22 TE_SCI_UNABLE_TO_CLOSE_CHANNEL Unable to close the sci channel and the resources allocated 17 5 8 MySQL...

Страница 1703: ...MODE There are two recommended ways to handle a node failure when running in single user mode Method 1 1 Finish all single user mode transactions 2 Issue the EXIT SINGLE USER MODE command 3 Restart the cluster s data nodes Method 2 Restart database nodes prior to entering single user mode 17 5 9 Quick Reference MySQL Cluster SQL Statements This section discusses several SQL statements that can pro...

Страница 1704: ... cluster node ID the host name and port for the cluster management server to which it is connected and the number of data nodes in the cluster as shown here mysql SHOW STATUS LIKE NDB Variable_name Value Ndb_cluster_node_id 10 Ndb_config_from_host 192 168 0 103 Ndb_config_from_port 1186 Ndb_number_of_data_nodes 4 If the MySQL server was built with clustering support but it is not connected to a cl...

Страница 1705: ...ng SQL nodes that know the management server s host name or IP address and port can connect to the cluster and access its data without restriction See Section 17 5 10 2 MySQL Cluster and MySQL Privileges for more information about this and related issues Note You can exercise some control over SQL and API node access to the cluster by specifying a HostName parameter for all mysqld and api sections...

Страница 1706: ...to be forwarded This means of course that all SQL nodes must be secured against hacking attempts Important With regard to potential security vulnerabilities an SQL node is no different from any other MySQL server See Section 6 1 3 Making MySQL Secure Against Attackers for a description of techniques you can use to secure MySQL servers 2 Using one or more software firewalls also known as host based...

Страница 1707: ...f node that is running on each cluster host computer Type of Node to be Accessed Traffic to Permit SQL or API node It originates from the IP address of a management or data node using any TCP or UDP port It originates from within the network in which the cluster resides and is on the port that your application is using Data node or Management node It originates from the IP address of a management ...

Страница 1708: ...uration you use remember that your objective from the viewpoint of keeping the cluster secure remains the same to prevent any unessential traffic from reaching the cluster while ensuring the most efficient communication between the nodes in the cluster Because MySQL Cluster requires large numbers of ports to be open for communications between nodes the recommended option is to use a segregated net...

Страница 1709: ... A and affecting the privileges of existing users on server A do not affect users on server B unless those statements are actually run on server B as well In other words changes in users and their privileges do not automatically propagate between SQL nodes Synchronization of privileges between SQL nodes must be done either manually or by scripting an application that periodically synchronizes the ...

Страница 1710: ...essible from outside your local network Important Never leave the MySQL root account password empty This is just as true when running MySQL as a MySQL Cluster SQL node as it is when running it as a standalone non Cluster MySQL Server and should be done as part of the MySQL installation process before configuring the MySQL Server as an SQL node in a MySQL Cluster You should never convert the system...

Страница 1711: ... it down and restart it as the mysql user If this user does not exist on the system the mysql user account should be created and this user should be part of the mysql user group in this case you should also make sure that the MySQL DataDir on this system is owned by the mysql user and that the SQL node s my cnf file includes user mysql in the mysqld section Alternatively you can start the server w...

Страница 1712: ...lso work without authentication and can reveal table names schemas and data By default these are installed on Unix style systems with the permissions wxr xr x 755 which means they can be executed by any user that can access the mysql bin directory See Section 17 4 MySQL Cluster Programs for more information about these utilities ...

Страница 1713: ...you invoke it in an expression and it returns a value during expression evaluation Triggers A trigger is a named database object that is associated with a table and that is activated when a particular event occurs for the table such as an insert or update Views are stored queries that when referenced produce a result set A view acts as a virtual table This chapter describes how to use stored progr...

Страница 1714: ... string other than and the delimiter can consist of a single character or multiple characters You should avoid the use of the backslash character because that is the escape character for MySQL The following is an example of a function that takes a parameter performs an operation using an SQL function and returns the result In this case it is unnecessary to use delimiter because the function defini...

Страница 1715: ...rking with stored procedures and functions For answers to some commonly asked questions regarding stored routines in MySQL see Section B 4 MySQL 5 0 FAQ Stored Procedures and Functions There are some restrictions on the use of stored routines See Section E 1 Restrictions on Stored Programs Binary logging for stored routines takes place as described in Section 18 6 Binary Logging of Stored Programs...

Страница 1716: ... into account as follows The CREATE ROUTINE 576 privilege is needed to create stored routines The ALTER ROUTINE 576 privilege is needed to alter or drop stored routines This privilege is granted automatically to the creator of a routine if necessary and dropped from the creator when the routine is dropped The EXECUTE 577 privilege is required to execute stored routines However this privilege is gr...

Страница 1717: ...lations on values involved in an update A trigger is defined to activate when an INSERT DELETE or UPDATE statement executes for the associated table A trigger can be set to activate either before or after the triggering statement For example you can have a trigger activate before each row that is inserted into a table or after each row that is updated Important MySQL triggers are activated by SQL ...

Страница 1718: ...t and then see what value the variable has afterward mysql SET sum 0 mysql INSERT INTO account VALUES 137 14 98 141 1937 50 97 100 00 mysql SELECT sum AS Total amount inserted Total amount inserted 1852 48 In this case the value of sum after the INSERT statement has executed is 14 98 1937 50 100 or 1852 48 To destroy the trigger use a DROP TRIGGER statement You must specify the schema name if the ...

Страница 1719: ...BEGIN IF NEW amount 0 THEN SET NEW amount 0 ELSEIF NEW amount 100 THEN SET NEW amount 100 END IF END mysql delimiter It can be easier to define a stored procedure separately and then invoke it from the trigger using a simple CALL statement This is also advantageous if you want to invoke the same routine from within several triggers There are some limitations on what can appear in statements that a...

Страница 1720: ... 6 MySQL 5 0 FAQ Views There are some restrictions on the use of views see Section E 4 Restrictions on Views 18 4 1 View Syntax The CREATE VIEW statement creates a new view see Section 13 1 12 CREATE VIEW Syntax To alter the definition of a view or drop a view use ALTER VIEW see Section 13 1 5 ALTER VIEW Syntax or DROP VIEW see Section 13 1 19 DROP VIEW Syntax A view can be created from many kinds...

Страница 1721: ...ioned earlier MERGE is handled by merging corresponding parts of a view definition into the statement that refers to the view The following examples briefly illustrate how the MERGE algorithm works The examples assume that there is a view v_merge that has this definition CREATE ALGORITHM MERGE VIEW v_merge vc1 vc2 AS SELECT c1 c2 FROM t WHERE c3 100 Example 1 Suppose that we issue this statement S...

Страница 1722: ...pdatable view in the FROM clause A subquery in the WHERE clause that refers to a table in the FROM clause Refers only to literal values in this case there is no underlying table to update Uses ALGORITHM TEMPTABLE use of a temporary table always makes a view nonupdatable Multiple references to any column of a base table With respect to insertability being updatable with INSERT statements an updatab...

Страница 1723: ...e scope of check testing when the view is defined in terms of another view The LOCAL keyword restricts the CHECK OPTION only to the view being defined CASCADED causes the checks for underlying views to be evaluated as well When neither keyword is given the default is CASCADED Consider the definitions for the following table and set of views mysql CREATE TABLE t1 a INT mysql CREATE VIEW v1 AS SELEC...

Страница 1724: ...rivileges of the account named by its DEFINER attribute These privileges may be entirely different from those of the invoking user The invoker must have appropriate privileges to reference the object for example EXECUTE 577 to call a stored procedure or SELECT 578 to select from a view but when the object executes the invoker s privileges are ignored and only the DEFINER account privileges matter ...

Страница 1725: ... reference to these objects by not granting unauthorized users particular privileges A stored procedure or function cannot be referenced by a user who does not have the EXECUTE 577 privilege for it A view cannot be referenced by a user who does not have the appropriate privilege for it SELECT 578 to select from it INSERT 577 to insert into it and so forth However no such control exists for trigger...

Страница 1726: ...ng which solves or alleviates these issues because the log contains changes made to individual rows as a result of executing SQL statements Unless noted otherwise the remarks here assume that you have enabled binary logging by starting the server with the log bin 1467 option See Section 5 2 3 The Binary Log If the binary log is not enabled replication is not possible nor is the binary log availabl...

Страница 1727: ...ption CREATE TRIGGER does not have an optional DETERMINISTIC characteristic so triggers are assumed to be always deterministic However this assumption might in some cases be invalid For example the UUID 967 function is nondeterministic and does not replicate You should be careful about using such functions in triggers Triggers can update tables so error messages similar to those for stored functio...

Страница 1728: ...outine related statements in the binary log means that stored routines are not replicated correctly It also means that for a data recovery operation re executing events in the binary log does not recover stored routines Routine logging changes in MySQL 5 0 6 To address the absence of logging for stored routine creation and CALL statements and the consequent replication and data recovery concerns t...

Страница 1729: ...his variable by using the log bin trust routine creators 1 1468 option when starting the server If binary logging is not enabled log_bin_trust_routine_creators does not apply SUPER 578 is not required for routine creation unless as described previously the DEFINER value in the routine definition requires it If a routine that performs updates is nondeterministic it is not repeatable This can have t...

Страница 1730: ...f the function itself modifies data This logging behavior has the potential to cause problems Suppose that a function myfunc is defined as follows CREATE FUNCTION myfunc RETURNS INT DETERMINISTIC BEGIN INSERT INTO t i VALUES 1 RETURN 0 END Given that definition the following statement is not written to the binary log because it is a SELECT Nevertheless it modifies the table t because myfunc modifi...

Страница 1731: ...tements are logged as SELECT func_name statements instead Stored procedure calls are logged at the statement level rather than at the CALL level That is the server does not log the CALL statement it logs those statements within the procedure that actually execute As a result the same changes that occur on the master will be observed on slave servers This eliminates the problems that could result f...

Страница 1732: ...hin a committed or rolled back transaction Previously CALL statements were logged even if they occurred within a rolled back transaction As of MySQL 5 0 12 transactional context is accounted for so that the transactional aspects of procedure execution are replicated correctly That is the server logs those statements within the procedure that actually execute and modify data and also logs BEGIN COM...

Страница 1733: ...ed within the function To reflect the lifting of the restriction on stored procedures the log_bin_trust_routine_creators system variable is renamed to log_bin_trust_function_creators 463 and the log bin trust routine creators 1468 server option is renamed to log bin trust function creators 1468 For backward compatibility the old names are recognized but result in a warning Error messages that now ...

Страница 1734: ...1714 ...

Страница 1735: ...about the data such as the name of a database or table the data type of a column or access privileges Other terms that sometimes are used for this information are data dictionary and system catalog INFORMATION_SCHEMA is the information database the place that stores information about all the other databases that the MySQL server maintains Inside INFORMATION_SCHEMA there are several read only table...

Страница 1736: ...nded as a more consistent way to provide access to the information provided by the various SHOW statements that MySQL supports SHOW DATABASES SHOW TABLES and so forth Using SELECT has these advantages compared to SHOW It conforms to Codd s rules That is all access is done on tables Nobody needs to learn a new statement syntax Because they already know how SELECT works they only need to learn the o...

Страница 1737: ...w dbazine com db2 db2 disarticles gulutzan5 Many sections indicate what SHOW statement is equivalent to a SELECT that retrieves information from INFORMATION_SCHEMA For SHOW statements that display information for the default database if you omit a FROM db_name clause you can often select information for the default database by adding an AND TABLE_SCHEMA DATABASE condition to the WHERE clause of a ...

Страница 1738: ...OLLATION statement The following statements are equivalent SELECT COLLATION_NAME FROM INFORMATION_SCHEMA COLLATIONS WHERE COLLATION_NAME LIKE wild SHOW COLLATION LIKE wild 19 3 The INFORMATION_SCHEMA COLLATION_CHARACTER_SET_APPLICABILITY Table The COLLATION_CHARACTER_SET_APPLICABILITY table indicates what character set is applicable for what collation The columns are equivalent to the first two di...

Страница 1739: ... byte character sets CHARACTER_SET_NAME can be derived from Collation For example if you say SHOW FULL COLUMNS FROM t and you see in the Collation column a value of latin1_swedish_ci the character set is what is before the first underscore latin1 The following statements are nearly equivalent SELECT COLUMN_NAME DATA_TYPE IS_NULLABLE COLUMN_DEFAULT FROM INFORMATION_SCHEMA COLUMNS WHERE table_name t...

Страница 1740: ...ns have constraints INFORMATION_SCHEMA Name SHOW Name Remarks CONSTRAINT_CATALOG NULL CONSTRAINT_SCHEMA CONSTRAINT_NAME TABLE_CATALOG TABLE_SCHEMA TABLE_NAME COLUMN_NAME ORDINAL_POSITION POSITION_IN_UNIQUE_CONSTRAINT REFERENCED_TABLE_SCHEMA REFERENCED_TABLE_NAME REFERENCED_COLUMN_NAME Notes If the constraint is a foreign key then this is the column of the foreign key not the column that the foreig...

Страница 1741: ...ROFILES and SHOW PROFILE statements see Section 13 7 5 29 SHOW PROFILES Syntax The table is empty unless the profiling 483 session variable is set to 1 INFORMATION_SCHEMA Name SHOW Name Remarks QUERY_ID Query_ID SEQ STATE Status DURATION Duration CPU_USER CPU_user CPU_SYSTEM CPU_system CONTEXT_VOLUNTARY Context_voluntary CONTEXT_INVOLUNTARY Context_involuntary BLOCK_OPS_IN Block_ops_in BLOCK_OPS_O...

Страница 1742: ...led state executes 19 8 The INFORMATION_SCHEMA ROUTINES Table The ROUTINES table provides information about stored routines both procedures and functions The ROUTINES table does not include user defined functions UDFs The column named mysql proc name indicates the mysql proc table column that corresponds to the INFORMATION_SCHEMA ROUTINES table column if any INFORMATION_SCHEMA Name mysql proc Name...

Страница 1743: ...owing statements are equivalent SELECT SCHEMA_NAME AS Database FROM INFORMATION_SCHEMA SCHEMATA WHERE SCHEMA_NAME LIKE wild SHOW DATABASES LIKE wild 19 10 The INFORMATION_SCHEMA SCHEMA_PRIVILEGES Table The SCHEMA_PRIVILEGES table provides information about schema database privileges This information comes from the mysql db grant table INFORMATION_SCHEMA Name SHOW Name Remarks GRANTEE user_name hos...

Страница 1744: ... QUALIFIER with CATALOG and we replaced the name OWNER with SCHEMA Clearly the preceding table and the output from SHOW INDEX are derived from the same parent So the correlation is already close The following statements are equivalent SELECT FROM INFORMATION_SCHEMA STATISTICS WHERE table_name tbl_name AND table_schema db_name SHOW INDEX FROM tbl_name FROM db_name 19 12 The INFORMATION_SCHEMA TABLE...

Страница 1745: ...hould be BASE TABLE or VIEW Currently the TABLES table does not list TEMPORARY tables The TABLE_ROWS column is NULL if the table is in the INFORMATION_SCHEMA database For InnoDB tables the row count is only a rough estimate used in SQL optimization We have nothing for the table s default character set TABLE_COLLATION is close because collation names begin with a character set name The following st...

Страница 1746: ...LL TABLE_SCHEMA TABLE_NAME PRIVILEGE_TYPE IS_GRANTABLE Notes PRIVILEGE_TYPE can contain one and only one of these values SELECT 578 INSERT 577 UPDATE 578 REFERENCES 577 ALTER 576 INDEX 577 DROP 577 CREATE VIEW 577 The following statements are not equivalent SELECT FROM INFORMATION_SCHEMA TABLE_PRIVILEGES SHOW GRANTS 19 15 The INFORMATION_SCHEMA TRIGGERS Table The TRIGGERS table provides informatio...

Страница 1747: ...he Statement column of the output from SHOW TRIGGERS Note that this text uses UTF 8 encoding The ACTION_ORIENTATION column always contains the value ROW The ACTION_TIMING column contains one of the two values BEFORE or AFTER The columns ACTION_REFERENCE_OLD_ROW and ACTION_REFERENCE_NEW_ROW contain the old and new column identifiers respectively This means that ACTION_REFERENCE_OLD_ROW always conta...

Страница 1748: ...marks GRANTEE user_name host_name value MySQL extension TABLE_CATALOG NULL MySQL extension PRIVILEGE_TYPE MySQL extension IS_GRANTABLE MySQL extension Notes This is a nonstandard table It takes its values from the mysql user table 19 17 The INFORMATION_SCHEMA VIEWS Table The VIEWS table provides information about views in databases You must have the SHOW VIEW 578 privilege to access this table INF...

Страница 1749: ...to a value different from ANSI 540 could cause the view to become invalid But this is not the case No matter how you write out a view definition MySQL always stores it the same way in a canonical form Here is an example that shows how the server changes a double bar concatenation operator to a CONCAT 887 function mysql SET sql_mode ANSI Query OK 0 rows affected 0 00 sec mysql CREATE VIEW test v AS...

Страница 1750: ...d against the column names displayed by the SHOW statement For example the SHOW CHARACTER SET statement produces these output columns mysql SHOW CHARACTER SET Charset Description Default collation Maxlen big5 Big5 Traditional Chinese big5_chinese_ci 2 dec8 DEC West European dec8_swedish_ci 1 cp850 DOS West European cp850_general_ci 1 hp8 HP West European hp8_english_ci 1 koi8r KOI8 R Relcom Russia...

Страница 1751: ...hinese_ci 2 ujis EUC JP Japanese ujis_japanese_ci 3 sjis Shift JIS Japanese sjis_japanese_ci 2 euckr EUC KR Korean euckr_korean_ci 2 gb2312 GB2312 Simplified Chinese gb2312_chinese_ci 2 gbk GBK Simplified Chinese gbk_chinese_ci 2 utf8 UTF 8 Unicode utf8_general_ci 3 ucs2 UCS 2 Unicode ucs2_general_ci 2 cp932 SJIS for Windows Japanese cp932_japanese_ci 2 eucjpms UJIS for Windows Japanese eucjpms_ja...

Страница 1752: ...1732 ...

Страница 1753: ...erence 2054 20 3 6 JDBC Concepts 2087 20 3 7 Connection Pooling with Connector J 2096 20 3 8 Load Balancing with Connector J 2099 20 3 9 Failover with Connector J 2101 20 3 10 Using the Connector J Interceptor Classes 2103 20 3 11 Using Connector J with Tomcat 2103 20 3 12 Using Connector J with JBoss 2105 20 3 13 Using Connector J with Spring 2106 20 3 14 Using Connector J with GlassFish 2110 20 ...

Страница 1754: ...ache plugin mysqlnd_memcache 2795 20 7 11 Connector PHP 2804 20 7 12 Common Problems with MySQL and PHP 2804 20 7 13 Enabling Both mysql and mysqli in PHP 2804 20 8 MySQL Perl API 2805 20 9 MySQL Python API 2806 20 10 MySQL Ruby APIs 2806 20 10 1 The MySQL Ruby API 2806 20 10 2 The Ruby MySQL API 2806 20 11 MySQL Tcl API 2806 20 12 MySQL Eiffel Wrapper 2806 MySQL Connectors provide connectivity to...

Страница 1755: ...y the Connectors or APIs in this chapter the C API is where to start A number of programmer s utilities are available to help with the process see Section 4 7 MySQL Program Development Utilities Third Party MySQL APIs The remaining APIs described in this chapter provide an interface to MySQL from specific application languages These third party solutions are not developed or supported by Oracle Ba...

Страница 1756: ...JDBC Connector J Native Driver See Section 20 3 MySQL Connector J Kaya MyDB libmysqlclient See MyDB Lua LuaSQL libmysqlclient See LuaSQL NET Mono Connector Net Native Driver See Section 20 2 MySQL Connector Net Objective Caml OBjective Caml MySQL Bindings libmysqlclient See MySQL Bindings for Objective Caml Octave Database bindings for GNU Octave libmysqlclient See Database bindings for GNU Octave...

Страница 1757: ...he family of MySQL ODBC drivers previously called MyODBC drivers that provide access to a MySQL database using the industry standard Open Database Connectivity ODBC API This reference covers Connector ODBC 5 2 which includes the functionality of the Unicode driver and the ANSI driver which formerly were split between Connector ODBC 5 1 and Connector ODBC 3 51 MySQL Connector ODBC provides both dri...

Страница 1758: ...ew features such as enabling server side prepared statements by default At installation time you can choose the Unicode driver for the broadest compatibility with data sources using various character sets or the ANSI driver for optimal performance with a more limited range of character sets It works with MySQL versions 4 1 1 and higher Connector ODBC 5 1 now superceded by 5 2 is a partial rewrite ...

Страница 1759: ...ange of databases or data sources ODBC is a standardized API that enables connections to SQL database servers It was developed according to the specifications of the SQL Access Group and defines a set of function calls error codes and data types that can be used to develop database independent applications ODBC usually is used when database independence or simultaneous access to different data sou...

Страница 1760: ...ot care where the data is stored how it is stored or even how the system is configured to access the data It needs to know only the Data Source Name DSN A number of tasks are common to all applications no matter how they use ODBC These tasks are Selecting the MySQL server and connecting to it Submitting SQL statements for execution Retrieving results if any Processing errors Committing or rolling ...

Страница 1761: ...driver is a library that implements the functions supported by the ODBC API It processes ODBC function calls submits SQL requests to MySQL server and returns results back to the application If necessary the driver modifies an application s request so that the request conforms to syntax supported by MySQL DSN Configuration The ODBC configuration file stores the driver and database information requi...

Страница 1762: ...ets through its ANSI driver Some users postponed their upgrade to Connector ODBC 5 1 remaining with the older 3 51 version to keep this performance edge As of Connector ODBC 5 2 both kinds of drivers are available based on the 5 x code base you can choose either a Unicode enabled driver or an ANSI driver on the download page The Unicode enabled driver recommended for most users has no special qual...

Страница 1763: ...MDAC are up to date You can obtain the latest version from the Microsoft Data Access and Storage Web site There are different distribution types to use when installing for Windows The software that is installed is identical in each case only the installation method is different The zipped installer consists of a zipped package containing a standalone installation application To install from this p...

Страница 1764: ...ow that the installation is complete configure your ODBC connections using Section 20 1 4 Configuring Connector ODBC 20 1 3 1 2 Installing the Windows Connector ODBC Driver using the Zipped DLL Package If you have downloaded the zipped DLL package 1 Unzip the installation files 2 Run the included batch file to perform an installation to the default locations 3 Alternatively install the individual ...

Страница 1765: ...e Windows System32 C copy bin myodbc3c exe Windows System32 6 Optionally copy the help files For these files to be accessible through the help system they must be installed in the Windows system directory C copy doc hlp Windows System32 7 Finally register the Connector ODBC driver with the ODBC manager For Unicode enabled driver C myodbc3i a d t MySQL ODBC 5 2 Driver DRIVER myodbc5w dll SETUP myod...

Страница 1766: ...ocuments to usr local lib and usr share doc MyODBC respectively See Section 20 1 4 5 Configuring a Connector ODBC DSN on Unix for the post installation configuration steps To uninstall the driver become root and execute an rpm command shell su root shell rpm e mysql connector odbc 20 1 3 3 Installing Connector ODBC on Mac OS X Mac OS X is based on the FreeBSD operating system and you can normally ...

Страница 1767: ...d Connector ODBC 5 2 cmake MySQL client libraries and include files from MySQL 4 0 0 or higher Preferably MySQL 4 0 16 or higher This is required because Connector ODBC uses calls and structures that exist only starting from this version of the library To get the client libraries and include files visit http dev mysql com downloads Build Steps Set the environment variables for the Visual Studio to...

Страница 1768: ... to work with the iODBC and unixODBC managers See Section 20 1 2 1 2 ODBC Driver Managers for more information If you are using a character set that is not compiled into the MySQL client library install the MySQL character definitions from the charsets directory into SHAREDIR by default usr local mysql share mysql charsets These should be in place if you have installed the MySQL server on the same...

Страница 1769: ...is option is available only for source trees that have been obtained from the Subversion repository This option does not apply to the packaged source distributions By default the driver is built with the without docs option If you would like the documentation to be built then execute configure with with docs Build Steps for Unix To build the driver libraries execute make shell make If any errors o...

Страница 1770: ...shell CC usr bin gcc CC bundle flat_namespace undefined error o libs libmyodbc3_r 3 51 01 so catalog o connect o cursor o dll o error o execute o handle o info o misc o myodbc3 o options o prepare o results o transact o utility o L usr local mysql lib mysql L usr local iodbc lib lz lc lmysqlclient_r liodbcinst Installing Driver Libraries To install the driver libraries execute the following comman...

Страница 1771: ...read safe driver library shell CC usr bin gcc CC bundle flat_namespace undefined error o libs libmyodbc3 3 51 01 so o L usr local mysql lib L usr local iodbc lib liodbcinst lmysqlclienti_r lz lc lpthread Make sure to change the liodbcinst to lodbcinst in case of using unixODBC instead of iODBC and configure the libraries path accordingly In Apple s version of GCC both cc and gcc are actually symbo...

Страница 1772: ...er For more information see Section 20 1 3 4 Building Connector ODBC from a Source Distribution on Windows After the initial checkout operation to get the source tree run bzr pull periodically to update your source according to the latest version 20 1 4 Configuring Connector ODBC Before you connect to a MySQL database using the Connector ODBC driver you configure an ODBC Data Source Name DSN The D...

Страница 1773: ...guration Alternatively you can set these parameters within the InConnectionString argument in the SQLDriverConnect call Table 20 3 Connector ODBC DSN Configuration Options Parameter Default Value Comment user ODBC The user name used to connect to MySQL uid ODBC Synonymous with user Added in 3 51 16 server localhost The host name of the MySQL server database The default database option 0 Options th...

Страница 1774: ...ables the CLIENT_INTERACTIVE connection option of mysql_real_connect prefetch 0 When set to a non zero value N causes all queries in the connection to return N rows at a time rather than the entire result set Useful for queries against very large tables where it is not practical to retrieve the whole result set at once You can scroll through the result set N records at a time This option works onl...

Страница 1775: ... Calls To myodbc log Make a debug log in C myodbc log on Windows or tmp myodbc log on Unix variants This option was removed in Connector ODBC 3 51 18 FLAG_BIG_PACKETS Allow Big Results 8 Do not set any packet limit for results and bind parameters Without this option parameter binding will be truncated to 255 characters FLAG_NO_PROMPT Do not Prompt Upon Connect 16 Do not prompt for questions even i...

Страница 1776: ... Enable query logging to c myodbc sql tmp myodbc sql file Enabled only in debug mode FLAG_NO_CACHE Do not Cache Result forward only cursors 1048576 Do not cache the results locally in the driver instead read from server mysql_use_result This works only for forward only cursors This option is very important in dealing with large tables when you do not want the driver to cache the entire result set ...

Страница 1777: ...ue where some statements will not work because the date returned and the minimum ODBC date value are incompatible Added in 3 51 17 FLAG_MIN_DATE_TO_ZERO Bind minimal date as zero date 33554432 Translates the minimum ODBC date value XXXX 01 01 to the zero date format supported by MySQL XXXX 00 00 This resolves an issue where some statements will not work because the date returned and the minimum OD...

Страница 1778: ...ddition to using the options parameter with various flags set you can use the flags directly as parameters For example FIELD_LENGTH FOUND_ROWS and DEBUG could all be used as parameters The following table shows some recommended option values for various configurations Table 20 5 Recommended Connector ODBC option Values for Different Configurations Configuration Option Value Microsoft Access Visual...

Страница 1779: ...k Data Sources ODBC To open the ODBC Data Source Administrator in Windows 2000 Server or Windows 2000 Professional 1 On the Start menu choose Settings and then click Control Panel 2 In Control Panel click Administrative Tools 3 In Administrative Tools click Data Sources ODBC To open the ODBC Data Source Administrator on Windows XP 1 On the Start menu click Control Panel 2 In the Control Panel when...

Страница 1780: ...ng the ODBC Data Source Administrator to your Start menu To do this locate the Data Sources ODBC icon using the methods shown then right click on the icon and then choose Pin to Start Menu The interfaces for the 3 51 and 5 x versions of the Connector ODBC driver are different although the fields and information that you need to enter remain the same To configure a DSN using Connector ODBC 5 2 see ...

Страница 1781: ...e a System DSN which will be available to all users select the System DSN tab To create a User DSN which will be unique only to the current user click the Add button 3 Select the ODBC driver for this DSN Select MySQL ODBC 5 x Driver for the appropriate level of Connector ODBC then click Finish 4 You now need to configure the specific fields for the DSN you are creating through the Connection Param...

Страница 1782: ...e Password field enter the corresponding password for this connection 9 The Database pop up should automatically populate with the list of databases that the user has permissions to access 10 To communicate over a different TCP IP port than the default 3306 change the value of the Port 11 Click OK to save the DSN To verify the connection using the parameters you have entered click the Test button ...

Страница 1783: ...Configuring Connector ODBC 1763 ...

Страница 1784: ...about the meaning of these options 20 1 4 3 2 Configuring a Connector ODBC 5 x DSN on Windows Using the Command Line Use myodbc installer exe when configuring Connector ODBC 5 1 or later from the command line Execute myodbc installer exe without arguments to view a list of available options 20 1 4 3 3 Troubleshooting ODBC Connection Problems This section answers Connector ODBC connection related q...

Страница 1785: ...C odbc ini file used to set up ODBC connectivity and DSNs are writable by the admin group If this file is not writable by this group then the ODBC Administrator may fail or may appear to work but not generate the correct entry Warning There are known issues with the Mac OS X ODBC Administrator and Connector ODBC that may prevent you from creating a DSN using this method In this case use the comman...

Страница 1786: ...C 1766 2 On the User DSN or System DSN panel click Add 3 Select the Connector ODBC driver and click OK 4 You will be presented with the Data Source Name dialog Enter the Data Source Name and an optional Description for the DSN ...

Страница 1787: ...anel Configure at least four pairs to specify the server username password and database connection parameters See Section 20 1 4 2 Connector ODBC Connection Parameters 6 Click OK to add the DSN to the list of configured data source names A completed DSN configuration may look like this ...

Страница 1788: ...SN name for Connector ODBC 3 51 odbc ini configuration for Connector ODBC and Connector ODBC 3 51 drivers ODBC Data Sources myodbc3 MyODBC 3 51 Driver DSN myodbc3 Driver usr local lib libmyodbc3 so Description Connector ODBC 3 51 Driver DSN SERVER localhost PORT USER root Password Database test OPTION 3 SOCKET Default Driver usr local lib libmyodbc3 so Description Connector ODBC 3 51 Driver DSN SE...

Страница 1789: ...ing as a single long string or to use a concatenation of multiple strings that does not add spaces in between For example ConnectionString DRIVER MySQL ODBC 3 51 Driver SERVER localhost DATABASE test USER venu PASSWORD venu OPTION 3 Note On Mac OS X you might need to specify the full path to the Connector ODBC driver library Refer to Section 20 1 4 2 Connector ODBC Connection Parameters for the li...

Страница 1790: ...pplications 3 ODBC function calls from applications running before tracing is activated are not logged ODBC function calls are recorded in a log file you specify 4 Tracing ceases only after you click Stop Tracing Now Remember that while tracing is on the log file continues to increase in size and that tracing affects the performance of all your ODBC applications 20 1 4 8 2 Enabling ODBC Tracing on...

Страница 1791: ...click the Choose button 20 1 4 8 3 Enabling ODBC Tracing on Unix To enable the trace option on Mac OS X 10 2 or earlier or Unix add the trace option to the ODBC configuration 1 On Unix explicitly set the Trace option in the ODBC INI file Set the tracing ON or OFF by using TraceFile and Trace parameters in odbc ini as shown below TraceFile tmp odbc trace Trace 1 ...

Страница 1792: ...e corresponding keyword value pair in the DSN 2 Start your application and try to get it to fail Then check the Connector ODBC trace file to find out what could be wrong If you need help determining what is wrong see Section 20 1 8 1 Connector ODBC Community Support 20 1 5 Connector ODBC Examples Once you have configured a DSN to provide access to a database how you access and use that connection ...

Страница 1793: ...Connector ODBC Examples 1773 ...

Страница 1794: ... you have just configured on system ALPHA Parameter Value Comment DSN remote_test A name to identify the connection SERVER ALPHA The address of the remote server DATABASE test The name of the default database USER myuser The user name configured for access to this database PASSWORD mypassword The password for myuser 2 Using an ODBC capable application such as Microsoft Office connect to the MySQL ...

Страница 1795: ...stems Vision Sybase PowerBuilder PowerDesigner theKompany com Data Architect If you know of any other applications that work with Connector ODBC please send mail to myodbc lists mysql com about them 20 1 5 4 Using Connector ODBC with Microsoft Access You can use MySQL database with Microsoft Access using Connector ODBC The MySQL database can be used as an import source an export source or as a lin...

Страница 1796: ...er a name for the file or use the suggested name and then select OK 5 The Select Data Source dialog box is displayed it lists the defined data sources for any ODBC drivers installed on your computer Click either the File Data Source or Machine Data Source tab and then double click the Connector ODBC or Connector ODBC 3 51 data source to export to To define a new data source for Connector ODBC plea...

Страница 1797: ...ect Data Source dialog box lists the defined data sources The Select Data Source dialog box is displayed it lists the defined data source names 4 If the ODBC data source that you selected requires you to log on enter your login ID and password additional information might also be required and then click OK 5 Microsoft Access connects to the MySQL server through ODBC data source and displays the li...

Страница 1798: ...es of type pop up 4 In the Select Data Source window choose an existing DSN either from a File Data Source or Machine Data Source You can also create a new DSN using the New button For more information on creating a DSN see Section 20 1 4 3 Configuring a Connector ODBC DSN on Windows ...

Страница 1799: ...Connector ODBC Examples 1779 5 In the Link Tables dialog select one or more tables from the MySQL database A link will be created to each table that you select from this list ...

Страница 1800: ...0 or newer and then click Linked Table Manager 3 Select the check box for the tables whose links you want to refresh 4 Click OK to refresh the links Microsoft Access confirms a successful refresh or if the table wasn t found displays the Select New Location of table name dialog box in which you can specify its the table s new location If several selected tables have moved to the new location that ...

Страница 1801: ... source You use Microsoft Query to build the SQL statement to be executed selecting the tables fields selection criteria and sort order For example to insert information from a table in the World test database into an Excel spreadsheet using the DSN samples shown in Section 20 1 4 Configuring Connector ODBC 1 Create a new Worksheet 2 From the Data menu choose Import External Data and then select N...

Страница 1802: ...Connector ODBC Examples 1782 5 You can filter rows from the query the equivalent of a WHERE clause using the Filter Data dialog Click Next to continue ...

Страница 1803: ...ntinue 7 Select the destination for your query You can select to return the data Microsoft Excel where you can choose a worksheet and cell where the data will be inserted you can continue to view the query and results within Microsoft Query where you can edit the SQL query and further filter and sort the information returned or you can create an OLAP Cube from the query which can then be used dire...

Страница 1804: ...t version including any outstanding service packs and hotfixes For more information on this issue see the Business Objects Knowledgebase for more information For example to create a simple crosstab report within Crystal Reports XI follow these steps 1 Create a DSN using the Data Sources ODBC tool You can either specify a complete database including user name and password or you can build a basic D...

Страница 1805: ...an select either a pre configured DSN open a file based DSN or enter and manual connection string For this example the Sakila DSN will be used If the DSN contains a user name password combination or you want to use different authentication credentials click Next to enter the user name and password that you want to use Otherwise click Finish to continue the data source selection wizard ...

Страница 1806: ...e will expand the selected Sakila database Click the city table and use the button to add the table to the report Then repeat the action with the country table Alternatively you can select multiple tables and add them to the report Finally you can select the parent Sakila resource and add of the tables to the report Once you have selected the tables you want to include click Next to continue ...

Страница 1807: ...ntification of links between tables enables Crystal Reports to automatically lookup and summarize information based on all the tables in the database according to your query If Crystal Reports is unable to perform the linking itself you can manually create the links between fields in the tables you have selected Click Next to continue the process ...

Страница 1808: ... each area of the report In the example shown we will report on cities organized by country incorporating a count of the number of cities within each country If you want to browse the data select a field and click the Browse Data button Click Next to create a graph of the results Since we are not creating a graph from this data click Finish to generate the report ...

Страница 1809: ...Connector ODBC Examples 1789 8 The finished report will be shown a sample of the output from the Sakila sample database is shown below ...

Страница 1810: ...iver installed any programming language or environment that can support ODBC can connect to a MySQL database through Connector ODBC This includes but is not limited to Microsoft support languages including Visual Basic C and interfaces such as ODBC NET Perl through the DBI module and the DBD ODBC driver 20 1 5 7 1 Using Connector ODBC with Visual Basic Using ADO DAO and RDO This section contains s...

Страница 1811: ...stamp direct insert conn Execute INSERT INTO my_ado id name txt values 1 100 venu conn Execute INSERT INTO my_ado id name txt values 2 200 MySQL conn Execute INSERT INTO my_ado id name txt values 3 300 Delete Set rs New ADODB Recordset rs CursorLocation adUseServer fetch the initial table rs Open SELECT FROM my_ado conn Debug Print rs RecordCount rs MoveFirst Debug Print String 50 Initial my_ado R...

Страница 1812: ...date and result set scrolling Private Sub myodbc_dao_Click Dim ws As Workspace Dim conn As Connection Dim queryDef As queryDef Dim str As String connect to MySQL using MySQL ODBC 3 51 Driver Set ws DBEngine CreateWorkspace venu venu dbUseODBC str odbc DRIVER MySQL ODBC 3 51 Driver _ SERVER localhost _ DATABASE test _ UID venu PWD venu OPTION 3 Set conn ws OpenConnection test dbDriverNoPrompt False...

Страница 1813: ...Close End Sub 20 1 5 7 1 3 RDO rs addNew and rs update The following RDO Remote Data Objects example creates a table my_rdo and demonstrates the use of rs addNew and rs update Dim rs As rdoResultset Dim cn As New rdoConnection Dim cl As rdoColumn Dim SQL As String cn Connect DSN test cn Connect DRIVER MySQL ODBC 3 51 Driver _ SERVER localhost _ DATABASE test _ UID venu PWD venu OPTION 3 cn CursorD...

Страница 1814: ...SQL rdOpenStatic rdConcurRowVer rdExecDirect Do Until rs EOF For Each cl In rs rdoColumns Debug Print cl Value Next rs MoveNext Debug Print Loop Debug Print Row count rs RowCount close rs Close cn Close End Sub 20 1 5 7 2 Using Connector ODBC with NET This section contains simple examples that demonstrate the use of Connector ODBC drivers with ODBC NET 20 1 5 7 2 1 Using Connector ODBC with ODBC N...

Страница 1815: ...e Console WriteLine tDriver MyConnection Driver Console WriteLine tServerVersion MyConnection ServerVersion Create a sample table OdbcCommand MyCommand new OdbcCommand DROP TABLE IF EXISTS my_odbc_net MyConnection MyCommand ExecuteNonQuery MyCommand CommandText CREATE TABLE my_odbc_net id int name varchar 20 idb bigint MyCommand ExecuteNonQuery Insert MyCommand CommandText INSERT INTO my_odbc_net ...

Страница 1816: ...r GetInt32 2 Close all resources MyDataReader Close MyConnection Close catch OdbcException MyOdbcException Catch any ODBC exception for int i 0 i MyOdbcException Errors Count i Console Write ERROR i n Message MyOdbcException Errors i Message n Native MyOdbcException Errors i NativeError ToString n Source MyOdbcException Errors i Source n SQL MyOdbcException Errors i SQLState n 20 1 5 7 2 2 Using C...

Страница 1817: ...ecuteNonQuery Insert MyCommand CommandText INSERT INTO my_vb_net VALUES 20 mysql Console WriteLine INSERT Total rows affected _ MyCommand ExecuteNonQuery Insert MyCommand CommandText INSERT INTO my_vb_net VALUES 20 mysql Console WriteLine INSERT Total rows affected _ MyCommand ExecuteNonQuery Insert MyCommand CommandText INSERT INTO my_vb_net id VALUES 30 Console WriteLine INSERT Total rows affect...

Страница 1818: ... microsoft com en us library ms714177 aspx An application can call SQLGetInfo function to obtain conformance information about Connector ODBC To obtain information about support for a specific function in the driver an application can call SQLGetFunctions Note For backward compatibility the Connector ODBC driver supports all deprecated functions The following tables list Connector ODBC API calls g...

Страница 1819: ...urns the value of a connection option SQLSetEnvAttr Yes ISO 92 Sets an environment attribute SQLGetEnvAttr Yes ISO 92 Returns the value of an environment attribute SQLSetStmtAttr Yes ISO 92 Sets a statement attribute SQLGetStmtAttr Yes ISO 92 Returns the value of a statement attribute SQLSetStmtOption Yes Deprecated Sets a statement option SQLGetStmtOption Yes Deprecated Returns the value of a sta...

Страница 1820: ...2 Returns the number of columns in the result set SQLDescribeCol Yes ISO 92 Describes a column in the result set SQLColAttribute Yes ISO 92 Describes attributes of a column in the result set SQLColAttributes Yes Deprecated Describes attributes of a column in the result set SQLFetch Yes ISO 92 Returns multiple result rows SQLFetchScroll Yes ISO 92 Returns scrollable result rows SQLExtendedFetch Yes...

Страница 1821: ...the list of indexes associated with the table SQLTablePrivileges Yes ODBC Returns a list of tables and the privileges associated with each table SQLTables Yes X Open Returns the list of table names stored in a specific data source Table 20 14 ODBC API Calls for Performing Transactions Function Name Connector ODBC Supports Standard Purpose SQLTransact Yes Deprecated Commits or rolls back a transact...

Страница 1822: ...DATE SQL_C_DATE datetime SQL_TIMESTAMP SQL_C_TIMESTAMP decimal SQL_DECIMAL SQL_C_CHAR double precision SQL_DOUBLE SQL_C_DOUBLE double SQL_FLOAT SQL_C_DOUBLE enum SQL_VARCHAR SQL_C_CHAR float SQL_REAL SQL_C_FLOAT int unsigned SQL_INTEGER SQL_C_ULONG int SQL_INTEGER SQL_C_SLONG integer unsigned SQL_INTEGER SQL_C_ULONG integer SQL_INTEGER SQL_C_SLONG long varbinary SQL_LONGVARBINARY SQL_C_BINARY long...

Страница 1823: ...ow updated deleted 505 01S06 01S06 Attempt to fetch before the result set returned the first row set 506 07001 07002 SQLBindParameter not used for all parameters 507 07005 07005 Prepared statement not a cursor specification 508 07009 07009 Invalid descriptor index 509 08002 08002 Connection name in use 510 08003 08003 Connection does not exist 511 24000 24000 Invalid cursor state 512 25000 25000 I...

Страница 1824: ... are based on the experiences of Connector ODBC developers and users 20 1 7 1 Connector ODBC General Functionality This section provides help with common queries and areas of functionality in MySQL and how to use them with Connector ODBC 20 1 7 1 1 Obtaining Auto Increment Values Obtaining the value of column that uses AUTO_INCREMENT after an INSERT statement can be achieved in a number of differe...

Страница 1825: ... for each DSN so make sure to examine only the DSN that you are using in your application Within Windows you can disable the Connector ODBC and query logs by modifying the DSN configuration Within Mac OS X and Unix ensure that the driver trace option value 4 and query logging option value 524288 are not enabled 20 1 7 1 4 Setting ODBC Query Timeout in Windows For more information on how to set the...

Страница 1826: ... fields you want and use that form data sheet view Set the DefaultValue property for the TIMESTAMP column to NOW 926 Consider hiding the TIMESTAMP column from view so your users are not confused In some cases Access may generate SQL statements that MySQL cannot understand You can fix this by selecting Query SQLSpecific Pass Through from the Access menu On Windows NT Access reports BLOB columns as ...

Страница 1827: ...date a table you must define a primary key for the table Visual Basic with ADO cannot handle big integers This means that some queries like SHOW PROCESSLIST do not work properly The fix is to use OPTION 16384 in the ODBC connect string or to select the Change BIGINT columns to INT option in the Connector ODBC connect screen You may also want to select the Return matching rows option 20 1 7 2 1 4 M...

Страница 1828: ...rg How to map Visual basic data type to MySQL types by Mike Hillyer mike openwin org 20 1 7 2 2 Using Connector ODBC with Borland Applications With all Borland applications where the Borland Database Engine BDE is used follow these steps to improve compatibility Update to BDE 3 2 or newer Enable the Don t optimize column widths option in the DSN Enabled the Return matching rows option in the DSN 2...

Страница 1829: ... ColdFusion Server for Linux to use the unixODBC driver with Connector ODBC for MySQL data sources You can download Connector ODBC at http dev mysql com downloads connector odbc ColdFusion version 4 5 1 lets you use the ColdFusion Administrator to add the MySQL data source However the driver is not included with ColdFusion version 4 5 1 Before the MySQL driver appears in the ODBC data sources drop...

Страница 1830: ...temRoot SysWOW64 odbcad32 exe this will correctly locate the installed Connector ODBC drivers and enable you to create a Connector ODBC DSN This issue was originally reported as Bug 20301 Error 10061 Cannot connect to server When connecting or using the Test button in ODBC Data Source Administrator I get error 10061 Cannot connect to server This error can be raised by a number of different issues ...

Страница 1831: ...ct the Change BIGINT columns to INT option in the connection dialog in ODBC DSN Administrator Delete the table link from Access and re create it Old records still display as DELETED but newly added updated records are displayed properly Write Conflicts or Row Location Errors How do I handle Write Conflicts or Row Location errors If you see the following errors select the Return Matching Rows optio...

Страница 1832: ...start by making a log file from the ODBC manager the log you get when requesting logs from ODBCADMIN and a Connector ODBC log to help you figure out why things go wrong For instructions see Section 20 1 4 8 Getting an ODBC Trace File Direct Application Linking Under Unix or Linux When linking an application directly to the Connector ODBC library under Unix or Linux the application crashes Connecto...

Страница 1833: ...or reading communication packets appears in the error log This error may be related to Keyboard Logger 1 1 from PanteraSoft com which is known to interfere with the network communication between MySQL Connector ODBC and MySQL Outer Join Error When using some applications to access a MySQL server using Connector ODBC and outer joins an error is reported regarding the Outer Join Escape Sequence This...

Страница 1834: ...integer value for the table s auto_increment counter 20 1 8 Connector ODBC Support There are many different places where you can get support for using Connector ODBC Always try the Connector ODBC Mailing List or Connector ODBC Forum See Section 20 1 8 1 Connector ODBC Community Support for help before reporting a specific bug or issue to MySQL 20 1 8 1 Connector ODBC Community Support Oracle provi...

Страница 1835: ... and a README file that explains the problem Initiate a bug report for our bugs database at http bugs mysql com then click the Files tab in the bug report for instructions on uploading the archive to the bugs database Only MySQL engineers have access to the files you upload and we are very discreet with the data If you can create a program that also demonstrates the problem please include it in th...

Страница 1836: ...ot currently support Express versions of Microsoft products including Microsoft Visual Web Developer Key topics For connection string properties when using the MySqlConnection class see Section 20 2 6 Connector Net Connection String Options Reference As of Connector Net 5 1 2 the Visual Studio Plugin is part of the main Connector Net package However even for versions of Connector Net older than 5 ...

Страница 1837: ...atures Connector Net 5 1 also includes support for a new membership role provider Compact Framework 2 0 a new stored procedure parser and improvements to GetSchema Connector Net 5 1 also includes the Visual Studio Plugin as a standard installable component This version of Connector Net is no longer supported Connector Net 5 0 includes support for MySQL Server 5 1 5 0 4 1 and 4 0 features Connector...

Страница 1838: ...ns of Microsoft Windows and is supported on Linux through the Open Source Mono framework see http www mono project com Connector Net is available for download from http dev mysql com downloads connector net 20 2 2 1 Installing Connector Net on Windows On Windows you can install either through a binary installation process or by downloading a zip file with the Connector Net components Before instal...

Страница 1839: ...Connector Net Installation 1819 2 You must choose the type of installation to perform ...

Страница 1840: ...u explicitly reference the Connector Net component The installer will also create the necessary links in the Start menu to the documentation and release notes 3 If you have chosen a custom installation you can select the individual components to install including the core interface component supporting documentation a CHM file samples and examples and the source code Select the items and their ins...

Страница 1841: ...Connector Net Installation 1821 4 You will be given a final opportunity to confirm the installation Click Install to copy and install the files onto your machine ...

Страница 1842: ...Connector Net Installation 1822 5 Once the installation has been completed click Finish to exit the installer ...

Страница 1843: ...ronment docs Connector Net documentation in CHM format samples Sample code and applications that use the Connector Net component src The source code for the Connector Net component You may also use the quiet or q command line option with the msiexec tool to install the Connector Net package automatically using the default options with no notification to the user Using this method the user cannot s...

Страница 1844: ...ller program MySql Data Source files for the core data provider MySql VisualStudio Source files for the Microsoft Visual Studio extensions MySql Web Source files for the web providers This includes code for the membership provider role provider and profile provider These are used in ASP NET web sites Samples Source files for several example applications Tests A spreadsheet listing test cases Visua...

Страница 1845: ...piled program for example shell mono HelloWorld exe 20 2 2 3 Installing Connector Net from the Source Code Caution Read this section only if you are interested in helping us test our new code If you just want to get Connector Net up and running on your system use a standard release distribution Obtaining the Source Code To obtain the most recent development source tree first download and install B...

Страница 1846: ... are required to enable new integration features supported in Visual Studio 2010 including New DDL T4 template for the Entity Framework EF This enables developers to design an EF model from scratch and use the native Visual Studio 2010 facility to generate MySQL DDL from that model This is done by creating the model and with the model open choosing the SSDLToMySQL template in the properties window...

Страница 1847: ...L Database is absent and then choose NET Framework Data Provider for MySQL in the combo box of data providers Figure 20 2 Choose Data Source Input the connection settings the server host name for example localhost if the MySQL server is installed on the local machine the user name the password and the default schema name Note that you must specify the default schema name to open the connection ...

Страница 1848: ...ection After the connection is successfully established all settings are saved for future use When you start Visual Studio for the next time open the connection node in Server Explorer to establish a connection to the MySQL server again To modify and delete a connection use the Server Explorer context menu for the corresponding node You can modify any of the settings by overwriting the existing va...

Страница 1849: ...e Tables node under the connection node and choose the Create Table command from the context menu To modify an existing table double click the node of the table to modify or right click this node and choose the Design item from the context menu Either of the commands opens the Table Designer The table editor is implemented in the manner of the well known Query Browser Table Editor but with minor d...

Страница 1850: ...tton of the Visual Studio main toolbar or press Control S If you have not already named the table you will be prompted to do so Figure 20 6 Choose Table Name Once the table is created you can view it in the Server Explorer Figure 20 7 Newly Created Table The Table Designer main menu lets you set a primary key column edit relationships such as foreign keys and create indexes Figure 20 8 Table Desig...

Страница 1851: ...n on a keyboard 20 2 3 3 2 Editing Indexes Indexes management is performed using the Indexes Keys dialog To add an index select Table Designer Indexes Keys from the main menu and click Add to add a new index You can then set the index name index kind index type and a set of index columns Figure 20 9 Indexes Dialog To remove an index select it in the list box on the left and click the Delete button...

Страница 1852: ...sired values Figure 20 10 Foreign Key Relationships Dialog 20 2 3 3 4 Column Properties The Column Properties tab can be used to set column options In addition to the general column properties presented in the Column Editor in the Column Properties tab you can set additional properties such as Character Set Collation and Precision 20 2 3 3 5 Table Properties To bring up Table Properties select the...

Страница 1853: ... Comment Data Directory Index Directory Maximum Rows Minimum Rows Name Row Format Schema Storage Engine Note that in MySQL 5 5 and higher the default storage engine for new tables is InnoDB See InnoDB as the Default MySQL Storage Engine for more information about the choice of storage engine and considerations if you convert existing tables to InnoDB The property Schema is read only ...

Страница 1854: ...reate View command This command opens the SQL Editor Figure 20 13 Editing View SQL You can then enter the SQL for your view Figure 20 14 View SQL Added To modify an existing view double click a node of the view to modify or right click this node and choose the Alter View command from a context menu Either of the commands opens the SQL Editor All other view properties can be set in the Properties w...

Страница 1855: ...edded combobox The properties Is Updatable and Schema are readonly To save changes you have made use either Save or Save All buttons of the Visual Studio main toolbar or press Control S Figure 20 15 View SQL Saved 20 2 3 5 Editing Stored Procedures and Functions To create a new stored procedure right click the Stored Procedures node under the connection node in Server Explorer From the node s cont...

Страница 1856: ...xt menu Either of the commands opens the SQL Editor To create or alter the routine definition using SQL Editor type this definition in the SQL Editor using standard SQL All other routine properties can be set in the Properties window These properties are Body Catalog Comment Creation Time Data Access Definer Definition External Name External Language Is Deterministic Last Modified Name Parameter S...

Страница 1857: ...and from the context menu Either of the commands opens the SQL Editor To create or alter the trigger definition using SQL Editor type the trigger statement in the SQL Editor using standard SQL Note Enter only the trigger statement that is the part of the CREATE TRIGGER query that is placed after the FOR EACH ROW clause All other trigger properties are set in the Properties window These properties ...

Страница 1858: ...s use the Stored Procedure Debugger available in Connector Net 6 6 and higher See Section 20 2 3 8 Debugging Stored Procedures and Functions for details 20 2 3 8 Debugging Stored Procedures and Functions The stored procedure debugger new in Connector Net 6 6 provides facilities for setting breakpoints stepping into individual statements Step Into Step Out Step Over evaluating and changing local va...

Страница 1859: ...ion Click on a stored procedure node then right click and from the context menu choose Debug Routine Figure 20 19 Choose a Stored Routine to Debug At this point Visual Studio switches to debug mode opening the source code of the routine being debugged in step mode positioned on the first statement If the initial routine you debug has one or more arguments a popup will show up with a grid a row per...

Страница 1860: ...rkings of a stored routine the debugger prepares a special version of the procedure function or trigger being debugged instrumented with extra code to keep track of the current line being stepped into and the values of all the local variables Any other stored procedures functions or triggers called from the routine being debugged are instrumented the same way The debug versions of the routines are...

Страница 1861: ...dows Locals The Locals tab lists all the variables available in the current scope variables defined with DECLARE at any point in the routine argument parameters and session variables that are referenced If the last step operation changes the value of a local its value will be highlighted in red until another statement is executed or stepped You can change the value of any local To show the Watch t...

Страница 1862: ...the menu item Debug Windows Call Stack The stack trace in the Call Stack tab will list all the stack traces one for each routine invocation The one with a yellow mark is the current stepping point Clicking in another will activate in the editor the tab for that routine source highlighting in green the last statement stepped ...

Страница 1863: ...onnector Net Visual Studio Integration 1843 Figure 20 23 Call Stack Stepping Stepping of a new routine starts in the first executable instruction excluding declares handlers cursor declarations and so on ...

Страница 1864: ...Connector Net Visual Studio Integration 1844 Figure 20 24 Debug Stepping Figure 20 25 Function Stepping 1 of 2 ...

Страница 1865: ...t and each trigger fired by that statement The order in which they are debugged is the same order in which the MySQL server executes them You can step into triggers triggered from INSERT DELETE UPDATE and REPLACE statements Also the number of times you enter into a stored function or trigger depends on how many rows are evaluated by the function or affected by the trigger For example if you press ...

Страница 1866: ...ve that breakpoint Once a breakpoint is defined it will appear enabled as filled red circle left to the current row if that line is a valid statement to put a breakpoint or disabled as a non filled red circle left to the current row if that row is not valid to put a breakpoint To define conditional breakpoints after creating the breakpoint right click in the red dot and choose Condition There you ...

Страница 1867: ... must not use get_lock or release_lock MySQL functions since they are used internally by the debugger infrastructure to synchronize the debugger and the debugged routine Code being debugged must avoid using any transaction code START TRANSACTION COMMIT ROLLBACK due to the possibility of wiping out the contents of the debugger tables This limitation may be removed in the future You cannot debug the...

Страница 1868: ...dropped with the appropriate Drop command selected from its context menu Drop Table Drop View Drop Routine Drop Trigger Drop UDF You will be asked to confirm the execution of the corresponding drop query in a confirmation dialog You can only drop a single object at a time 20 2 3 11 Using the ADO NET Entity Framework Connector Net 6 0 introduced support for the ADO NET Entity Framework ADO NET Enti...

Страница 1869: ...the Membership Role Session State and Profile Provider without editing configuration files You set your configuration options within the tool and the tool modifies your web config file accordingly The MySQL Website Configuration Tool appears as a small icon on the Solution Explorer toolbar in Visual Studio as show by the following screenshot Figure 20 29 MySQL Website Configuration Tool Clicking t...

Страница 1870: ...r you by selecting the Autogenerate Schema check box These schemas are used to store membership information The database used to storage is the one specified in the connection string You can also ensure that exceptions generated by the application will be written to the Windows event log by selecting the Write exceptions to event log check box Clicking the Advanced button launches a dialog that en...

Страница 1871: ...MySQL Website Configuration Tool Advanced Options Once information has been set up as required for configuration of the Membership Provider the Next button can be clicked to display the Roles Provider screen Figure 20 33 MySQL Website Configuration Tool Roles ...

Страница 1872: ...his screen display similar options to the previous screens Click Next to proceed to the Session State configuration page Figure 20 35 MySQL Website Configuration Tool Session State Once you have set up the Session State Provider as required click Finish to exit the wizard At this point select the Authentication Type to From Internet Launch the ASP NET Configuration Tool and select the Security tab...

Страница 1873: ...MySQL Website Configuration Tool Tables 20 2 3 13 MySQL SQL Editor MySQL Connector Net 6 3 2 introduced a new MySQL SQL Editor The easiest way to invoke the editor is by selecting the New File menu item from the Visual Studio main menu This displays the New File dialog Figure 20 37 MySQL SQL Editor New File From the New File dialog select the MySQL template and then double click the MySQL SQL Scri...

Страница 1874: ...QL server To execute your SQL code against the server click the Run SQL button on the toolbar Figure 20 38 MySQL SQL Editor Query The results from any queries are displayed on the Results tab Any errors are displayed on the Messages tab 20 2 3 14 DDL T4 Template Macro MySQL Connector Net 6 3 introduced the ability to convert an Entity Framework model to MySQL DDL code Starting with a blank model y...

Страница 1875: ...9 DDL T4 Template Macro Model Properties Right clicking the model design area displays a context sensitive menu Selecting Generate Database from Model from the menu displays the Generate Database Wizard The wizard can then be used to generate MySQL DDL code ...

Страница 1876: ...signed to work on both Microsoft NET Framework and Mono This tutorial is designed to get you up and running with Connector Net as quickly as possible it does not go into detail on any particular topic However the following sections of this manual describe each of the topics introduced in this tutorial in more detail In this tutorial you are encouraged to type in and run the code modifying it as re...

Страница 1877: ...tor is invoked it returns a connection object which is used for subsequent database operations Open the connection before any other operations take place Before the application exits close the connection to the database by calling Close on the connection object Sometimes an attempt to perform an Open on a connection object can fail generating an exception that can be handled using standard excepti...

Страница 1878: ...s passed to the MySqlCommand constructor The ExecuteReader method is then used to generate a MySqlReader object The MySqlReader object contains the results generated by the SQL executed on the command object Once the results have been obtained in a MySqlReader object the results can be processed In this case the information is printed out by a while loop Finally the MySqlReader object is disposed ...

Страница 1879: ...ic static void Main string connStr server localhost user root database world port 3306 password MySqlConnection conn new MySqlConnection connStr try Console WriteLine Connecting to MySQL conn Open string sql SELECT COUNT FROM Country MySqlCommand cmd new MySqlCommand sql conn object result cmd ExecuteScalar if result null int r Convert ToInt32 result Console WriteLine Number of countries in the Wo...

Страница 1880: ...f the class MySqlCommandBuilder is created Each of these classes will now be discussed in more detail Instantiating a DataSet object A DataSet object can be created simply as shown in the following example code snippet DataSet dsCountry dsCountry new DataSet Although this creates the DataSet object it has not yet filled it with data For that a Data Adapter is required Instantiating a MySqlDataAdap...

Страница 1881: ... clicking an update button The update button then activates code to write changes back to the database The code uses the principles explained above The application was built using the Microsoft Visual Studio to place and create the user interface controls but the main code that uses the key classes described above is shown below and is portable using System using System Collections Generic using S...

Страница 1882: ... be processed as field data only For example imagine the following query was constructed from user input string sql SELECT Name HeadOfState FROM Country WHERE Continent user_continent If the string user_continent came from a Text Box control there would potentially be no control over the string entered by the user The user could enter a string that generates a runtime error or in the worst case ac...

Страница 1883: ...Value Continent user_input MySqlDataReader rdr cmd ExecuteReader while rdr Read Console WriteLine rdr Name rdr HeadOfState rdr Close catch Exception ex Console WriteLine ex ToString conn Close Console WriteLine Done In this part of the tutorial you have see how to use parameters to make your code more secure 20 2 4 1 5 Working with Stored Procedures This section illustrates how to work with stored...

Страница 1884: ...tored procedure requires you to pass a parameter This can be achieved using the techniques seen in the previous section on parameters Section 20 2 4 1 4 Working with Parameters as shown in the following code snippet cmd Parameters AddWithValue con Europe The value of the parameter con could more realistically have come from a user input control but for simplicity it is set as a static string in th...

Страница 1885: ...nd Microsoft Visual Studio This tutorial was tested with MySQL Connector Net 6 0 4 and Microsoft Visual Studio 2008 Professional Edition It is recommended you use 6 0 4 or above for this tutorial 1 Create a new database in the MySQL Server using the MySQL Command Line Client program mysql or other suitable tool It does not matter what name is used for the database but record it You specify it in t...

Страница 1886: ...ors are present This can be done by selecting Build Build Solution from the main menu or pressing F6 10 ASP NET supports the concept of locally and remotely authenticated users With local authentication the user is validated using their Windows credentials when they attempt to access the web site This can be useful in an Intranet environment With remote authentication a user is prompted for their ...

Страница 1887: ...ferent provider for each feature advanced link 16 Now select the MySQLMembershipProvider and the MySQLRoleProvider radio buttons Figure 20 43 Select Membership and Role Provider 17 In Visual Studio rebuild the solution by selecting Build Rebuild Solution from the main menu 18 Check that the necessary schema has been created This can be achieved using the mysql command interpreter ...

Страница 1888: ...n their own modules for creating roles and users For simplicity the ASP NET Web Site Administration Tool will be used in this tutorial 20 In the ASP NET Web Site Administration Tool click the Security tab Now that both the Membership and Role Provider are enabled you will see links for creating roles and users Click the Create or Manage Roles link Figure 20 45 Security Tab 21 You can now enter the...

Страница 1889: ...er to one or more Roles Figure 20 46 Create User 24 Using the mysql command interpreter you can check that your database has been correctly populated with the Membership and Role data Figure 20 47 Membership and Roles Table Contents In this tutorial you have seen how to set up the MySQL Connector Net Membership and Role Providers for use in your ASP NET web application ...

Страница 1890: ... 5 Ensure that the check box Autogenerate Schema is selected so that MySQL Connector Net will create the schema in your database to store the session data correctly 6 Enter the name of your application 7 Click Finish The MySQL Website Configuration tool will now update your application s web config file with information about the connection string and default providers to be used In this case we h...

Страница 1891: ...o the Text property of the text box 4 In the Design View double click Button3 and modify the click handler as follows protected void Button3_Click object sender EventArgs e TextBox1 Text String Session SessionString This will retrieve the session string and display it in the text box 5 Now modify the Page_Load method as follows protected void Page_Load object sender EventArgs e if IsPostBack TextB...

Страница 1892: ...e tool s icon will display in the toolbar of the Solution Explorer 3 In the MySQL Website Configuration tool navigate through the tool to the Profiles page 4 Select the Use MySQL to manage my profiles check box 5 Select the Autogenerate Schema check box 6 Click the Edit button and configure a connection string for the database that will be used to store user profile information 7 Navigate to the l...

Страница 1893: ...file Name TextBox2 Text Profile Age ToString Label1 Text Profile UI Color Store Profile protected void Button1_Click object sender EventArgs e Profile Name TextBox1 Text Profile Age UInt16 Parse TextBox2 Text Clear Form protected void Button2_Click object sender EventArgs e TextBox1 Text TextBox2 Text Label1 Text Retrieve Profile protected void Button3_Click object sender EventArgs e TextBox1 Text...

Страница 1894: ...nnector Net 20 2 4 5 Tutorial Using an Entity Framework Entity as a Windows Forms Data Source In this tutorial you will learn how to create a Windows Forms Data Source from an Entity in an Entity Data Model This tutorial assumes that you have installed the World example database which can be downloaded from the MySQL Documentation page You can also find details on how to install the database on th...

Страница 1895: ...875 Figure 20 49 Add Entity Data Model 2 You will now see the Entity Data Model Wizard You will use the wizard to generate the Entity Data Model from the world example database Select the icon Generate from database Click Next ...

Страница 1896: ...u can now select the connection you made earlier to the World database If you have not already done so you can create the new connection at this time by clicking New Connection For further instructions on creating a connection to a database see Section 20 2 3 1 Making a Connection ...

Страница 1897: ...l code 5 Click Next 6 The Entity Data Model Wizard connects to the database You are then presented with a tree structure of the database From this you can select the object you would like to include in your model If you had created Views and Stored Routines these will be displayed along with any tables In this example you just need to select the tables Click Finish to create the model and exit the...

Страница 1898: ...Connector Net Tutorials 1878 Figure 20 52 Entity Data Model Wizard Screen 3 7 Visual Studio will generate the model and then display it ...

Страница 1899: ...lution to ensure that everything compiles correctly so far Adding a new Data Source You will now add a new Data Source to your project and see how it can be used to read and write to the database 1 From the Visual Studio main menu select Data Add New Data Source You will be presented with the Data Source Configuration Wizard ...

Страница 1900: ... Entity Data Source Configuration Wizard Screen 1 2 Select the Object icon Click Next 3 You will now select the Object to bind to Expand the tree In this tutorial you will select the city table Once the city table has been selected click Next ...

Страница 1901: ... Tutorials 1881 Figure 20 55 Entity Data Source Configuration Wizard Screen 2 4 The wizard will confirm that the city object is to be added Click Finish Figure 20 56 Entity Data Source Configuration Wizard Screen 3 ...

Страница 1902: ...e 20 57 Data Sources Using the Data Source in a Windows Form You will now learn how to use the Data Source in a Windows Form 1 In the Data Sources panel select the Data Source you just created and drag and drop it onto the Form Designer By default the Data Source object will be added as a Data Grid View control Note that the Data Grid View control is bound to the cityBindingSource and the Navigato...

Страница 1903: ...pulate the Data Grid View You are now ready to add code to ensure that the Data Grid View control will be populated with data from the City database table 1 Double click the form to access its code 2 Add code to instantiate the Entity Data Model s EntityContainer object and retrieve data from the database to populate the control ...

Страница 1904: ... 3 Save and rebuild the solution 4 Run the solution Ensure the grid is populated and you can navigate the database Figure 20 60 The Populated Grid Control Adding Code to Save Changes to the Database You will now add code to enable you to save changes to the database ...

Страница 1905: ...is can be achieved by the enabling of the Save button in the Navigator control and the addition of some code 1 In the Form Designer click the Save icon in the Form toolbar and ensure that its Enabled property is set to True Figure 20 61 Save Button Enabled 2 Double click the Save icon in the Form toolbar to display its code 3 You now need to add code to ensure that data is saved to the database wh...

Страница 1906: ...Section 20 2 4 5 Tutorial Using an Entity Framework Entity as a Windows Forms Data Source for instructions on downloading and installing this database Creating an ASP NET web site In this part of the tutorial you create an ASP NET web site The web site uses the World database The main web page features a drop down list from which you can select a country Data about that country s cities is then di...

Страница 1907: ...trol to a location beneath the text on your web page Figure 20 64 Drop Down List 6 From the DropDownList control s context menu ensure that the Enable AutoPostBack check box is enabled This will ensure the control s event handler is called when an item is selected The user s choice will in turn be used to populate the GridView control Figure 20 65 Enable AutoPostBack 7 From the Toolbox select the ...

Страница 1908: ... at all Adding this functionality is described in the following sections At this stage you have a web site that will build but further functionality is required The next step will be to use the Entity Framework to create a mapping from the World database into entities that you can control programmatically Creating an ADO NET Entity Data Model In this stage of the tutorial you will add an ADO NET E...

Страница 1909: ... not repopulated which would cause the user selection to be lost 3 Save the solution build it and run it You should see the list control has been populated You can select an item but as yet the grid view control does not appear At this point you have a working Drop Down List control populated by a LINQ query on your entity data model Populating a Grid View control using an entity LINQ query In the...

Страница 1910: ... In this tutorial you have seen how to create an ASP NET web site you have also seen how you can access a MySQL database using LINQ queries on an entity data model 20 2 4 7 Tutorial Using SSL with MySQL Connector Net In this tutorial you will learn how you can use MySQL Connector Net to connect to a MySQL server configured to use SSL Support for SSL client certificates was added with MySQL Connect...

Страница 1911: ...PEM file format as NET does not support this format natively You will be using test client certificates from the same server repository for the purposes of this example Convert these to PFX format first This format is also known as PKCS 12 An article describing this procedure can be found at the Citrix website From the directory server repository root mysql test std_data issue the following comman...

Страница 1912: ...he same Issuer this can be a source of confusion and result in the wrong certificate being used To alleviate this situation there is an optional Certificate Thumbprint parameter that can additionally be specified as part of the connection string As mentioned before you can double click a certificate in the Microsoft Management Console to display the certificate s details When the Certificate dialo...

Страница 1913: ...rated after each statement is executed It is possible to assign event handlers to each of these events These user provided routines are called back when the connected event occurs The following code shows how the event handlers are set up script Error new MySqlScriptErrorEventHandler script_Error script ScriptCompleted new EventHandler script_ScriptCompleted script StatementExecuted new MySqlState...

Страница 1914: ...ject is EventArgs Empty 20 2 4 8 1 Using Delimiters with MySqlScript Depending on the nature of the script you may need control of the delimiter used to separate the statements that will make up a script The most common example of this is where you have a multi statement stored routine as part of your script In this case if the default delimiter of is used you will get an error when you attempt to...

Страница 1915: ...onnecting to MySQL conn Open string sql DROP PROCEDURE IF EXISTS test_routine CREATE PROCEDURE test_routine BEGIN SELECT name FROM TestTable ORDER BY name SELECT COUNT name FROM TestTable END CALL test_routine MySqlScript script new MySqlScript conn script Query sql script Delimiter int count script Execute Console WriteLine Executed count statement s script Delimiter Console WriteLine Delimiter s...

Страница 1916: ...ve seen how to create MySQL DDL code from an Entity Framework model 20 2 5 Connector Net Programming Connector Net comprises several classes that are used to connect to the database execute queries and statements and manage query results The following are the major classes of Connector Net MySqlCommand Represents an SQL statement to execute against a MySQL database MySqlCommandBuilder Automaticall...

Страница 1917: ...using the symbol in combination with user variables see the Allow User Variables connection string option in Section 20 2 6 Connector Net Connection String Options Reference The Old Syntax connection string option has now been deprecated 20 2 5 2 1 Opening a Connection Once you have created a connection string it can be used to open a connection to the MySQL server The following code is used to cr...

Страница 1918: ...Data MySqlClient MySqlConnection myConnectionString conn Open catch MySql Data MySqlClient MySqlException ex MessageBox Show ex Message Once the connection is open it can be used by the other Connector Net classes to communicate with the MySQL server 20 2 5 2 2 Handling Connection Errors Because connecting to an external server is unpredictable it is important to add error handling to your NET app...

Страница 1919: ...f you are using multilanguage databases you must specify the character set in the connection string If you do not specify the character set the connection defaults to the latin1 charset You can specify the character set as part of the connection string for example MySqlConnection myConnection new MySqlConnection server 127 0 0 1 uid root pwd 12345 database test Charset latin1 20 2 5 2 3 Using GetS...

Страница 1920: ... to all data providers and collections specific to a particular provider Common The following collections are common to all data providers MetaDataCollections DataSourceInformation DataTypes Restrictions ReservedWords Provider specific The following are the collections currently provided by MySQL Connector Net in addition to the common collections above Databases Tables Columns Users Foreign Keys ...

Страница 1921: ...ion on the GetSchema method and schema collections can be found in the Microsoft NET documentation 20 2 5 3 Using MySqlCommand A MySqlCommand has the CommandText and CommandType properties associated with it The CommandText will be handled differently depending on the setting of CommandType CommandType can be one of 1 Text A SQL text command default 2 StoredProcedure The name of a Stored Procedure...

Страница 1922: ...ing of the results A timeout can still occur in the MySqlReader Read method after the first row is returned and does not include user processing time only IO operations The 6 2 implementation uses the underlying stream timeout facility so is more efficient in that it does not require the additional timer thread as was the case with the previous implementation Further details on this can be found i...

Страница 1923: ...ion Plugin as of Connector Net 6 4 4 and MySQL 5 5 16 5 6 10 Users who have logged in to Windows can connect from MySQL client programs to the server based on the information in their environment without specifying an additional password For background and usage information about the authentication plugin see The Windows Native Authentication Plugin The interface matches the MySql Data MySqlClient...

Страница 1924: ...nd rethrows it summary param name ex The exception with extra information on the error param protected virtual void AuthenticationFailed Exception ex summary This method is invoked when the authentication phase was successful accepted by the server Derived classes must override this if they want to be notified of such condition summary remarks The default implementation does nothing remarks protec...

Страница 1925: ...n program as follows using System using System Collections Generic using System Linq using System Text using MySql Data MySqlClient namespace AuthPluginTest class Program static void Main string args Customize the connection string as necessary MySqlConnection con new MySqlConnection server localhost database test user id myuser password mypass con Open con Close 3 Create your plugin class In this...

Страница 1926: ...Length for int i 1 i finalHash Length i finalHash i byte finalHash i firstHash i 1 return finalHash 4 Notice that the plugin implementation just overrides GetPassword and provides an implementation to encrypt the password using the 4 1 protocol We also put the following line in the GetPassword body Debug WriteLine Calling MySqlNativePasswordPlugin2 GetPassword to provide confirmation that the plug...

Страница 1927: ...y is parsed every time it is executed Prepared execution also can provide a reduction of network traffic because for each execution of the prepared statement it is necessary only to send the data for the parameters Another advantage of prepared statements is that it uses a binary protocol that makes data transfer between client and server more efficient 20 2 5 8 1 Preparing Statements in Connector...

Страница 1928: ...hat can influence the procedure logic and query conditions rather than issuing individual hardcoded SQL statements Stored procedures can be particularly useful in situations such as the following Stored procedures can act as an API or abstraction layer allowing multiple client applications to perform the same database operations The applications can be written in different languages and run on dif...

Страница 1929: ... Net To call a stored procedure using Connector Net you create a MySqlCommand object and pass the stored procedure name as the CommandText property You then set the CommandType property to CommandType StoredProcedure After the stored procedure is named you create one MySqlCommand parameter for every parameter in the stored procedure IN parameters are defined with the parameter name and the object ...

Страница 1930: ...as occurred ex Message conn Close Console WriteLine Connection closed try Console WriteLine Connecting to MySQL conn Open cmd Connection conn cmd CommandText add_emp cmd CommandType CommandType StoredProcedure cmd Parameters AddWithValue lname Jones cmd Parameters lname Direction ParameterDirection Input cmd Parameters AddWithValue fname Tom cmd Parameters fname Direction ParameterDirection Input ...

Страница 1931: ...en cmd Connection conn cmd CommandText add_emp cmd CommandType CommandType StoredProcedure cmd Parameters AddWithValue lname Jones cmd Parameters lname Direction ParameterDirection Input cmd Parameters AddWithValue fname Tom cmd Parameters fname Direction ParameterDirection Input cmd Parameters AddWithValue bday 1940 06 07 cmd Parameters bday Direction ParameterDirection Input cmd Parameters AddWi...

Страница 1932: ...rver only accepts a maximum size of 1MB from the client application If you intend to exceed 1MB in your file transfers increase this number The max_allowed_packet option can be modified using the MySQL Workbench Server Administration screen Adjust the Maximum permitted option in the Data Memory size section of the Networking tab to an appropriate setting After adjusting the value click the Apply b...

Страница 1933: ...d conn new MySql Data MySqlClient MySqlConnection cmd new MySql Data MySqlClient MySqlCommand string SQL UInt32 FileSize byte rawData FileStream fs conn ConnectionString server 127 0 0 1 uid root pwd 12345 database test try fs new FileStream c image png FileMode Open FileAccess Read FileSize fs Length rawData new byte FileSize fs Read rawData 0 FileSize fs Close conn Open SQL INSERT INTO file VALU...

Страница 1934: ...nString server 127 0 0 1 _ uid root _ pwd 12345 _ database test SQL SELECT file_name file_size file FROM file Try conn Open cmd Connection conn cmd CommandText SQL myData cmd ExecuteReader If Not myData HasRows Then Throw New Exception There are no BLOBs to save myData Read FileSize myData GetUInt32 myData GetOrdinal file_size rawData New Byte FileSize myData GetBytes myData GetOrdinal file 0 rawD...

Страница 1935: ...e BLOB into a byte array which is then written to disk using a FileStream object The GetOrdinal method of the MySqlDataReader can be used to determine the integer index of a named column Use of the GetOrdinal method prevents errors if the column order of the SELECT query is changed 20 2 5 11 Using the Connector Net Interceptor Classes An interceptor is a software design pattern that provides a tra...

Страница 1936: ... to do some one time initialization Each exception interceptor has 2 methods public abstract Exception InterceptException Exception exception MySqlConnection connection public virtual void Init MySqlConnection connection The connection passed to Init is the connection that is attached to this interceptor Each interceptor is required to override InterceptException and return an exception It can ret...

Страница 1937: ... time types specify a value from 1 to 6 when creating the table column for example TIME 3 or DATETIME 6 representing the number of digits of precision after the decimal point Specifying a precision of 0 leaves the fractional part out entirely In your C or Visual Basic code refer to the Millisecond member to retrieve the fractional second value from the MySqlDateTime object returned by the GetMySql...

Страница 1938: ...ted in the standard MySQL format for example 2005 02 23 08 50 25 This differs from the ToString behavior of the NET DateTime class 3 The MySqlDateTime class supports NULL dates while the NET DateTime class does not This can cause errors when trying to convert a MySQLDateTime to a DateTime if you do not check for NULL first Because of the known issues the best recommendation is still to use only va...

Страница 1939: ...a 43 Nurse Fred 21 IT Specialist Simon 45 Hairy Biker Note that with this test file the first three lines will need to be ignored as they do not contain table data This can be achieved using the NumberOfLinesToSkip property This file can then be loaded and used to populate the Career table in the test database using System using System Text using MySql Data using MySql Data MySqlClient namespace C...

Страница 1940: ...ritten While a switch defines the level of information that will be written to all listeners a filter can be applied on a per listener basis giving finer grained control of trace information To use tracing a TraceSource object first needs to be created To create a TraceSource object in MySQL Connector Net you would use code similar to the following TraceSource ts new TraceSource mysql To enable tr...

Страница 1941: ...e can have a value of Verbose Information Warning Error and Critical Using the TraceData method you can pass any object for example an exception object instead of a message To ensure than these generated trace messages gets flushed from the trace source buffers to listeners invoke the Flush method When you are finished using a trace source call the Close method The Close method first calls Flush t...

Страница 1942: ... args string connStr server localhost user root database world port 3306 password logging true MySqlConnection conn new MySqlConnection connStr try Console WriteLine Connecting to MySQL conn Open string sql SELECT Name HeadOfState FROM Country WHERE Continent Oceania MySqlCommand cmd new MySqlCommand sql conn MySqlDataReader rdr cmd ExecuteReader while rdr Read Console WriteLine rdr 0 rdr 1 rdr Cl...

Страница 1943: ...onClosed 3 QueryOpened mysql server thread id query text 4 ResultOpened field count affected rows 1 if select inserted id 1 if select 5 ResultClosed total rows read rows skipped size of resultset in bytes 6 QueryClosed 7 StatementPrepared prepared sql statement id 8 StatementExecuted statement id mysql server thread id 9 StatementClosed statement id 10 NonQuery varies 11 UsageAdvisorWarning usage ...

Страница 1944: ...s Object args The first three parameters are used in the standard as defined by Microsoft The last three parameters contain MySQL specific trace information Each of these parameters is now discussed in more detail int id This is a MySQL specific identifier It identifies the MySQL event type that has occurred resulting in a trace message being generated This value is defined by the MySqlTraceEventT...

Страница 1945: ...eturn incorrect metadata about one or more columns More specifically the server will sometimes report that a column is binary when it is not and vice versa In these situations it becomes practically impossible for the connector to be able to correctly identify the correct metadata Some examples of situations that may return incorrect metadata are Execution of SHOW PROCESSLIST Some of the columns w...

Страница 1946: ...velopers to perform reporting and document generation In this section we will show how to use Crystal Reports XI with MySQL and Connector Net 20 2 5 17 1 Creating a Data Source When creating a report in Crystal Reports there are two options for accessing the MySQL data while designing your report The first option is to use Connector ODBC as an ADO data source when designing your report You will be...

Страница 1947: ... resulting XML file can be used as an ADO NET XML datasource when designing your report If you choose to design your reports using Connector ODBC it can be downloaded from dev mysql com 20 2 5 17 2 Creating the Report For most purposes the Standard Report wizard helps with the initial creation of a report To start the wizard open Crystal Reports and choose the New Standard Report option from the F...

Страница 1948: ...opulation country continent _ FROM country city ORDER BY country continent country name cmd Connection conn myAdapter SelectCommand cmd myAdapter Fill myData myReport Load world_report rpt myReport SetDataSource myData myViewer ReportSource myReport Catch ex As Exception MessageBox Show ex Message Report could not be created MessageBoxButtons OK MessageBoxIcon Error End Try C Example using Crystal...

Страница 1949: ...qlCommand object These SELECT statements are based on the SQL query shown in Crystal Reports in the Database menu s Show SQL Query option Assume the following query SELECT country Name country Continent country Population city Name city Population FROM world country country LEFT OUTER JOIN world city city ON country Code city CountryCod ORDER BY country Continent country Name city Name This query ...

Страница 1950: ...ta Tables 1 myViewer ReportSource myReport catch MySql Data MySqlClient MySqlException ex MessageBox Show ex Message Report could not be created MessageBoxButtons OK MessageBoxIcon Error It is important to order the SELECT queries in alphabetic order as this is the order the report will expect its source tables to be in One SetDataSource statement is needed for each table in the report This approa...

Страница 1951: ...httpHandlers membership providers add name AspNetSqlMembershipProvider type System Web Security SqlMembershipProvider System Web Ve add name MySQLMembershipProvider type MySql Web Security MySQLMembershipProvider MySql Web Versio providers membership profile providers add name AspNetSqlProfileProvider connectionStringName LocalSqlServer applicationName type Sy add name MySQLProfileProvider type My...

Страница 1952: ...tring in your web config file You do this by first removing the dummy connection string and then adding in the proper one as shown in the following example connectionStrings remove name LocalMySqlServer add name LocalMySqlServer connectionString server xxx uid xxx pwd xxx database xxx connectionStrings Note the database to connect to must be specified Rather than manually editing configuration fil...

Страница 1953: ... and Above Partial Trust Requires Socket Permissions Starting with these versions Connector Net can be used under partial trust hosting that has been modified to allow the use of sockets for communication By default partial trust does not include SocketPermission Connector Net uses sockets to talk with the MySQL server so the hosting provider must create a new trust level that is an exact clone of...

Страница 1954: ...ce in your application for the MySql Data MySqlClient library 8 Edit your web config file so that your application runs using a Medium trust level system web trust level Medium system web 9 Add the MySql Data MySqlClient namespace to your server code page 10 Define the connection string in slightly different ways depending on the Connector Net version Only for 6 6 4 or later To use the connections...

Страница 1955: ...he web configuration file as follows 1 Open the medium trust policy web configuration file which should be under this folder windir Microsoft NET Framework version CONFIG web_mediumtrust config Use Framework64 in the path instead of Framework if you are using a 64 bit installation of the framework 2 Locate the SecurityClasses tag SecurityClass Name SocketPermission Description System Net SocketPer...

Страница 1956: ... used in a medium trust environment BlobAsUTF8ExcludePattern null A POSIX style regular expression that matches the names of BLOB columns that do not contain UTF 8 character data See Section 20 2 5 16 Character Set Considerations for Connector Net for usage details BlobAsUTF8IncludePattern null A POSIX style regular expression that matches the names of BLOB columns containing UTF 8 character data ...

Страница 1957: ...andTimeout 30 Sets the default value of the command timeout to be used This does not supercede the individual command timeout property on an individual command object If you set the command timeout property that will be used This option was added in Connector Net 5 1 4 Default Table Cache Age DefaultTableCacheAge 60 Specifies how long a TableDirect result should be cached in seconds For usage info...

Страница 1958: ...atements If you use server side prepare statements set this option to false This option was added in Connector Net 5 0 3 and Connector Net 1 0 9 includesecurityasserts include security asserts false Must be set to true when using the MySQLClientPermissions class in a partial trust environment with the library installed in the GAC of the hosting environment This requirement is new for partial trust...

Страница 1959: ... the name of a named pipe the MySqlConnection attempts to connect to MySQL on that named pipe This setting only applies to the Windows platform Port 3306 The port MySQL is using to listen for connections This value is ignored if Unix socket is used Procedure Cache Size ProcedureCacheSize procedure cache procedurecache 25 Sets the size of the stored procedure cache By default Connector Net stores t...

Страница 1960: ... INT See Section 11 1 1 Numeric Type Overview for a further explanation of the TINYINT and BOOL data types Use Affected Rows UseAffectedRows false When true the connection reports changed rows instead of found rows This option was added in Connector Net version 5 2 6 Use Procedure Bodies UseProcedureBodies procedure bodies true When set to true the default value MySQL Connector Net expects the bod...

Страница 1961: ... performance counters should be updated during execution Connection Pooling Options The following table lists the valid names for options related to connection pooling within the ConnectionString For more information about connection pooling see Section 20 2 5 4 Using Connector Net with Connection Pooling Table 20 21 Connector Net Connection String Options Connection Pooling Name Default Descripti...

Страница 1962: ...s a means of enhancing or replacing SQL commands through the connection string rather than recompiling BaseExceptionInterceptor Provides a means of enabling and disabling exception handling through the connection string rather than recompiling MySqlClientPermission Derived from the NET DBDataPermission class For usage information see Section 20 2 5 19 Working with Partial Trust Medium Trust MySqlC...

Страница 1963: ...a MySqlClientHierarchy See Also MySql Data MySqlClient Namespace 20 2 7 1 2 BaseCommandInterceptor The BaseCommandInterceptor class has these methods that you can override public virtual bool ExecuteScalar string sql ref object returnValue public virtual bool ExecuteNonQuery string sql ref int returnValue public virtual bool ExecuteReader string sql CommandBehavior behavior ref MySqlDataReader ret...

Страница 1964: ...f this type see MySqlCommand Members Syntax Visual Basic NotInheritable Public Class MySqlCommand_ Inherits Component_ Implements IDbCommand ICloneable Syntax C public sealed class MySqlCommand Component IDbCommand ICloneable Thread Safety Public static Shared in Visual Basic members of this type are safe for multithreaded operations Instance members are not guaranteed to be thread safe Requiremen...

Страница 1965: ...s suitable for use in hashing algorithms and data structures like a hash table GetLifetimeService inherited from MarshalByRefObject Retrieves the current lifetime service object that controls the lifetime policy for this instance GetType inherited from Object Gets the Type of the current instance InitializeLifetimeService inherited from MarshalByRefObject Obtains a lifetime service object to contr...

Страница 1966: ...ructor String Syntax Visual Basic Overloads Public Sub New _ ByVal cmdText As String _ Syntax C public MySqlCommand stringcmdText See Also MySqlCommand Class MySql Data MySqlClient Namespace MySqlCommand Constructor Overload List 20 2 7 1 4 1 1 3 MySqlCommand Constructor Syntax Visual Basic Overloads Public Sub New _ ByVal cmdText As String _ ByVal connection As MySqlConnection _ Syntax C public M...

Страница 1967: ...7 1 4 1 1 3 1 1 MySqlConnection Members MySqlConnection overview Public Instance Constructors MySqlConnection Overloaded Initializes a new instance of the MySqlConnection class Public Instance Properties ConnectionString ConnectionTimeout Container inherited from Component Gets the IContainer that contains the Component Database DataSource Gets the name of the MySQL server to which to connect Serv...

Страница 1968: ...t instance InitializeLifetimeService inherited from MarshalByRefObject Obtains a lifetime service object to control the lifetime policy for this instance Open Ping Ping ToString inherited from Component Returns a String containing the name of the Component if any This method should not be overridden Public Instance Events Disposed inherited from Component Adds an event handler to listen to the Dis...

Страница 1969: ...0 2 7 1 4 1 1 3 1 1 2 ConnectionString Property Syntax Visual Basic NotOverridable Public Property ConnectionString As String _ _ Implements IDbConnection ConnectionString Syntax C public string ConnectionString get set Implements IDbConnection ConnectionString See Also MySqlConnection Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 1 3 1 1 3 ConnectionTimeout Property Syntax Visual Basic NotO...

Страница 1970: ...lic ReadOnly Property DataSource As String Syntax C public string DataSource get See Also MySqlConnection Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 1 3 1 1 6 ServerThread Property Returns the ID of the server thread this connection is executing on Syntax Visual Basic Public ReadOnly Property ServerThread As Integer Syntax C public int ServerThread get See Also MySqlConnection Class MySql...

Страница 1971: ...ax C public bool UseCompression get See Also MySqlConnection Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 1 3 1 1 10 BeginTransaction Method Overload List public MySqlTransaction BeginTransaction public MySqlTransaction BeginTransaction IsolationLevel See Also MySqlConnection Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 1 3 1 1 10 1 MySqlConnection BeginTransaction Method Syntax Visu...

Страница 1972: ...saction or a null reference Nothing in Visual Basic if the transaction is no longer valid IsolationLevel Specifies the IsolationLevel for this transaction Public Instance Methods Commit Equals inherited from Object Determines whether the specified Object is equal to the current Object GetHashCode inherited from Object Serves as a hash function for a particular type GetHashCode is suitable for use ...

Страница 1973: ... Specifies the IsolationLevel for this transaction Syntax Visual Basic NotOverridable Public ReadOnly Property IsolationLevel As IsolationLevel _ _ Implements IDbTransaction IsolationLevel Syntax C public System Data IsolationLevel IsolationLevel get Property Value The IsolationLevel for this transaction The default is ReadCommitted Implements IDbTransaction IsolationLevel Remarks Parallel transac...

Страница 1974: ... Syntax Visual Basic Overloads Public Function BeginTransaction _ ByVal iso As IsolationLevel _ As MySqlTransaction Syntax C public MySqlTransaction BeginTransaction IsolationLeveliso See Also MySqlConnection Class MySql Data MySqlClient Namespace MySqlConnection BeginTransaction Overload List 20 2 7 1 4 1 1 3 1 1 11 MySqlConnection ChangeDatabase Method Syntax Visual Basic NotOverridable Public S...

Страница 1975: ...tax Visual Basic Public Function CreateCommand As MySqlCommand Syntax C public MySqlCommand CreateCommand See Also MySqlConnection Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 1 3 1 1 14 MySqlConnection Open Method Syntax Visual Basic NotOverridable Public Sub Open _ _ Implements IDbConnection Open Syntax C public void Open Implements IDbConnection Open See Also MySqlConnection Class MySql ...

Страница 1976: ...ntax Visual Basic Public Delegate Sub MySqlInfoMessageEventHandler _ ByVal sender As Object _ ByVal args As MySqlInfoMessageEventArgs _ Syntax C public delegate void MySqlInfoMessageEventHandler objectsender MySqlInfoMessageEventArgsargs Requirements Namespace MySql Data MySqlClient Assembly MySql Data in MySql Data dll See Also MySql Data MySqlClient Namespace 20 2 7 1 4 1 1 3 1 1 16 1 1 MySqlInf...

Страница 1977: ...o the current Object GetHashCode inherited from Object Serves as a hash function for a particular type GetHashCode is suitable for use in hashing algorithms and data structures like a hash table GetType inherited from Object Gets the Type of the current instance ToString inherited from Object Returns a String that represents the current Object Protected Instance Methods Finalize inherited from Obj...

Страница 1978: ... members of this type see MySqlError Members Syntax Visual Basic Public Class MySqlError Syntax C public class MySqlError Thread Safety Public static Shared in Visual Basic members of this type are safe for multithreaded operations Instance members are not guaranteed to be thread safe Requirements Namespace MySql Data MySqlClient Assembly MySql Data in MySql Data dll See Also MySqlError Members My...

Страница 1979: ...to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection MemberwiseClone inherited from Object Creates a shallow copy of the current Object See Also MySqlError Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 1 3 1 1 16 1 1 1 2 1 1 1 MySqlError Constructor Syntax Visual Basic Public Sub New _ ByVal level As String _ ByVal code As Int...

Страница 1980: ...ing Syntax C public string Message get See Also MySqlError Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 1 3 1 1 17 MySqlConnection StateChange Event Syntax Visual Basic Public Event StateChange As StateChangeEventHandler Syntax C public event StateChangeEventHandler StateChange See Also MySqlConnection Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 1 4 MySqlCommand Constructor Syntax V...

Страница 1981: ...mespace 20 2 7 1 4 1 3 CommandTimeout Property Syntax Visual Basic NotOverridable Public Property CommandTimeout As Integer _ _ Implements IDbCommand CommandTimeout Syntax C public int CommandTimeout get set Implements IDbCommand CommandTimeout See Also MySqlCommand Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 4 CommandType Property Syntax Visual Basic NotOverridable Public Property Command...

Страница 1982: ...ters get See Also MySqlCommand Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 7 1 MySqlParameterCollection Class Represents a collection of parameters relevant to a MySqlCommand as well as their respective mappings to columns in a DataSet This class cannot be inherited For a list of all members of this type see MySqlParameterCollection Members Syntax Visual Basic NotInheritable Public Class M...

Страница 1983: ...arameter objects from the MySqlParameterCollection to the specified array CreateObjRef inherited from MarshalByRefObject Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object Equals inherited from Object Determines whether the specified Object is equal to the current Object GetHashCode inherited from Object Serves as a ha...

Страница 1984: ...MySqlClient Namespace 20 2 7 1 4 1 7 1 1 2 Count Property Gets the number of MySqlParameter objects in the collection Syntax Visual Basic NotOverridable Public ReadOnly Property Count As Integer _ _ Implements ICollection Count Syntax C public int Count get Implements ICollection Count See Also MySqlParameterCollection Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 7 1 1 3 Item Property Gets ...

Страница 1985: ...ata MySqlClient Assembly MySql Data in MySql Data dll See Also MySqlParameter Members MySql Data MySqlClient Namespace 20 2 7 1 4 1 7 1 1 3 1 1 MySqlParameter Members MySqlParameter overview Public Instance Constructors MySqlParameter Overloaded Initializes a new instance of the MySqlParameter class Public Instance Properties DbType Gets or sets the DbType of the parameter Direction Gets or sets a...

Страница 1986: ...from Object Gets the Type of the current instance InitializeLifetimeService inherited from MarshalByRefObject Obtains a lifetime service object to control the lifetime policy for this instance ToString Overridden Gets a string containing the ParameterName See Also MySqlParameter Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 7 1 1 3 1 1 1 MySqlParameter Constructor Initializes a new instance ...

Страница 1987: ...MySqlParameter See Also MySqlParameter Class MySql Data MySqlClient Namespace MySqlParameter Constructor Overload List 20 2 7 1 4 1 7 1 1 3 1 1 1 2 MySqlParameter Constructor Initializes a new instance of the MySqlParameter class with the parameter name and the data type Syntax Visual Basic Overloads Public Sub New _ ByVal parameterName As String _ ByVal dbType As MySqlDbType _ Syntax C public MyS...

Страница 1988: ...at default is 4 digit The allowable values are 1901 to 2155 0000 in the 4 digit year format and 1970 2069 if you use the 2 digit format 70 69 TinyBlob A BLOB column with a maximum length of 255 2 8 1 characters Blob A BLOB column with a maximum length of 65535 2 16 1 characters MediumBlob A BLOB column with a maximum length of 16777215 2 24 1 characters LongBlob A BLOB column with a maximum length...

Страница 1989: ...racters Enum An enumeration A string object that can have only one value chosen from the list of values value1 value2 NULL or the special error value An ENUM can have a maximum of 65535 distinct values Geometry Bit Bit field data type TinyText A nonbinary string column supporting a maximum length of 255 2 8 1 characters Text A nonbinary string column supporting a maximum length of 65535 2 16 1 cha...

Страница 1990: ...e size of the parameter a ParameterDirection the precision of the parameter the scale of the parameter the source column a DataRowVersion to use and the value of the parameter Syntax Visual Basic Overloads Public Sub New _ ByVal parameterName As String _ ByVal dbType As MySqlDbType _ ByVal size As Integer _ ByVal direction As ParameterDirection _ ByVal isNullable As Boolean _ ByVal precision As By...

Страница 1991: ...lParameter Class MySql Data MySqlClient Namespace MySqlParameter Constructor Overload List 20 2 7 1 4 1 7 1 1 3 1 1 1 4 1 Value Property Gets or sets the value of the parameter Syntax Visual Basic NotOverridable Public Property Value As Object _ _ Implements IDataParameter Value Syntax C public object Value get set Implements IDataParameter Value See Also MySqlParameter Class MySql Data MySqlClien...

Страница 1992: ...meter class with the parameter name and a value of the new MySqlParameter Syntax Visual Basic Overloads Public Sub New _ ByVal parameterName As String _ ByVal value As Object _ Syntax C public MySqlParameter stringparameterName objectvalue Parameters parameterName The name of the parameter to map value An Object that is the value of the MySqlParameter See Also MySqlParameter Class MySql Data MySql...

Страница 1993: ...irection Syntax C public System Data ParameterDirection Direction get set Implements IDataParameter Direction See Also MySqlParameter Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 7 1 1 3 1 1 4 IsNullable Property Gets or sets a value indicating whether the parameter accepts null values Syntax Visual Basic NotOverridable Public Property IsNullable As Boolean _ _ Implements IDataParameter IsN...

Страница 1994: ...ParameterName As String _ _ Implements IDataParameter ParameterName Syntax C public string ParameterName get set Implements IDataParameter ParameterName See Also MySqlParameter Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 7 1 1 3 1 1 8 Precision Property Gets or sets the maximum number of digits used to represent the Value property Syntax Visual Basic NotOverridable Public Property Precisio...

Страница 1995: ...ter Size Syntax C public int Size get set Implements IDbDataParameter Size See Also MySqlParameter Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 7 1 1 3 1 1 11 SourceColumn Property Gets or sets the name of the source column that is mapped to the DataSetand used for loading or returning the Value Syntax Visual Basic NotOverridable Public Property SourceColumn As String _ _ Implements IDataPa...

Страница 1996: ...String As String Syntax C public override string ToString Return Value See Also MySqlParameter Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 7 1 1 3 2 Item Property Int32 Gets the MySqlParameter at the specified index Syntax Visual Basic Overloads Public Default Property Item _ ByVal index As Integer _ As MySqlParameter Syntax C public MySqlParameter this intindex get set See Also MySqlParam...

Страница 1997: ...SqlDbType Adds a MySqlParameter to the MySqlParameterCollection with the parameter name the data type and the column length public MySqlParameter Add string MySqlDbType int Adds a MySqlParameter to the MySqlParameterCollection with the parameter name the data type the column length and the source column name public MySqlParameter Add string MySqlDbType int string Adds a MySqlParameter to the MySql...

Страница 1998: ...As Integer _ _ Implements IList Add Syntax C public int Add objectvalue Parameters value The MySqlParameter to add to the collection Return Value The index of the new MySqlParameter object Implements IList Add See Also MySqlParameterCollection Class MySql Data MySqlClient Namespace MySqlParameterCollection Add Overload List 20 2 7 1 4 1 7 1 1 4 3 MySqlParameterCollection Add Method Adds a MySqlPar...

Страница 1999: ...ize As Integer _ As MySqlParameter Syntax C public MySqlParameter Add stringparameterName MySqlDbTypedbType intsize Parameters parameterName The name of the parameter dbType One of the MySqlDbType values size The length of the column Return Value The newly added MySqlParameter object See Also MySqlParameterCollection Class MySql Data MySqlClient Namespace MySqlParameterCollection Add Overload List...

Страница 2000: ...eterCollection Add Method Adds a MySqlParameter to the MySqlParameterCollection given the specified parameter name and value Syntax Visual Basic Overloads Public Function Add _ ByVal parameterName As String _ ByVal value As Object _ As MySqlParameter Syntax C public MySqlParameter Add stringparameterName objectvalue Parameters parameterName The name of the parameter value The Value of the MySqlPar...

Страница 2001: ...ting whether a MySqlParameter with the specified parameter name exists in the collection public bool Contains string See Also MySqlParameterCollection Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 7 1 1 6 1 MySqlParameterCollection Contains Method Gets a value indicating whether a MySqlParameter exists in the collection Syntax Visual Basic NotOverridable Overloads Public Function Contains _ ...

Страница 2002: ...ublic bool Contains stringname Parameters name The name of the MySqlParameter object to find Return Value true if the collection contains the parameter otherwise false Implements IDataParameterCollection Contains See Also MySqlParameterCollection Class MySql Data MySqlClient Namespace MySqlParameterCollection Contains Overload List 20 2 7 1 4 1 7 1 1 7 MySqlParameterCollection CopyTo Method Copies...

Страница 2003: ...7 1 1 8 1 MySqlParameterCollection IndexOf Method Gets the location of a MySqlParameter in the collection Syntax Visual Basic NotOverridable Overloads Public Function IndexOf _ ByVal value As Object _ As Integer _ _ Implements IList IndexOf Syntax C public int IndexOf objectvalue Parameters value The MySqlParameter object to locate Return Value The zero based location of the MySqlParameter in the ...

Страница 2004: ...llection Class MySql Data MySqlClient Namespace MySqlParameterCollection IndexOf Overload List 20 2 7 1 4 1 7 1 1 9 MySqlParameterCollection Insert Method Inserts a MySqlParameter into the collection at the specified index Syntax Visual Basic NotOverridable Public Sub Insert _ ByVal index As Integer _ ByVal value As Object _ _ _ Implements IList Insert Syntax C public void Insert intindex objectva...

Страница 2005: ...rameter from the collection using a specific index public void RemoveAt int Removes the specified MySqlParameter from the collection using the parameter name public void RemoveAt string See Also MySqlParameterCollection Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 7 1 1 11 1 MySqlParameterCollection RemoveAt Method Removes the specified MySqlParameter from the collection using a specific in...

Страница 2006: ...arameters name The name of the MySqlParameter object to retrieve Implements IDataParameterCollection RemoveAt See Also MySqlParameterCollection Class MySql Data MySqlClient Namespace MySqlParameterCollection RemoveAt Overload List 20 2 7 1 4 1 8 Transaction Property Syntax Visual Basic Public Property Transaction As MySqlTransaction Syntax C public MySqlTransaction Transaction get set See Also MyS...

Страница 2007: ... not supported on any version of MySQL Exceptions Exception Type Condition NotSupportedException This operation is not supported See Also MySqlCommand Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 11 MySqlCommand CreateParameter Method Creates a new instance of a MySqlParameter object Syntax Visual Basic Public Function CreateParameter As MySqlParameter Syntax C public MySqlParameter CreateP...

Страница 2008: ...tax C public MySqlDataReader ExecuteReader See Also MySqlCommand Class MySql Data MySqlClient Namespace MySqlCommand ExecuteReader Overload List 20 2 7 1 4 1 13 1 1 MySqlDataReader Class Provides a means of reading a forward only stream of rows from a MySQL database This class cannot be inherited For a list of all members of this type see MySqlDataReader Members Syntax Visual Basic NotInheritable ...

Страница 2009: ... inserted or deleted by execution of the SQL statement Public Instance Methods Close Closes the MySqlDataReader object CreateObjRef inherited from MarshalByRefObject Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object Equals inherited from Object Determines whether the specified Object is equal to the current Object Get...

Страница 2010: ...ue Gets the value of the specified column in its native format GetValues Gets all attribute columns in the collection for the current row InitializeLifetimeService inherited from MarshalByRefObject Obtains a lifetime service object to control the lifetime policy for this instance IsDBNull Gets a value indicating whether the column contains non existent or missing values NextResult Advances the dat...

Страница 2011: ...cord FieldCount See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 3 HasRows Property Gets a value indicating whether the MySqlDataReader contains one or more rows Syntax Visual Basic Public ReadOnly Property HasRows As Boolean Syntax C public bool HasRows get See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 4 IsClosed Propert...

Страница 2012: ...ss MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 5 1 Item Property Int32 Overloaded Gets the value of a column in its native format In C this property is the indexer for the MySqlDataReader class Syntax Visual Basic NotOverridable Overloads Public Default ReadOnly Property Item _ ByVal i As Integer _ _ _ Implements IDataRecord Item As Object _ _ Implements IDataRecord Item Syntax C public...

Страница 2013: ...able Public ReadOnly Property RecordsAffected As Integer _ _ Implements IDataReader RecordsAffected Syntax C public int RecordsAffected get Implements IDataReader RecordsAffected See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 7 MySqlDataReader Close Method Closes the MySqlDataReader object Syntax Visual Basic NotOverridable Public Sub Close _ _ Implements IDa...

Страница 2014: ...MySqlDataReader GetByte Method Gets the value of the specified column as a byte Syntax Visual Basic NotOverridable Public Function GetByte _ ByVal i As Integer _ As Byte _ _ Implements IDataRecord GetByte Syntax C public byte GetByte inti Parameters i Return Value Implements IDataRecord GetByte See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 10 MySqlDataReader...

Страница 2015: ...n the read operation buffer The buffer into which to read the stream of bytes bufferIndex The index for buffer to begin the read operation length The maximum length to copy into the buffer Return Value The actual number of bytes read Implements IDataRecord GetBytes See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 11 MySqlDataReader GetChar Method Gets the value...

Страница 2016: ...fieldOffset As Long _ ByVal buffer As Char _ ByVal bufferoffset As Integer _ ByVal length As Integer _ As Long _ _ Implements IDataRecord GetChars Syntax C public long GetChars inti longfieldOffset char buffer intbufferoffset intlength Parameters i fieldOffset buffer bufferoffset length Return Value Implements IDataRecord GetChars See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 ...

Страница 2017: ...dable Public Function GetDateTime _ ByVal index As Integer _ As Date _ _ Implements IDataRecord GetDateTime Syntax C public DateTime GetDateTime intindex Implements IDataRecord GetDateTime See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 15 MySqlDataReader GetDecimal Method Syntax Visual Basic NotOverridable Public Function GetDecimal _ ByVal index As Integer _...

Страница 2018: ... Namespace 20 2 7 1 4 1 13 1 1 1 17 MySqlDataReader GetFieldType Method Gets the Type that is the data type of the object Syntax Visual Basic NotOverridable Public Function GetFieldType _ ByVal i As Integer _ As Type _ _ Implements IDataRecord GetFieldType Syntax C public Type GetFieldType inti Parameters i Return Value Implements IDataRecord GetFieldType See Also MySqlDataReader Class MySql Data ...

Страница 2019: ...ublic Guid GetGuid intindex Implements IDataRecord GetGuid See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 20 MySqlDataReader GetInt16 Method Syntax Visual Basic NotOverridable Public Function GetInt16 _ ByVal index As Integer _ As Short _ _ Implements IDataRecord GetInt16 Syntax C public short GetInt16 intindex Implements IDataRecord GetInt16 See Also MySqlDa...

Страница 2020: ...er _ As Long _ _ Implements IDataRecord GetInt64 Syntax C public long GetInt64 intindex Implements IDataRecord GetInt64 See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 23 MySqlDataReader GetMySqlDateTime Method Syntax Visual Basic Public Function GetMySqlDateTime _ ByVal index As Integer _ As MySqlDateTime Syntax C public MySqlDateTime GetMySqlDateTime intinde...

Страница 2021: ...umn ordinal given the name of the column Syntax Visual Basic NotOverridable Public Function GetOrdinal _ ByVal name As String _ As Integer _ _ Implements IDataRecord GetOrdinal Syntax C public int GetOrdinal stringname Parameters name Return Value Implements IDataRecord GetOrdinal See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 26 MySqlDataReader GetSchemaTabl...

Страница 2022: ... _ _ Implements IDataRecord GetString Syntax C public string GetString intindex Implements IDataRecord GetString See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 28 MySqlDataReader GetTimeSpan Method Syntax Visual Basic Public Function GetTimeSpan _ ByVal index As Integer _ As TimeSpan Syntax C public TimeSpan GetTimeSpan intindex See Also MySqlDataReader Class...

Страница 2023: ... Namespace 20 2 7 1 4 1 13 1 1 1 31 MySqlDataReader GetUInt64 Method Syntax Visual Basic Public Function GetUInt64 _ ByVal index As Integer _ As UInt64 Syntax C public ulong GetUInt64 intindex See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 32 MySqlDataReader GetValue Method Gets the value of the specified column in its native format Syntax Visual Basic NotOve...

Страница 2024: ... _ _ Implements IDataRecord GetValues Syntax C public int GetValues object values Parameters values Return Value Implements IDataRecord GetValues See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 34 MySqlDataReader IsDBNull Method Gets a value indicating whether the column contains non existent or missing values Syntax Visual Basic NotOverridable Public Function...

Страница 2025: ...er NextResult See Also MySqlDataReader Class MySql Data MySqlClient Namespace 20 2 7 1 4 1 13 1 1 1 36 MySqlDataReader Read Method Advances the MySqlDataReader to the next record Syntax Visual Basic NotOverridable Public Function Read As Boolean _ _ Implements IDataReader Read Syntax C public bool Read Return Value Implements IDataReader Read See Also MySqlDataReader Class MySql Data MySqlClient N...

Страница 2026: ...mand Prepare Method Syntax Visual Basic NotOverridable Public Sub Prepare _ _ Implements IDbCommand Prepare Syntax C public void Prepare Implements IDbCommand Prepare See Also MySqlCommand Class MySql Data MySqlClient Namespace 20 2 7 1 5 MySqlCommandBuilder Class For a list of all members of this type see MySqlCommandBuilder Members Syntax Visual Basic NotInheritable Public Class MySqlCommandBuil...

Страница 2027: ...nherited from Component Gets or sets the ISite of the Component Public Instance Methods CreateObjRef inherited from MarshalByRefObject Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object Dispose inherited from Component Releases all resources used by the Component Equals inherited from Object Determines whether the spec...

Страница 2028: ...the specified MySqlCommand object This method is not currently supported since stored procedures are not available in MySql public static void DeriveParameters MySqlCommand public static void DeriveParameters MySqlCommand bool See Also MySqlCommandBuilder Class MySql Data MySqlClient Namespace 20 2 7 1 5 1 1 1 MySqlCommandBuilder DeriveParameters Method Retrieves parameter information from the sto...

Страница 2029: ...pace MySqlCommandBuilder DeriveParameters Overload List 20 2 7 1 5 1 2 MySqlCommandBuilder Constructor Initializes a new instance of the MySqlCommandBuilder class Overload List Initializes a new instance of the MySqlCommandBuilder class public MySqlCommandBuilder public MySqlCommandBuilder MySqlDataAdapter public MySqlCommandBuilder MySqlDataAdapter bool public MySqlCommandBuilder bool See Also My...

Страница 2030: ...d class MySqlDataAdapter DbDataAdapter Thread Safety Public static Shared in Visual Basic members of this type are safe for multithreaded operations Instance members are not guaranteed to be thread safe Requirements Namespace MySql Data MySqlClient Assembly MySql Data in MySql Data dll See Also MySqlDataAdapter Members MySql Data MySqlClient Namespace 20 2 7 1 5 1 2 2 1 1 MySqlDataAdapter Members ...

Страница 2031: ...master mapping between a source table and a DataTable UpdateBatchSize inherited from DbDataAdapter Gets or sets a value that enables or disables batch processing support and specifies the number of commands that can be executed in a batch UpdateCommand Overloaded Public Instance Methods CreateObjRef inherited from MarshalByRefObject Creates an object that contains all the relevant information requ...

Страница 2032: ...ed updated or deleted row in the specified DataSet Public Instance Events Disposed inherited from Component Adds an event handler to listen to the Disposed event on the component FillError inherited from DataAdapter Returned when an error occurs during a fill operation RowUpdated Occurs during Update after a command is executed against the data source The attempt to update is made so the event fir...

Страница 2033: ...lCommand _ Syntax C public MySqlDataAdapter MySqlCommandselectCommand See Also MySqlDataAdapter Class MySql Data MySqlClient Namespace MySqlDataAdapter Constructor Overload List 20 2 7 1 5 1 2 2 1 1 1 3 MySqlDataAdapter Constructor Syntax Visual Basic Overloads Public Sub New _ ByVal selectCommandText As String _ ByVal connection As MySqlConnection _ Syntax C public MySqlDataAdapter stringselectCo...

Страница 2034: ...e 20 2 7 1 5 1 2 2 1 1 3 InsertCommand Property Syntax Visual Basic Overloads Public Property InsertCommand As MySqlCommand Syntax C new public MySqlCommand InsertCommand get set See Also MySqlDataAdapter Class MySql Data MySqlClient Namespace 20 2 7 1 5 1 2 2 1 1 4 SelectCommand Property Syntax Visual Basic Overloads Public Property SelectCommand As MySqlCommand Syntax C new public MySqlCommand S...

Страница 2035: ...Errors Gets any errors generated by the NET Framework data provider when the Commandwas executed RecordsAffected Gets the number of rows changed inserted or deleted by execution of the SQL statement Row Gets the DataRowsent through an Update RowCount Gets the number of rows processed in a batch of updated records StatementType Gets the type of SQL statement executed Status Gets the UpdateStatus of...

Страница 2036: ...not guaranteed to be thread safe Requirements Namespace MySql Data MySqlClient Assembly MySql Data in MySql Data dll See Also MySqlRowUpdatedEventArgs Members MySql Data MySqlClient Namespace 20 2 7 1 5 1 2 2 1 1 6 1 1 1 MySqlRowUpdatedEventArgs Members MySqlRowUpdatedEventArgs overview Public Instance Constructors MySqlRowUpdatedEventArgs Constructor Initializes a new instance of the MySqlRowUpda...

Страница 2037: ... structures like a hash table GetType inherited from Object Gets the Type of the current instance ToString inherited from Object Returns a String that represents the current Object See Also MySqlRowUpdatedEventArgs Class MySql Data MySqlClient Namespace 20 2 7 1 5 1 2 2 1 1 6 1 1 1 1 MySqlRowUpdatedEventArgs Constructor Initializes a new instance of the MySqlRowUpdatedEventArgs class Syntax Visual...

Страница 2038: ...ype MySqlRowUpdatingEventArgs containing data related to this event The following MySqlRowUpdatingEventArgsproperties provide information specific to this event Property Description Command Gets or sets the MySqlCommand to execute when performing the Update Errors Gets any errors generated by the NET Framework data provider when the Command executes Row Gets the DataRow that will be sent to the se...

Страница 2039: ...tingEventArgs_ Inherits RowUpdatingEventArgs Syntax C public sealed class MySqlRowUpdatingEventArgs RowUpdatingEventArgs Thread Safety Public static Shared in Visual Basic members of this type are safe for multithreaded operations Instance members are not guaranteed to be thread safe Requirements Namespace MySql Data MySqlClient Assembly MySql Data in MySql Data dll See Also MySqlRowUpdatingEventA...

Страница 2040: ...r type GetHashCode is suitable for use in hashing algorithms and data structures like a hash table GetType inherited from Object Gets the Type of the current instance ToString inherited from Object Returns a String that represents the current Object See Also MySqlRowUpdatingEventArgs Class MySql Data MySqlClient Namespace 20 2 7 1 5 1 2 2 1 1 7 1 1 1 1 MySqlRowUpdatingEventArgs Constructor Initial...

Страница 2041: ...yVal adapter As MySqlDataAdapter _ ByVal lastOneWins As Boolean _ Syntax C public MySqlCommandBuilder MySqlDataAdapteradapter boollastOneWins See Also MySqlCommandBuilder Class MySql Data MySqlClient Namespace MySqlCommandBuilder Constructor Overload List 20 2 7 1 5 1 2 4 MySqlCommandBuilder Constructor Syntax Visual Basic Overloads Public Sub New _ ByVal lastOneWins As Boolean _ Syntax C public M...

Страница 2042: ...mandBuilder Class MySql Data MySqlClient Namespace 20 2 7 1 5 1 6 MySqlCommandBuilder GetDeleteCommand Method Syntax Visual Basic Public Function GetDeleteCommand As MySqlCommand Syntax C public MySqlCommand GetDeleteCommand See Also MySqlCommandBuilder Class MySql Data MySqlClient Namespace 20 2 7 1 5 1 7 MySqlCommandBuilder GetInsertCommand Method Syntax Visual Basic Public Function GetInsertCom...

Страница 2043: ...nheritable Public Class MySqlException_ Inherits SystemException Syntax C public sealed class MySqlException SystemException Thread Safety Public static Shared in Visual Basic members of this type are safe for multithreaded operations Instance members are not guaranteed to be thread safe Requirements Namespace MySql Data MySqlClient Assembly MySql Data in MySql Data dll See Also MySqlException Mem...

Страница 2044: ...BaseException inherited from Exception When overridden in a derived class returns the Exception that is the root cause of one or more subsequent exceptions GetHashCode inherited from Object Serves as a hash function for a particular type GetHashCode is suitable for use in hashing algorithms and data structures like a hash table GetObjectData inherited from Exception When overridden in a derived cl...

Страница 2045: ...hod ExecuteDataset Overloaded Executes a single SQL statement and returns the resultset in a DataSet A new MySqlConnection object is created opened and closed during this method ExecuteNonQuery Overloaded Executes a single command against a MySQL database The MySqlConnection is assumed to be open when the method is called and remains open after the method completes ExecuteReader Overloaded Execute...

Страница 2046: ...mand Return Value DataRow containing the first row of the resultset See Also MySqlHelper Class MySql Data MySqlClient Namespace 20 2 7 1 7 1 2 ExecuteDataset Method Executes a single SQL statement and returns the resultset in a DataSet The state of the MySqlConnection object remains unchanged after execution of this method Overload List Executes a single SQL statement and returns the resultset in ...

Страница 2047: ...tatic DataSet ExecuteDataset MySqlConnectionconnection stringcommandText Parameters connection MySqlConnection object to use commandText Command to execute Return Value DataSetcontaining the resultset See Also MySqlHelper Class MySql Data MySqlClient Namespace MySqlHelper ExecuteDataset Overload List 20 2 7 1 7 1 2 2 MySqlHelper ExecuteDataset Method Executes a single SQL statement and returns the...

Страница 2048: ...c DataSet ExecuteDataset stringconnectionString stringcommandText Parameters connectionString Settings to be used for the connection commandText Command to execute Return Value DataSetcontaining the resultset See Also MySqlHelper Class MySql Data MySqlClient Namespace MySqlHelper ExecuteDataset Overload List 20 2 7 1 7 1 2 4 MySqlHelper ExecuteDataset Method Executes a single SQL statement and ret...

Страница 2049: ...s MySqlParameter Executes a single command against a MySQL database A new MySqlConnection is created using the ConnectionString given public static int ExecuteNonQuery string string params MySqlParameter See Also MySqlHelper Class MySql Data MySqlClient Namespace 20 2 7 1 7 1 3 1 MySqlHelper ExecuteNonQuery Method Executes a single command against a MySQL database The MySqlConnection is assumed to...

Страница 2050: ... MySqlParameter parms Parameters connectionString ConnectionString to use commandText SQL statement to be executed parms Array of MySqlParameter objects to use with the command Return Value See Also MySqlHelper Class MySql Data MySqlClient Namespace MySqlHelper ExecuteNonQuery Overload List 20 2 7 1 7 1 4 ExecuteReader Method Executes a single command against a MySQL database Overload List Execute...

Страница 2051: ...s a single command against a MySQL database Syntax Visual Basic Overloads Public Shared Function ExecuteReader _ ByVal connectionString As String _ ByVal commandText As String _ ParamArray commandParameters As MySqlParameter _ As MySqlDataReader Syntax C public static MySqlDataReader ExecuteReader stringconnectionString stringcommandText params MySqlParameter commandParameters Parameters connectio...

Страница 2052: ...QL database Syntax Visual Basic Overloads Public Shared Function ExecuteScalar _ ByVal connection As MySqlConnection _ ByVal commandText As String _ As Object Syntax C public static object ExecuteScalar MySqlConnectionconnection stringcommandText Parameters connection MySqlConnection object to use commandText Command text to use for the command Return Value The first column of the first row in the...

Страница 2053: ... Visual Basic Overloads Public Shared Function ExecuteScalar _ ByVal connectionString As String _ ByVal commandText As String _ As Object Syntax C public static object ExecuteScalar stringconnectionString stringcommandText Parameters connectionString Settings to use for the update commandText Command text to use for the update Return Value The first column of the first row in the result set or a n...

Страница 2054: ... 1 7 1 6 MySqlHelper UpdateDataSet Method Updates the given table with data from the given DataSet Syntax Visual Basic Public Shared Sub UpdateDataSet _ ByVal connectionString As String _ ByVal commandText As String _ ByVal ds As DataSet _ ByVal tablename As String _ Syntax C public static void UpdateDataSet stringconnectionString stringcommandText DataSetds stringtablename Parameters connectionSt...

Страница 2055: ...amespace Namespace hierarchy Classes Class Description MySqlConversionException Summary description for MySqlConversionException MySqlDateTime Summary description for MySqlDateTime MySqlValue 20 2 7 2 1 MySql Data TypesHierarchy See Also MySql Data Types Namespace 20 2 7 2 2 MySqlConversionException Class Summary description for MySqlConversionException For a list of all members of this type see M...

Страница 2056: ...d from Exception Gets a message that describes the current exception Source inherited from Exception Gets or sets the name of the application or the object that causes the error StackTrace inherited from Exception Gets a string representation of the frames on the call stack at the time the current exception was thrown TargetSite inherited from Exception Gets the method that throws the current exce...

Страница 2057: ...ql Data Types Namespace 20 2 7 2 2 1 1 MySqlConversionException Constructor Syntax Visual Basic Public Sub New _ ByVal msg As String _ Syntax C public MySqlConversionException stringmsg See Also MySqlConversionException Class MySql Data Types Namespace 20 2 7 2 3 MySqlDateTime Class Summary description for MySqlDateTime For a list of all members of this type see MySqlDateTime Members Syntax Visual...

Страница 2058: ...als inherited from Object Determines whether the specified Object is equal to the current Object GetDateTime Returns this value as a DateTime GetHashCode inherited from Object Serves as a hash function for a particular type GetHashCode is suitable for use in hashing algorithms and data structures like a hash table GetType inherited from Object Gets the Type of the current instance ToString Returns...

Страница 2059: ...val Return Value See Also MySqlDateTime Class MySql Data Types Namespace 20 2 7 2 3 1 2 Day Property Returns the day portion of this datetime Syntax Visual Basic Public Property Day As Integer Syntax C public int Day get set See Also MySqlDateTime Class MySql Data Types Namespace 20 2 7 2 3 1 3 Hour Property Returns the hour portion of this datetime Syntax Visual Basic Public Property Hour As Inte...

Страница 2060: ...ta in MySql Data dll See Also MySqlValue Members MySql Data Types Namespace 20 2 7 2 3 1 4 1 1 MySqlValue Members MySqlValue overview Protected Static Shared Fields numberFormat Public Instance Constructors MySqlValue Constructor Initializes a new instance of the MySqlValue class Public Instance Properties IsNull ValueAsObject Returns the value of this field as an object Public Instance Methods Eq...

Страница 2061: ...erwiseClone inherited from Object Creates a shallow copy of the current Object See Also MySqlValue Class MySql Data Types Namespace 20 2 7 2 3 1 4 1 1 1 MySqlValue numberFormat Field Syntax Visual Basic Protected Shared numberFormat As NumberFormatInfo Syntax C protected static NumberFormatInfo numberFormat See Also MySqlValue Class MySql Data Types Namespace 20 2 7 2 3 1 4 1 1 2 MySqlValue Constr...

Страница 2062: ... MySqlValue classType Field The system type represented by this value Syntax Visual Basic Protected classType As Type Syntax C protected Type classType See Also MySqlValue Class MySql Data Types Namespace 20 2 7 2 3 1 4 1 1 6 MySqlValue dbType Field The generic dbtype of this value Syntax Visual Basic Protected dbType As DbType Syntax C protected DbType dbType See Also MySqlValue Class MySql Data ...

Страница 2063: ...bject Syntax C protected object objectValue See Also MySqlValue Class MySql Data Types Namespace 20 2 7 2 3 1 5 IsValidDateTime Property Indicates if this object contains a value that can be represented as a DateTime Syntax Visual Basic Public ReadOnly Property IsValidDateTime As Boolean Syntax C public bool IsValidDateTime get See Also MySqlDateTime Class MySql Data Types Namespace 20 2 7 2 3 1 6...

Страница 2064: ...lic int Month get set See Also MySqlDateTime Class MySql Data Types Namespace 20 2 7 2 3 1 9 Second Property Returns the second portion of this datetime Syntax Visual Basic Public Property Second As Integer Syntax C public int Second get set See Also MySqlDateTime Class MySql Data Types Namespace 20 2 7 2 3 1 10 Year Property Returns the year portion of this datetime Syntax Visual Basic Public Pro...

Страница 2065: ...ems 20 2 8 1 Connector Net Community Support Community support for Connector Net can be found through the forums at http forums mysql com Community support for Connector Net can also be found through the mailing lists at http lists mysql com Paid support is available from Oracle Additional information is available at http dev mysql com support 20 2 8 2 How to Report Connector Net Problems or Bugs ...

Страница 2066: ...oblem is to clone the command object so you have a different actual reference dataAdapter InsertCommand cb GetInsertCommand Clone This will work but since the CommandBuilder is still connected to the DataAdapter the RowUpdating event will still fire and performance will be hit To stop that once all your commands have been added you need to disconnect the CommandBuilder from the DataAdapter cb Data...

Страница 2067: ... detailing the changes in each release of Connector J see MySQL Connector J Release Notes 20 3 1 Overview of MySQL Connector J MySQL provides connectivity for client applications developed in the Java programming language through a JDBC driver which is called MySQL Connector J MySQL Connector J is a JDBC Type 4 driver Different versions are available that are compatible with the JDBC 3 0 and JDBC ...

Страница 2068: ...C API it supports what versions of MySQL Server it works with and whether it is currently supported or not Table 20 22 Summary of Connector J Versions Connector J version Driver Type JDBC version MySQL Server version Status 5 1 4 3 0 4 0 4 1 5 0 5 1 5 4 5 5 Recommended version 5 0 4 3 0 4 1 5 0 Released version 3 1 4 3 0 4 1 5 0 Obsolete 3 0 4 3 0 3 x 4 1 Obsolete The current recommended version f...

Страница 2069: ...ip or zip file Extract it to a suitable location then optionally make the information about the package available by changing your CLASSPATH see Section 20 3 3 2 Installing the Driver and Configuring the CLASSPATH MySQL Connector J is distributed as a zip or tar gz archive containing the sources the class files and the JAR archive named mysql connector java version bin jar Starting with Connector ...

Страница 2070: ...ver s jar file in the WEB INF lib subdirectory of your webapp as this is a standard location for third party class libraries in J2EE web applications You can also use the MysqlDataSource or MysqlConnectionPoolDataSource classes in the com mysql jdbc jdbc2 optional package if your J2EE application server supports or requires them Starting with Connector J 5 0 0 the javax sql XADataSource interface ...

Страница 2071: ... changes are isolated to new functionality exposed in MySQL 4 1 and newer which includes Unicode character sets server side prepared statements SQLState codes returned in error messages by the server and various performance enhancements that can be enabled or disabled using configuration properties Unicode Character Sets See the next section as well as Section 10 1 Character Set Support for inform...

Страница 2072: ...Connector J 3 1 8 a debug build of the driver in a file named mysql connector java version bin g jar is shipped alongside the normal binary jar file that is named mysql connector java version bin jar Starting with Connector J 3 1 9 we do not ship the class files unbundled they are only available in the JAR archives that ship with the driver Do not use the debug build of the driver unless instructe...

Страница 2073: ...mes through the Ant D option 5 Issue the following command to compile the driver and create a jar file suitable for installation shell ant dist This creates a build directory in the current directory where all build output will go A directory is created in the build directory that includes the version number of the sources you are building from This directory contains the sources compiled class fi...

Страница 2074: ...r The org gjt mm mysql Driver class name is also usable for backward compatibility with MM MySQL the predecessor of Connector J Use this class name when registering the driver or when otherwise configuring software to use MySQL Connector J JDBC URL Format The JDBC URL format for MySQL Connector J is as follows with items in square brackets being optional jdbc mysql host failoverhost port database ...

Страница 2075: ...to true at the end of every transaction connection use The failover functionality has the following behavior If the URL property autoReconnect is false Failover only happens at connection initialization and failback occurs when the driver determines that the first host has become available again If the URL property autoReconnect is true Failover happens when the driver determines that the connecti...

Страница 2076: ...tified of connection lifecycle events creation destruction commit rollback setCatalog and setAutoCommit and potentially alter the execution of these commands ConnectionLifecycleInterceptors are stackable more than one interceptor may be specified via the configuration property as a comma delimited list with the interceptors executed in order from left to right 5 1 4 useConfigs Load the comma delim...

Страница 2077: ...IVE_TIMEOUT instead of WAIT_TIMEOUT false 3 1 0 localSocketAddress Hostname or IP address given to explicitly configure the interface that the driver will bind the client side of the TCP IP connection to when connecting 5 0 5 propertiesTransform An implementation of com mysql jdbc ConnectionPropertiesTransform that the driver will use to modify URL properties passed to the driver before attempting...

Страница 2078: ...ions properly Alternatively as a last option investigate setting the MySQL server variable wait_timeout to a high value rather than the default of 8 hours false 1 1 autoReconnectForPools Use a reconnection strategy appropriate for connection pools defaults to false false 3 1 3 failOverReadOnly When failing over in autoReconnect mode should the connection be set to read only true 3 0 12 maxReconnec...

Страница 2079: ...to false and does not affect the addBatch and executeBatch methods which instead rely on rewriteBatchStatements false 3 1 1 useSSL Use SSL when communicating with the server true false defaults to false false 3 0 2 requireSSL Require SSL connection if useSSL true defaults to false false 3 1 0 verifyServerCertificate If useSSL is set to true should the driver verify the server s certificate When us...

Страница 2080: ... statements should be cached 100 3 1 2 metadataCacheSize The number of queries to cache ResultSetMetadata for if cacheResultSetMetaData is set to true default 50 50 3 1 1 useLocalSessionState Should the driver refer to the internal values of autocommit and transaction isolation that are set by Connection setAutoCommit and Connection setTransactionIsolation and transaction state as maintained by th...

Страница 2081: ...etrieve rows false 5 0 0 blobSendChunkSize Chunk to use when sending BLOB CLOBs via ServerPreparedStatements 1048576 3 1 9 cacheCallableStmts Should the driver cache the parsing stage of CallableStatements false 3 1 2 cachePrepStmts Should the driver cache the parsing stage of PreparedStatements of client side prepared statements the check for suitability of server side prepared and server side pr...

Страница 2082: ...should the driver use 1 random the driver will pick a random host for each request This tends to work better than round robin as the randomness will somewhat account for spreading loads where requests vary in response time while round robin can sometimes lead to overloaded nodes if there are variations in response times across the workload 2 bestResponseTime the driver will route the request to th...

Страница 2083: ...ofiling Property Name Definition Default Value Since Version logger The name of a class that implements com mysql jdbc log Log that will be used to log messages to default is com mysql jdbc log StandardLogger which logs to STDERR com mysql jdbc log StandardLogge 3 1 1 gatherPerfMetrics Should the driver gather performance metrics and report them via the configured logger every reportMetricsInterva...

Страница 2084: ...tDebugBufferSize packets will be kept and dumped when exceptions are thrown in key areas in the driver s code false 3 1 3 explainSlowQueries If logSlowQueries is enabled should the driver automatically issue an EXPLAIN on the server and send the results to the configured log at a WARN level false 3 1 2 includeInnodbStatusInDeadlockExceptions Include the output of SHOW ENGINE INNODB STATUS in excep...

Страница 2085: ...defined key value pairs to be passed to MySQL Server for display as connection attributes in the PERFORMANCE_SCHEMA SESSION_CONNECT_ATTRS table Example usage connectionAttributes key1 value1 key2 value2 This functionality is available for use with MySQL Server version 5 6 or later only Earlier versions of MySQL Server do not support connection attributes causing this configuration option will be i...

Страница 2086: ...ResultSetMetadata false 5 1 7 allowNanAndInf Should the driver allow NaN or INF values in PreparedStatement setDouble false 3 1 5 autoClosePStmtStreams Should the driver automatically call close on streams readers passed as arguments via set methods false 3 1 12 autoDeserialize Should the driver automatically detect and de serialize objects stored in BLOB fields false 3 1 5 blobsAreStrings Should ...

Страница 2087: ...ace them with client side emulated versions true 3 1 7 exceptionInterceptors Comma delimited list of classes that implement com mysql jdbc ExceptionInterceptor These classes will be instantiated one per Connection instance and all SQLExceptions thrown by the driver will be allowed to be intercepted by these interceptors in a chained fashion with the first class listed as the head of the chain 5 1 ...

Страница 2088: ... each of load balanced physical connections when using load balanced Connection 0 5 1 13 loadBalanceSQLExceptionSubclassFailover Comma delimited list of classes interfaces used by default load balanced exception checker to determine whether a given SQLException should trigger failover The comparison is done using Class isInstance SQLException using the thrown SQLException 5 1 13 loadBalanceSQLStat...

Страница 2089: ... this facility contains much more than just foreign key support one such application being OpenOffice false 3 1 12 padCharsWithSpace If a result set column has the CHAR type and the value does not fill the amount of characters specified in the DDL for the column should the driver pad the remaining characters with space for ANSI compliance false 5 0 6 pedantic Follow the JDBC spec to the letter fal...

Страница 2090: ...as specified in this property 5 1 1 strictFloatingPoint Used only in older versions of compliance test false 3 0 0 strictUpdates Should the driver do strict checking all primary keys selected of updatable result sets true false defaults to true true 3 0 4 tinyInt1isBit Should the driver treat the datatype TINYINT 1 as the BIT type because the server silently converts BIT TINYINT 1 when creating ta...

Страница 2091: ...turn aliases if any for ResultSetMetaData getColumnName or ResultSetMetaData getTableName rather than the original column table name In 5 0 x the default value was true false 5 0 4 useOldUTF8Behavior Use the UTF 8 behavior the driver did when communicating with 4 0 and older servers false 3 1 6 useOnlyServerErrorMessages Don t prepend standard SQLState error messages to error messages returned by ...

Страница 2092: ...onvenient shorthand for specifying combinations of options for particular scenarios The argument values you can use with this option correspond to the names of properties files within the Connector J mysql connector java version bin jar JAR file For example the Connector J 5 1 9 driver includes the following configuration properties files unzip mysql connector java 5 1 19 bin jar configs Archive m...

Страница 2093: ...liance test suite This section gives details on a interface by interface level about implementation decisions that might affect how you code applications with MySQL Connector J The JDBC specification is vague about how certain functionality should be implemented or the specification enables leeway in implementation BLOB Starting with Connector J version 3 1 0 you can emulate BLOBs with locators by...

Страница 2094: ...information getImportedKeys getExportedKeys and getCrossReference is only available from InnoDB tables The driver uses SHOW CREATE TABLE to retrieve this information so if any other storage engines add support for foreign keys the driver would transparently support them as well PreparedStatement PreparedStatements are implemented by the driver as MySQL does not have a prepared statement feature Be...

Страница 2095: ... the locks these statements hold can be released whether they be MyISAM table level locks or row level locks in some other storage engine such as InnoDB is when the statement completes If the statement is within scope of a transaction then locks are released when the transaction completes which implies that the statement needs to complete first As with most other databases statements are not compl...

Страница 2096: ...am instance that will be used to send data in response to a LOAD DATA LOCAL INFILE statement This method returns NULL if no such stream has been set using setLocalInfileInputStream 20 3 5 3 Java JDBC and MySQL Types MySQL Connector J is flexible in the way it handles conversions between MySQL data types and Java data types In general any MySQL data type can be converted to a java lang String and a...

Страница 2097: ... between MySQL and Java types following the JDBC specification where appropriate The value returned by ResultSetMetaData GetColumnClassName is also shown below For more information on the java sql Types classes see Java 2 Platform Types Table 20 25 MySQL Types to Java Types for ResultSet getObject MySQL Type Name Return value of GetColumnClassName Returned as Java Class BIT 1 new in MySQL 5 0 BIT ...

Страница 2098: ...1 value2 CHAR java lang String 20 3 5 4 Using Character Sets and Unicode All strings sent from the JDBC driver to the server are converted automatically from native Java Unicode form to the client character encoding including all queries sent using Statement execute Statement executeUpdate Statement executeQuery as well as all PreparedStatement and CallableStatement parameters with the exclusion o...

Страница 2099: ...ter set or by configuring the JDBC driver to use UTF 8 through the characterEncoding property When specifying character encodings on the client side use Java style names The following table lists MySQL character set names and the corresponding Java style names Table 20 26 MySQL to Java Encoding Name Translations MySQL Character Set Name Java Style Character Encoding Name ascii US ASCII big5 Big5 g...

Страница 2100: ...r Alternatively use the CA Certificate that you have generated or been provided with by your SSL provider To use Java s keytool to create a truststore in the current directory and import the server s CA certificate cacert pem you can do the following assuming that keytool is in your path The keytool is typically located in the bin subdirectory of your JDK or JRE shell keytool import alias mysqlSer...

Страница 2101: ... ssl trustStore path_to_truststore_file Djavax net ssl trustStorePassword password Or you can set the values directly within the application System setProperty javax net ssl keyStore path_to_keystore_file System setProperty javax net ssl keyStorePassword password System setProperty javax net ssl trustStore path_to_truststore_file System setProperty javax net ssl trustStorePassword password You wil...

Страница 2102: ...d to the server the connection to the server must be encrypted PAM authentication support is enabled by default in Connector J 5 1 21 and up so no extra configuration is needed To disable the PAM authentication feature specify mysql_clear_password the method or com mysql jdbc authentication MysqlClearPasswordPlugin the class name in the comma separated list of arguments for the disabledAuthenticat...

Страница 2103: ... Looks like a normal MySQL JDBC url with a comma separated list of hosts the first being the master the rest being any number of slaves that the driver will load balance against Connection conn driver connect jdbc mysql replication master slave1 slave2 slave3 test props Perform read write work on the master by setting the read only flag to false conn setReadOnly false conn setAutoCommit false conn...

Страница 2104: ...22 42S22 1055 ER_WRONG_FIELD_WITH_GROUP S1009 42000 1056 ER_WRONG_GROUP_FIELD S1009 42000 1057 ER_WRONG_SUM_SELECT S1009 42000 1058 ER_WRONG_VALUE_COUNT 21S01 21S01 1059 ER_TOO_LONG_IDENT S1009 42000 1060 ER_DUP_FIELDNAME S1009 42S21 1061 ER_DUP_KEYNAME S1009 42000 1062 ER_DUP_ENTRY S1009 23000 1063 ER_WRONG_FIELD_SPEC S1009 42000 1064 ER_PARSE_ERROR 42000 42000 1065 ER_EMPTY_QUERY 42000 42000 106...

Страница 2105: ...E S1000 42000 1120 ER_WRONG_OUTER_JOIN S1000 42000 1121 ER_NULL_COLUMN_IN_INDEX S1000 42000 1129 ER_HOST_IS_BLOCKED 08004 HY000 1130 ER_HOST_NOT_PRIVILEGED 08004 HY000 1131 ER_PASSWORD_ANONYMOUS_USER S1000 42000 1132 ER_PASSWORD_NOT_ALLOWED S1000 42000 1133 ER_PASSWORD_NO_MATCH S1000 42000 1136 ER_WRONG_VALUE_COUNT_ON_ROW S1000 21S01 1138 ER_INVALID_USE_OF_NULL S1000 42000 1139 ER_REGEXP_ERROR S10...

Страница 2106: ...000 42000 1173 ER_REQUIRES_PRIMARY_KEY S1000 42000 1177 ER_CHECK_NO_SUCH_TABLE S1000 42000 1178 ER_CHECK_NOT_IMPLEMENTED S1000 42000 1179 ER_CANT_DO_THIS_DURING_AN_TRANSACTION S1000 25000 1184 ER_NEW_ABORTING_CONNECTION S1000 08S01 1189 ER_MASTER_NET_READ S1000 08S01 1190 ER_MASTER_NET_WRITE S1000 08S01 1203 ER_TOO_MANY_USER_CONNECTIONS S1000 42000 1205 ER_LOCK_WAIT_TIMEOUT 41000 41000 1207 ER_REA...

Страница 2107: ...utside of an application server the DriverManager class manages the establishment of Connections Specify to the DriverManager which JDBC drivers to try to make Connections with The easiest way to do this is to use Class forName on the class that implements the java sql Driver interface With MySQL Connector J the name of this class is com mysql jdbc Driver With this method you could use an external...

Страница 2108: ...on is established it can be used to create Statement and PreparedStatement objects as well as retrieve metadata about the database This is explained in the following sections 20 3 6 2 Using JDBC Statement Objects to Execute SQL Statement objects allow you to execute basic SQL queries and retrieve the results through the ResultSet class which is described later To create a Statement instance you ca...

Страница 2109: ... println VendorError ex getErrorCode finally it is a good idea to release resources in a finally block in reverse order of their creation if they are no longer needed if rs null try rs close catch SQLException sqlEx ignore rs null if stmt null try stmt close catch SQLException sqlEx ignore stmt null 20 3 6 3 Using JDBC CallableStatements to Execute Stored Procedures Starting with MySQL server vers...

Страница 2110: ... prepareCall import java sql CallableStatement Prepare a call to the stored procedure demoSp with two parameters Notice the use of JDBC escape syntax call CallableStatement cStmt conn prepareCall call demoSp cStmt setString 1 abcdefg Note Connection prepareCall is an expensive method due to the metadata retrieval that the driver performs to support output parameters For performance reasons minimiz...

Страница 2111: ...arameters if any exist Input and in out parameters are set as for PreparedStatement objects However CallableStatement also supports setting parameters by name Example 20 6 Connector J Setting CallableStatement input parameters Set a parameter by index cStmt setString 1 abcdefg Alternatively set a parameter using the parameter name cStmt setString inputParameter abcdefg Set the in out parameter usi...

Страница 2112: ...l isn t portable and issuing a SELECT to get the AUTO_INCREMENT key s value requires another round trip to the database which isn t as efficient as possible The following code snippets demonstrate the three different ways to retrieve AUTO_INCREMENT values First we demonstrate the use of the new JDBC 3 0 method getGeneratedKeys which is now the preferred method to use if you need to retrieve AUTO_I...

Страница 2113: ...f using Statement getGeneratedKeys to retrieve the value of an auto increment value int autoIncKeyFromApi 1 rs stmt getGeneratedKeys if rs next autoIncKeyFromApi rs getInt 1 else throw an exception from here rs close rs null System out println Key returned from getGeneratedKeys autoIncKeyFromApi finally if rs null try rs close catch SQLException ex ignore if stmt null try stmt close catch SQLExcep...

Страница 2114: ...d Use the MySQL LAST_INSERT_ID function to do the same thing as getGeneratedKeys int autoIncKeyFromFunc 1 rs stmt executeQuery SELECT LAST_INSERT_ID if rs next autoIncKeyFromFunc rs getInt 1 else throw an exception from here rs close System out println Key returned from SELECT LAST_INSERT_ID autoIncKeyFromFunc finally if rs null try rs close catch SQLException ex ignore if stmt null try stmt close...

Страница 2115: ...INCREMENT key from an updatable result set rs stmt executeQuery SELECT priKey dataField FROM autoIncTutorial rs moveToInsertRow rs updateString dataField AUTO INCREMENT here rs insertRow the driver adds rows at the end rs last We should now be on the row we just inserted int autoIncKeyFromRS rs getInt priKey rs close rs null System out println Key returned for inserted row autoIncKeyFromRS finally...

Страница 2116: ...it is used exclusively by the thread that requested it From a programming point of view it is the same as if your thread called DriverManager getConnection every time it needed a JDBC connection With connection pooling your thread may end up using either a new connection or an already existing connection Benefits of Connection Pooling The main benefits to connection pooling are Reduced connection ...

Страница 2117: ...sms your particular connection pooling library provides InitialContext ctx new InitialContext Lookup the DataSource which will be backed by a pool that the application server provides DataSource instances are also a good candidate for caching as an instance variable as JNDI lookups can be expensive as well DataSource ds DataSource ctx lookup java comp env jdbc MySQLDB The following code is what wo...

Страница 2118: ...ing any useful work Connection pools can be tuned to maximize performance while keeping resource utilization below the point where your application will start to fail rather than just run slower The optimal size for the connection pool depends on anticipated load and average database transaction time In practice the optimal connection pool size can be smaller than you might expect If you take Sun ...

Страница 2119: ...results in the non active physical connections assuming a stale state and they may die If Connector J then re balances it might select a dead connection resulting in an exception being passed to the application To help prevent this you can use loadBalanceValidateConnectionOnSwapServer to validate the connection before use If your Connector J deployment uses a connection pool that allows you to spe...

Страница 2120: ...hysical connection count Current active logical connection count Total logical connections created Total transaction count The following management operations can also be performed Add host Remove host The JMX interface com mysql jdbc jmx LoadBalanceConnectionGroupManagerMBean has the following methods int getActiveHostCount String group int getTotalHostCount String group long getTotalLogicalConne...

Страница 2121: ...th the Dcom sun management jmxremote flag to enable remote management jconsole can then be started The Test main class will be listed by jconsole Select this and click Connect You can then navigate to the com mysql jdbc jmx LoadBalanceConnectionGroupManager bean At this point you can click on various operations and examine the returned result If you now had an additional instance of MySQL running ...

Страница 2122: ...s public class NdbLoadBalanceExceptionChecker extends StandardLoadBalanceExceptionChecker public boolean shouldExceptionTriggerFailover SQLException ex return super shouldExceptionTriggerFailover ex checkNdbException ex private boolean checkNdbException SQLException ex Have to parse the message since most NDB errors are mapped to the same DEMC return ex getMessage startsWith Lock wait timeout exce...

Страница 2123: ...transparent way to extend or modify some aspect of a program similar to a user exit No recompiling is required With Connector J the interceptors are enabled and disabled by updating the connection string to refer to different sets of interceptor classes that you instantiate The connection properties that control the interceptors are explained in Section 20 3 5 1 Driver Datasource Class Names URL S...

Страница 2124: ...asicDataSourceFactory value parameter parameter name maxActive name value 10 value parameter parameter name maxIdle name value 5 value parameter parameter name validationQuery name value SELECT 1 value parameter parameter name testOnBorrow name value true value parameter parameter name testWhileIdle name value true value parameter parameter name timeBetweenEvictionRunsMillis name value 10000 value...

Страница 2125: ...he Connector J driver in Tomcat on Windows Namely the Connector J jar remains locked This is an initialization problem that is not related to the driver The possible workarounds if viable are as follows use antiResourceLocking true as a Tomcat Context attribute or remove the META INF directory 20 3 12 Using Connector J with JBoss These instructions cover JBoss 4 x To make the JDBC driver classes a...

Страница 2126: ...perties that will be used in the configuration For the datasource configuration bean id dataSource class org springframework jdbc datasource DriverManagerDataSource property name driverClassName value db driver property name url value db jdbcurl property name username value db username property name password value db password bean The placeholders are used to provide values for properties of this ...

Страница 2127: ...e use of the Template method design pattern see Template Method Pattern Our immediate focus will be on the JdbcTemplate and related classes specifically NamedParameterJdbcTemplate The template classes handle obtaining and releasing a connection for data access when one is needed The next example shows how to use NamedParameterJdbcTemplate inside of a DAO Data Access Object class to retrieve a rand...

Страница 2128: ...add transactions into our code if we do not deal directly with the JDBC classes Spring provides a transaction management package that not only replaces JDBC transaction management but also enables declarative transaction management configuration instead of code To use transactional database access we will need to change the storage engine of the tables in the world database The downloaded script e...

Страница 2129: ...an id transactionManager class org springframework jdbc datasource DataSourceTransactionManager property name dataSource ref dataSource bean tx advice id txAdvice transaction manager transactionManager tx attributes tx method name tx attributes tx advice The preceding code creates a transaction manager that handles transactions for the data source provided to it The txAdvice uses this transaction ...

Страница 2130: ...CP that we want three connections in the pool when it is created Another way to configure connection pooling is to configure a data source in our J2EE application server Using JBoss as an example you can set up the MySQL connection pool by creating a file called mysql local ds xml and placing it in the server default deploy directory in JBoss Once we have this setup we can use JNDI to look it up W...

Страница 2131: ...n pool you will also need to create a JDBC Resource data source for use by your application Creating a JDBC Resource Your Java application will usually reference a data source object to establish a connection with the database This needs to be created first using the following procedure Using the navigation tree in the Glassfish Administration Console navigate to Resources JDBC JDBC Resources A li...

Страница 2132: ...wo XML files are required web xml and sun web xml There may be other files present such as classes and images These files are organized into the directory structure as follows index jsp WEB INF web xml sun web xml The code for web xml is xml version 1 0 encoding UTF 8 web app version 2 4 xmlns http java sun com xml ns j2ee xmlns xsi http www w3 org 2001 XMLSchema instan display name HelloWebApp di...

Страница 2133: ...p env jdbc MySQLDataSource You will still be able to access the data source directly using ds DataSource ctx lookup jdbc MySQLDataSource With the source files in place in the correct directory structure you are ready to deploy the application 1 In the navigation tree navigate to Applications the Applications frame will be displayed Click Deploy 2 You can now deploy an application packaged into a s...

Страница 2134: ...tement sql catch SQLException se System out println SQLException se getMessage catch NamingException ne System out println NamingException ne getMessage public void destroy try if rs null rs close if ps null ps close if conn null conn close if ctx null ctx close catch SQLException se System out println SQLException se getMessage catch NamingException ne System out println NamingException ne getMes...

Страница 2135: ...POST action associated with the input form The form is defined in the file index html html head title HelloWebServlet title head body h1 HelloWebServlet h1 p Please enter country name p form action HelloWebServlet method POST input type text name country_name length 50 input type submit value Submit form body html The XML files web xml and sun web xml are as for the example in the preceding sectio...

Страница 2136: ... to the MySQL server using Connector J and I m sure the connection parameters are correct 21 3 15 7 2120 I am trying to connect to my MySQL server within my application but I get the following error and stack trace java net SocketException MESSAGE Software caused connection abort recv failed STACKTRACE java net SocketException Software caused connection abort recv failed at java net SocketInputStr...

Страница 2137: ...nects to MySQL the security manager in MySQL server will use its grant tables to determine whether the connection is permitted You must add the necessary security credentials to the MySQL server for this to happen using the GRANT statement to your MySQL Server See Section 13 7 1 3 GRANT Syntax for more information Note Testing your connectivity with the mysql command line client will not work unle...

Страница 2138: ...llow TCP IP connections from the host where your Java code is running to the MySQL server on the port that MySQL is listening to by default 3306 21 3 15 4 I have a servlet application that works fine for a day and then stops working overnight MySQL closes connections after 8 hours of inactivity You either need to use a connection pool that handles stale connections or use the autoReconnect paramet...

Страница 2139: ...tring query SELECT foo FROM bar ORDER BY baz rs stmt executeQuery query while rs next rs close rs null stmt close stmt null conn commit conn close conn null transactionCompleted true catch SQLException sqlEx The two SQL states that are retry able are 08S01 for a communications error and 40001 for deadlock Only retry if the error was due to a stale connection communications problem or deadlock Stri...

Страница 2140: ...pan one table that is no joins This is outlined in the JDBC specification Note that this issue only occurs when using updatable result sets and is caused because Connector J is unable to guarantee that it can identify the correct rows within the result set to be updated without having a unique reference to each row There is no requirement to have a unique field on a table if you are using UPDATE o...

Страница 2141: ...ithin the JBoss wiki for more information 21 3 15 9 When using gcj a java io CharConversionException exception is raised when working with certain character sequences This is a known issue with gcj which raises an exception when it reaches an unknown character or one it cannot convert Add useJvmCharsetConverters true to your connection string to force character conversion outside of the gcj librar...

Страница 2142: ...left idle for an extended period of time Ensure that wait_timeout and interactive_timeout are set sufficiently high Ensure that tcpKeepalive is enabled Ensure that any configurable firewall or router timeout settings allow for the maximum expected connection idle time Note Do not expect to be able to reuse a connection without problems if it has being lying idle for a period If a connection is to ...

Страница 2143: ...xample Temporary tables User defined variables Server side prepared statements These items are lost when a connection fails and if the connection silently reconnects without generating an exception this could be detrimental to the correct execution of your application In summary communication errors generate conditions that may well be unsafe for Connector J to simply ignore by silently reconnecti...

Страница 2144: ...elp us much or at all If you have a repeatable bug report please report it to the bugs database at http bugs mysql com Any bug that we are able to repeat has a high chance of being fixed in the next MySQL release To report other problems you can use one of the MySQL mailing lists Remember that it is possible for us to respond to a message containing too much information but not to one containing t...

Страница 2145: ...ertTrue String failureMessage boolean expression methods to create conditions that must be met in your testcase demonstrating the behavior you are expecting vs the behavior you are observing which is why you are most likely filing a bug report Finally create a main method that creates a new instance of your testcase and calls the run method public static void main String args throws Exception new ...

Страница 2146: ...piled and ready for use in writing client programs A source distribution contains the source files required to produce the same headers libraries and utilities included in a binary distribution but you compile them yourself MySQL Connector C distributions include these components A set of h header files that C applications include at compile time These files are located in the include directory St...

Страница 2147: ... denoted here as PACKAGE tar gz or PACKAGE zip A source distribution can be used on any supported platform listed in Section 20 4 1 MySQL Connector C Supported Platforms Download the distribution file and unpack it in the intended installation directory To unpack a compressed tar file use this command shell tar zxvf PACKAGE tar gz To unpack a Zip archive use WinZip or another tool that can read zi...

Страница 2148: ...0 4 5 3 Other Build Options The result of the cmake command is a project solution file libmysql sln that you can open with Visual Studio Alternatively build from the command line with either of these commands shell devenv com libmysql sln build Release shell devenv com libmysql sln build RelWithDebInfo For other versions of Visual Studio or for an nmake based build use the following command to che...

Страница 2149: ...ySQL Connector C specify the appropriate compile time options as indicated in that section 20 5 libmysqld the Embedded MySQL Server Library The embedded MySQL server library is NOT part of MySQL 5 0 It is part of previous editions and will be included in future versions starting with MySQL 5 1 You can find appropriate documentation in the corresponding manuals for these versions In this manual onl...

Страница 2150: ...grams because they are referenced from the library For a list of these variables see Section 4 1 Overview of MySQL Programs For instructions on building client programs using the C API see Section 20 6 3 1 Building C API Client Programs For programming with threads see Section 20 6 3 2 Writing C API Threaded Client Programs To create a standalone application which includes the server and client in...

Страница 2151: ...bedded server depending on whether it is linked against libmysqlclient or libmysqld at build time There are two ways to obtain the C API header and library files required to build C API client programs Install a MySQL Server distribution Server distributions include both libmysqlclient and libmysqld Install a MySQL Connector C distribution Connector C distributions include only libmysqlclient They...

Страница 2152: ...ibrary For example if the library is installed in usr local mysql lib use these options in the link command L usr local mysql lib lmysqlclient lz The path names may differ on your system Adjust the I and L options as necessary To make it simpler to compile MySQL programs on Unix use the mysql_config script See Section 4 7 2 mysql_config Display Options for Compiling Clients mysql_config displays t...

Страница 2153: ... o text 0x69 undefined reference to mysql_error tmp ccFKsdPa o text 0x9a undefined reference to mysql_close You should be able to solve this problem by adding Ldir_path lmysqlclient at the end of your link command where dir_path represents the path name of the directory where the client library is located To determine the correct directory try this command shell mysql_config libs The output from m...

Страница 2154: ...n access different result sets that are retrieved with mysql_store_result To use mysql_use_result you must ensure that no other thread is using the same connection until the result set is closed However it really is best for threaded clients that share the same connection to use mysql_store_result You need to know the following if you have a thread that did not create the connection to the MySQL d...

Страница 2155: ...h a copy is usable MYSQL_RES This structure represents the result of a query that returns rows SELECT SHOW DESCRIBE EXPLAIN The information returned from a query is called the result set in the remainder of this section MYSQL_ROW This is a type safe representation of one row of data It is currently implemented as an array of counted byte strings You cannot treat these as null terminated strings if...

Страница 2156: ...ar catalog The catalog name This value is always def char def The default value of this field as a null terminated string This is set only if you use mysql_list_fields unsigned long length The width of the field This corresponds to the display length in bytes The server determines the length value before it generates the result set so this is the minimum length required for a data type capable of ...

Страница 2157: ...hown in the following table Flag Value Flag Description NOT_NULL_FLAG Field can t be NULL PRI_KEY_FLAG Field is part of a primary key UNIQUE_KEY_FLAG Field is part of a unique key MULTIPLE_KEY_FLAG Field is part of a nonunique key UNSIGNED_FLAG Field has the UNSIGNED attribute ZEROFILL_FLAG Field has the ZEROFILL attribute BINARY_FLAG Field has the BINARY attribute AUTO_INCREMENT_FLAG Field has th...

Страница 2158: ...e to determine the boolean status of the flags value Flag Status Description IS_NOT_NULL flags True if this field is defined as NOT NULL IS_PRI_KEY flags True if this field is a primary key IS_BLOB flags True if this field is a BLOB or TEXT deprecated test field type instead unsigned int decimals The number of decimals for numeric fields unsigned int charsetnr An ID number that indicates the chara...

Страница 2159: ... BINARY field MYSQL_TYPE_VAR_STRING VARCHAR or VARBINARY field MYSQL_TYPE_BLOB BLOB or TEXT field use max_length to determine the maximum length MYSQL_TYPE_SET SET field MYSQL_TYPE_ENUM ENUM field MYSQL_TYPE_GEOMETRY Spatial field MYSQL_TYPE_NULL NULL type field You can use the IS_NUM macro to test whether a field has a numeric type Pass the type value to IS_NUM and it evaluates to TRUE if the fie...

Страница 2160: ...mysql_error Returns the error message for the most recently invoked MySQL function mysql_escape_string Escapes special characters in a string for use in an SQL statement mysql_fetch_field Returns the type of the next table field mysql_fetch_field_direct Returns the type of a table field given a field number mysql_fetch_fields Returns an array of all field structures mysql_fetch_lengths Returns the...

Страница 2161: ... SQL query specified as a null terminated string mysql_real_connect Connects to a MySQL server mysql_real_escape_string Escapes special characters in a string for use in an SQL statement taking into account the current character set of the connection mysql_real_query Executes an SQL query specified as a counted string mysql_refresh Flush or reset tables and caches mysql_reload Tells the server to ...

Страница 2162: ...t For applications that are linked with the embedded server these calls start and stop the server mysql_library_init and mysql_library_end are available as of MySQL 5 0 3 For older versions of MySQL you can call mysql_server_init and mysql_server_end instead In a nonmulti threaded environment the call to mysql_library_init may be omitted because mysql_init will invoke it automatically as necessary...

Страница 2163: ...mysql_use_result is that the client requires less memory for the result set because it maintains only one row at a time and because there is less allocation overhead mysql_use_result can be faster Disadvantages are that you must process each row quickly to avoid tying up the server you don t have random access to rows within the result set you can only access rows sequentially and you don t know h...

Страница 2164: ... statement if it was an UPDATE DELETE or INSERT For SELECT statements mysql_affected_rows works like mysql_num_rows For UPDATE statements the affected rows value by default is the number of rows actually changed If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect when connecting to mysqld the affected rows value is the number of rows found that is matched by the WHERE clause For REPLAC...

Страница 2165: ... specifier mysql_change_user fails if the connected user cannot be authenticated or doesn t have permission to use the database In this case the user and database are not changed The db parameter may be set to NULL if you don t want to have a default database This command resets the state as if one had done a new connect See Section 20 6 14 Controlling Automatic Reconnection Behavior It always per...

Страница 2166: ... to the database ER_WRONG_DB_NAME 2917 The database name was too long Example if mysql_change_user mysql user password new_database fprintf stderr Failed to change user Error s n mysql_error mysql 20 6 6 4 mysql_character_set_name const char mysql_character_set_name MYSQL mysql Description Returns the default character set name for the current connection Return Values The default character set nam...

Страница 2167: ...on is deprecated Use mysql_real_connect instead mysql_connect attempts to establish a connection to a MySQL database engine running on host mysql_connect must complete successfully before you can execute any of the other API functions with the exception of mysql_get_client_info The meanings of the parameters are the same as for the corresponding parameters for mysql_real_connect with the differenc...

Страница 2168: ...g the query CR_UNKNOWN_ERROR 2941 An unknown error occurred Example if mysql_create_db mysql my_database fprintf stderr Failed to create new database Error s n mysql_error mysql 20 6 6 9 mysql_data_seek void mysql_data_seek MYSQL_RES result my_ulonglong offset Description Seeks to an arbitrary row in a query result set The offset value is a row number Specify a value in the range from 0 to mysql_n...

Страница 2169: ... db Description Drops the database named by the db parameter This function is deprecated It is preferable to use mysql_query to issue an SQL DROP DATABASE statement instead Return Values Zero if the database was dropped successfully Nonzero if an error occurred Errors CR_COMMANDS_OUT_OF_SYNC 2942 Commands were executed in an improper order CR_SERVER_GONE_ERROR 2942 The MySQL server has gone away C...

Страница 2170: ...esult set has been reached and it is unnecessary to call mysql_eof When used with mysql_store_result mysql_eof always returns true On the other hand if you use mysql_use_result to initiate a result set retrieval the rows of the set are obtained from the server one by one as you call mysql_fetch_row repeatedly Because an error may occur on the connection during this process a NULL return value from...

Страница 2171: ...n that can succeed or fail A return value of zero means that no error occurred Client error message numbers are listed in the MySQL errmsg h header file Server error message numbers are listed in mysqld_error h Errors also are listed at Appendix C Errors Error Codes and Common Problems Note that some functions like mysql_fetch_row don t set mysql_errno if they succeed A rule of thumb is that all f...

Страница 2172: ...ql_real_escape_string except that mysql_real_escape_string takes a connection handler as its first argument and escapes the string according to the current character set mysql_escape_string does not take a connection argument and does not respect the current character set 20 6 6 17 mysql_fetch_field MYSQL_FIELD mysql_fetch_field MYSQL_RES result Description Returns the definition of one column of ...

Страница 2173: ...the definition for an arbitrary column Specify a value for fieldnr in the range from 0 to mysql_num_fields result 1 Return Values The MYSQL_FIELD structure for the specified column Errors None Example unsigned int num_fields unsigned int i MYSQL_FIELD field num_fields mysql_num_fields result for i 0 i num_fields i field mysql_fetch_field_direct result i printf Field u is s n i field name 20 6 6 19...

Страница 2174: ...ns containing NULL values is zero To see how to distinguish these two cases see the description for mysql_fetch_row Return Values An array of unsigned long integers representing the size of each column not including any terminating null characters NULL if an error occurred Errors mysql_fetch_lengths is valid only for the current row of the result set It returns NULL if you call it before calling m...

Страница 2175: ...ql_fetch_row CR_SERVER_LOST 2942 The connection to the server was lost during the query CR_UNKNOWN_ERROR 2941 An unknown error occurred Example MYSQL_ROW row unsigned int num_fields unsigned int i num_fields mysql_num_fields result while row mysql_fetch_row result unsigned long lengths lengths mysql_fetch_lengths result for i 0 i num_fields i printf s int lengths i row i row i NULL printf n 20 6 6...

Страница 2176: ...ected_rows mysql else mysql_store_result should have returned data fprintf stderr Error s n mysql_error mysql An alternative is to replace the mysql_field_count mysql call with mysql_errno mysql In this case you are checking directly for an error from mysql_store_result rather than inferring from the value of mysql_field_count whether the statement was a SELECT 20 6 6 23 mysql_field_seek MYSQL_FIE...

Страница 2177: ...Values None Errors None 20 6 6 26 mysql_get_character_set_info void mysql_get_character_set_info MYSQL mysql MY_CHARSET_INFO cs Description This function provides information about the default client character set The default character set may be changed with the mysql_set_character_set function This function was added in MySQL 5 0 10 Example This example shows the fields that are available in the...

Страница 2178: ...jor version YY is the release level and ZZ is the version number within the release level For example a value of 40102 represents a client library version of 4 1 2 Return Values An integer that represents the MySQL client library version Errors None 20 6 6 29 mysql_get_host_info const char mysql_get_host_info MYSQL mysql Description Returns a string describing the type of connection in use includi...

Страница 2179: ...of the server as an integer Return Values A number that represents the MySQL server version in this format major_version 10000 minor_version 100 sub_version For example 5 0 12 is returned as 50012 This function is useful in client programs for quickly determining whether some version specific server capability exists Errors None 20 6 6 33 mysql_get_ssl_cipher const char mysql_get_ssl_cipher MYSQL ...

Страница 2180: ...X The caller must supply whichever of those is desired Example char query 1000 end end strmov query INSERT INTO test_table values end strmov end 0x end mysql_hex_string end What is this 12 end strmov end 0x end mysql_hex_string end binary data 0 r n 16 end if mysql_real_query mysql query unsigned int end query fprintf stderr Failed to insert row Error s n mysql_error mysql The strmov function used...

Страница 2181: ...tion Allocates or initializes a MYSQL object suitable for mysql_real_connect If mysql is a NULL pointer the function allocates initializes and returns a new object Otherwise the object is initialized and the address of the object is returned If mysql_init allocates a new object it is freed when mysql_close is called to close the connection Return Values An initialized MYSQL handle NULL if there wa...

Страница 2182: ...The value of mysql_insert_id is not affected by statements such as SELECT that return a result set The value of mysql_insert_id is affected only by statements issued within the current client connection It is not affected by statements issued by other clients The LAST_INSERT_ID 961 SQL function returns the most recently generated AUTO_INCREMENT value and is not reset between statements because the...

Страница 2183: ...r application linked against the libmysqld library by using the lmysqld flag mysql_library_end shuts down the embedded server and then cleans up For usage information see Section 20 6 5 C API Function Overview and Section 20 6 6 40 mysql_library_init mysql_library_end was added in MySQL 5 0 3 For older versions of MySQL call mysql_server_end instead 20 6 6 40 mysql_library_init int mysql_library_i...

Страница 2184: ...uld not initialize MySQL library n exit 1 Use any MySQL API functions here mysql_library_end return EXIT_SUCCESS When arguments are to be passed argc is greater than 0 the first element of argv is ignored it typically contains the program name mysql_library_init makes a copy of the arguments so it is safe to destroy argv or groups after the call For embedded applications if you want to connect to ...

Страница 2185: ...cess NULL if an error occurred Errors CR_COMMANDS_OUT_OF_SYNC 2942 Commands were executed in an improper order CR_OUT_OF_MEMORY 2942 Out of memory CR_SERVER_GONE_ERROR 2942 The MySQL server has gone away CR_SERVER_LOST 2942 The connection to the server was lost during the query CR_UNKNOWN_ERROR 2941 An unknown error occurred 20 6 6 42 mysql_list_fields MYSQL_RES mysql_list_fields MYSQL mysql const...

Страница 2186: ...on as that reported by mysqladmin processlist or a SHOW PROCESSLIST query You must free the result set with mysql_free_result Return Values A MYSQL_RES result set for success NULL if an error occurred Errors CR_COMMANDS_OUT_OF_SYNC 2942 Commands were executed in an improper order CR_SERVER_GONE_ERROR 2942 The MySQL server has gone away CR_SERVER_LOST 2942 The connection to the server was lost duri...

Страница 2187: ... which can return multiple result sets mysql_more_results true if more results exist from the currently executed statement in which case the application must call mysql_next_result to fetch the results Return Values TRUE 1 if more results exist FALSE 0 if no more results exist In most cases you can call mysql_next_result instead to test whether more results exist and initiate retrieval if so See S...

Страница 2188: ...he CLIENT_MULTI_RESULTS flag itself or implicitly by passing CLIENT_MULTI_STATEMENTS which also enables CLIENT_MULTI_RESULTS It is also possible to test whether there are more results by calling mysql_more_results However this function does not change the connection state so if it returns true you must still call mysql_next_result to advance to the next result For an example that shows how to use ...

Страница 2189: ...t num_rows if mysql_query mysql query_string error else query succeeded process any data returned by it result mysql_store_result mysql if result there are rows num_fields mysql_num_fields result retrieve rows then call mysql_free_result result else mysql_store_result returned nothing should it have if mysql_errno mysql fprintf stderr Error s n mysql_error mysql else if mysql_field_count mysql 0 q...

Страница 2190: ...s linked against the libmysqld embedded server library and are unused for applications linked against the libmysqlclient client library For option descriptions that indicate arg is unused its value is irrelevant it is conventional to pass 0 MYSQL_INIT_COMMAND argument type char SQL statement to execute when connecting to the MySQL server Automatically re executed if reconnection occurs MYSQL_OPT_C...

Страница 2191: ...s not necessary as of 5 0 19 Call mysql_options only before mysql_real_connect as usual MYSQL_OPT_SSL_VERIFY_SERVER_CERT argument type my_bool Enable or disable verification of the server s Common Name value in its certificate against the host name used when connecting to the server The connection is rejected if there is a mismatch This feature can be used to prevent man in the middle attacks Veri...

Страница 2192: ...ed against the libmysqlclient client library MYSQL_SHARED_MEMORY_BASE_NAME argument type char The name of the shared memory object for communication to the server on Windows if the server supports shared memory connections Specify the same value as the shared memory base name 420 option used for the mysqld server you want to connect to The client group is always read if you use MYSQL_READ_DEFAULT_...

Страница 2193: ...ficate Authority directory ssl cert file_name Certificate file ssl cipher cipher_list Permissible SSL ciphers ssl key file_name Key file timeout seconds Like connect timeout user Default user timeout has been replaced by connect timeout but timeout is still supported in MySQL 5 0 for backward compatibility For more information about option files see Section 4 2 3 3 Using Option Files Return Values...

Страница 2194: ... Section 20 6 14 Controlling Automatic Reconnection Behavior Return Values Zero if the connection to the server is active Nonzero if an error occurred A nonzero return does not indicate whether the MySQL server itself is down the connection might be broken for other reasons such as network problems Errors CR_COMMANDS_OUT_OF_SYNC 2942 Commands were executed in an improper order CR_SERVER_GONE_ERROR...

Страница 2195: ... be either a host name or an IP address If host is NULL or the string localhost a connection to the local host is assumed For Windows the client connects using a shared memory connection if the server has shared memory connections enabled Otherwise TCP IP is used For Unix the client connects using a Unix socket file For local connections you can also influence the type of connection to use with th...

Страница 2196: ... handler that the application has already installed CLIENT_IGNORE_SPACE Permit spaces after function names Makes all functions names reserved words CLIENT_INTERACTIVE Permit interactive_timeout 457 seconds instead of wait_timeout 506 seconds of inactivity before closing the connection The client s session wait_timeout 506 variable is set to the value of the session interactive_timeout 457 variable...

Страница 2197: ...Section 20 6 15 C API Support for Multiple Statement Execution For some parameters it is possible to have the value taken from an option file rather than from an explicit value in the mysql_real_connect call To do this call mysql_options with the MYSQL_READ_DEFAULT_FILE or MYSQL_READ_DEFAULT_GROUP option before calling mysql_real_connect Then in the mysql_real_connect call specify the no value val...

Страница 2198: ...YSQL mysql mysql_init mysql mysql_options mysql MYSQL_READ_DEFAULT_GROUP your_prog_name if mysql_real_connect mysql host user passwd database 0 NULL 0 fprintf stderr Failed to connect to database Error s n mysql_error mysql By using mysql_options the MySQL library reads the client and your_prog_name sections in the my cnf file which ensures that your program works even if someone has set up MySQL ...

Страница 2199: ... to be encoded as using two bytes and you need room for the terminating null byte When mysql_real_escape_string returns the contents of to is a null terminated string The return value is the length of the encoded string not including the terminating null character If you need to change the character set of the connection use the mysql_set_character_set function rather than executing a SET NAMES or...

Страница 2200: ...d_count to check for this See Section 20 6 6 22 mysql_field_count Return Values Zero if the statement was successful Nonzero if an error occurred Errors CR_COMMANDS_OUT_OF_SYNC 2942 Commands were executed in an improper order CR_SERVER_GONE_ERROR 2942 The MySQL server has gone away CR_SERVER_LOST 2942 The connection to the server was lost during the query CR_UNKNOWN_ERROR 2941 An unknown error occ...

Страница 2201: ...F_SYNC 2942 Commands were executed in an improper order CR_SERVER_GONE_ERROR 2942 The MySQL server has gone away CR_SERVER_LOST 2942 The connection to the server was lost during the query CR_UNKNOWN_ERROR 2941 An unknown error occurred 20 6 6 56 mysql_reload int mysql_reload MYSQL mysql Description Asks the MySQL server to reload the grant tables The connected user must have the RELOAD 577 privile...

Страница 2202: ... 20 6 6 58 mysql_row_seek MYSQL_ROW_OFFSET mysql_row_seek MYSQL_RES result MYSQL_ROW_OFFSET offset Description Sets the row cursor to an arbitrary row in a query result set The offset value is a row offset typically a value returned from mysql_row_tell or from mysql_row_seek This value is not a row number to seek to a row within a result set by number use mysql_data_seek instead This function requ...

Страница 2203: ...error occurred Errors CR_COMMANDS_OUT_OF_SYNC 2942 Commands were executed in an improper order CR_SERVER_GONE_ERROR 2942 The MySQL server has gone away CR_SERVER_LOST 2942 The connection to the server was lost during the query CR_UNKNOWN_ERROR 2941 An unknown error occurred 20 6 6 61 mysql_set_character_set int mysql_set_character_set MYSQL mysql const char csname Description This function is used...

Страница 2204: ...or void char unsigned int void userdata Description This function installs callbacks to be used during the execution of LOAD DATA LOCAL INFILE statements It enables application programs to exert control over local client side data file reading The arguments are the connection handler a set of pointers to callback functions and a pointer to a data area that the callbacks can use to share informatio...

Страница 2205: ... error number Typically the other callbacks store the error message in the data structure pointed to by ptr so that local_infile_error can copy the message from there into error_msg After calling mysql_set_local_infile_handler in your C code and passing pointers to your callback functions you can then issue a LOAD DATA LOCAL INFILE statement for example by using mysql_query The client library auto...

Страница 2206: ...utdown int mysql_shutdown MYSQL mysql enum mysql_enum_shutdown_level shutdown_level Description Asks the database server to shut down The connected user must have the SHUTDOWN 578 privilege The shutdown_level argument was added in MySQL 5 0 1 MySQL 5 0 servers support only one type of shutdown shutdown_level must be equal to SHUTDOWN_DEFAULT Additional shutdown levels are planned to make it possib...

Страница 2207: ...t fails mysql_sqlstate might not return a useful value For example this happens if a host is blocked by the server and the connection is closed without any SQLSTATE value being sent to the client Return Values A null terminated character string containing the SQLSTATE error code See Also See Section 20 6 6 14 mysql_errno Section 20 6 6 15 mysql_error and Section 20 6 10 26 mysql_stmt_sqlstate 20 6...

Страница 2208: ...tore_result or mysql_use_result for every statement that successfully produces a result set SELECT SHOW DESCRIBE EXPLAIN CHECK TABLE and so forth You must also call mysql_free_result after you are done with the result set You don t have to call mysql_store_result or mysql_use_result for other statements but it does not do any harm or cause any notable performance degradation if you call mysql_stor...

Страница 2209: ...ection 20 6 13 1 Why mysql_store_result Sometimes Returns NULL After mysql_query Returns Success Return Values A MYSQL_RES result structure with the results NULL 0 if an error occurred Errors mysql_store_result resets mysql_error and mysql_errno if it succeeds CR_COMMANDS_OUT_OF_SYNC 2942 Commands were executed in an improper order CR_OUT_OF_MEMORY 2942 Out of memory CR_SERVER_GONE_ERROR 2942 The ...

Страница 2210: ... use mysql_use_result if you are doing a lot of processing for each row on the client side or if the output is sent to a screen on which the user may type a S stop scroll This ties up the server and prevent other threads from updating any tables from which the data is being fetched When using mysql_use_result you must execute mysql_fetch_row until a NULL value is returned otherwise the unfetched r...

Страница 2211: ...ation function Prepared execution is faster than direct execution for statements executed more than once primarily because the query is parsed only once In the case of direct execution the query is parsed every time it is executed Prepared execution also can provide a reduction of network traffic because for each execution of the prepared statement it is necessary only to send the data for the par...

Страница 2212: ...ata values sent to the server and output result values returned from the server For input use MYSQL_BIND structures with mysql_stmt_bind_param to bind parameter data values to buffers for use by mysql_stmt_execute For output use MYSQL_BIND structures with mysql_stmt_bind_result to bind buffers to result set columns for use in fetching rows with mysql_stmt_fetch To use a MYSQL_BIND structure zero i...

Страница 2213: ... bytes This indicates the maximum amount of data that can be stored in the buffer For character and binary C data the buffer_length value specifies the length of buffer when used with mysql_stmt_bind_param to specify input values or the maximum number of output data bytes that can be fetched into the buffer when used with mysql_stmt_bind_result unsigned long length A pointer to an unsigned long va...

Страница 2214: ... to the C language variable on the client side It indicates nothing about the signedness of the corresponding SQL value on the server side For example if you use an int variable to supply a value for a BIGINT UNSIGNED column is_unsigned should be false because int is a signed type If you use an unsigned int variable to supply a value for a BIGINT column is_unsigned should be true because unsigned ...

Страница 2215: ...hows the C variable types that you can use the corresponding type codes and the SQL data types for which the supplied value can be used without conversion Choose the buffer_type value according to the data type of the C language variable that you are binding For the integer types you should also set the is_unsigned member to indicate whether the variable is signed or unsigned Input Variable C Type...

Страница 2216: ...MYSQL_TYPE_DATE MYSQL_TIME DATETIME MYSQL_TYPE_DATETIME MYSQL_TIME TIMESTAMP MYSQL_TYPE_TIMESTAMP MYSQL_TIME CHAR BINARY MYSQL_TYPE_STRING char VARCHAR VARBINARY MYSQL_TYPE_VAR_STRING char TINYBLOB TINYTEXT MYSQL_TYPE_TINY_BLOB char BLOB TEXT MYSQL_TYPE_BLOB char MEDIUMBLOB MEDIUMTEXT MYSQL_TYPE_MEDIUM_BLOB char LONGBLOB LONGTEXT MYSQL_TYPE_LONG_BLOB char BIT MYSQL_TYPE_BIT char 20 6 8 2 C API Pre...

Страница 2217: ...ing the prepared statement with mysql_stmt_execute The metadata provides access to the type codes for the result set as described in Section 20 6 10 22 mysql_stmt_result_metadata and Section 20 6 4 C API Data Structures To determine whether output string values in a result set returned from the server contain binary or nonbinary data check whether the charsetnr value of the result set metadata is ...

Страница 2218: ...rently this function does nothing mysql_stmt_prepare Prepares an SQL statement string for execution mysql_stmt_reset Resets the statement buffers in the server mysql_stmt_result_metadata Returns prepared statement metadata in the form of a result set mysql_stmt_row_seek Seeks to a row offset in a statement result set using value returned from mysql_stmt_row_tell mysql_stmt_row_tell Returns the sta...

Страница 2219: ...nd sends the okay status back to the client by assigning a statement ID It also sends total number of parameters a column count and its metadata if it is a result set oriented statement All syntax and semantics of the statement are checked by the server during this call The client uses this statement ID for the further operations so that the server can identify the statement from among its pool of...

Страница 2220: ...hat operate with a MYSQL_STMT structure begin with the prefix mysql_stmt_ To create a MYSQL_STMT handle use the mysql_stmt_init function 20 6 10 1 mysql_stmt_affected_rows my_ulonglong mysql_stmt_affected_rows MYSQL_STMT stmt Description mysql_stmt_affected_rows may be called immediately after executing a statement with mysql_stmt_execute It is like mysql_affected_rows but for prepared statements ...

Страница 2221: ...mysql_stmt_execute is invoked arg can be CURSOR_TYPE_NO_CURSOR the default or CURSOR_TYPE_READ_ONLY STMT_ATTR_PREFETCH_ROWS unsigned long Number of rows to fetch from server at a time when using a cursor arg can be in the range from 1 to the maximum value of unsigned long The default is 1 Note In MySQL 5 0 mysql_stmt_attr_get uses unsigned int not my_bool for STMT_ATTR_UPDATE_MAX_LENGTH This is co...

Страница 2222: ...tement that was passed to mysql_stmt_prepare It uses MYSQL_BIND structures to supply the data bind is the address of an array of MYSQL_BIND structures The client library expects the array to contain one element for each parameter marker that is present in the query Suppose that you prepare the following statement INSERT INTO mytbl VALUES When you bind the parameters the array of MYSQL_BIND structu...

Страница 2223: ...ffect the next time mysql_stmt_fetch is called Suppose that an application binds the columns in a result set and calls mysql_stmt_fetch The client server protocol returns data in the bound buffers Then suppose that the application binds the columns to a different set of buffers The protocol places data into the newly bound buffers when the next call to mysql_stmt_fetch occurs To bind a column an a...

Страница 2224: ...ws stmt 1 This function requires that the statement result set structure contains the entire result of the last executed query so mysql_stmt_data_seek may be used only in conjunction with mysql_stmt_store_result Return Values None Errors None 20 6 10 8 mysql_stmt_errno unsigned int mysql_stmt_errno MYSQL_STMT stmt Description For the statement specified by stmt mysql_stmt_errno returns the error c...

Страница 2225: ... the server replaces the markers with this newly supplied data Statement processing following mysql_stmt_execute depends on the type of statement For an UPDATE DELETE or INSERT the number of changed deleted or inserted rows can be found by calling mysql_stmt_affected_rows For a statement such as SELECT that generates a result set you must call mysql_stmt_fetch to fetch the data prior to calling an...

Страница 2226: ...BLE IF EXISTS test_table define CREATE_SAMPLE_TABLE CREATE TABLE test_table col1 INT col2 VARCHAR 40 col3 SMALLINT col4 TIMESTAMP define INSERT_SAMPLE INSERT INTO test_table col1 col2 col3 VALUES MYSQL_STMT stmt MYSQL_BIND bind 3 my_ulonglong affected_rows int param_count short small_data int int_data char str_data STRING_SIZE unsigned long str_length my_bool is_null if mysql_query mysql DROP_SAMP...

Страница 2227: ..._type MYSQL_TYPE_STRING bind 1 buffer char str_data bind 1 buffer_length STRING_SIZE bind 1 is_null 0 bind 1 length str_length SMALLINT PARAM bind 2 buffer_type MYSQL_TYPE_SHORT bind 2 buffer char small_data bind 2 is_null is_null bind 2 length 0 Bind the buffers if mysql_stmt_bind_param stmt bind fprintf stderr mysql_stmt_bind_param failed n fprintf stderr s n mysql_stmt_error stmt exit 0 Specify...

Страница 2228: ...mysql_stmt_error stmt exit 0 Note For complete examples on the use of prepared statement functions refer to the file tests mysql_client_test c This file can be obtained from a MySQL source distribution or from the Bazaar source repository 20 6 10 11 mysql_stmt_fetch int mysql_stmt_fetch MYSQL_STMT stmt Description mysql_stmt_fetch returns the next row in the result set It can be called only while ...

Страница 2229: ...e allocated To accomplish this you can use these strategies Before invoking mysql_stmt_fetch to retrieve individual rows pass STMT_ATTR_UPDATE_MAX_LENGTH to mysql_stmt_attr_set then invoke mysql_stmt_store_result to buffer the entire result on the client side Setting the STMT_ATTR_UPDATE_MAX_LENGTH attribute causes the maximal length of column values to be indicated by the max_length member of the...

Страница 2230: ...ut the data type is not DATE TIME DATETIME or TIMESTAMP All other unsupported conversion errors are returned from mysql_stmt_bind_result Example The following example demonstrates how to fetch data from a table using mysql_stmt_result_metadata mysql_stmt_bind_result and mysql_stmt_fetch This example expects to retrieve the two rows inserted by the example shown in Section 20 6 10 10 mysql_stmt_exe...

Страница 2231: ..._meta_result fprintf stdout total columns in SELECT statement d n column_count if column_count 4 validate column count fprintf stderr invalid column count returned by MySQL n exit 0 Execute the SELECT query if mysql_stmt_execute stmt fprintf stderr mysql_stmt_execute failed n fprintf stderr s n mysql_stmt_error stmt exit 0 Bind the result buffers for all 4 columns before fetching them memset bind ...

Страница 2232: ...sults n while mysql_stmt_fetch stmt row_count fprintf stdout row d n row_count column 1 fprintf stdout column1 integer if is_null 0 fprintf stdout NULL n else fprintf stdout d ld n int_data length 0 column 2 fprintf stdout column2 string if is_null 1 fprintf stdout NULL n else fprintf stdout s ld n str_data length 1 column 3 fprintf stdout column3 smallint if is_null 2 fprintf stdout NULL n else f...

Страница 2233: ... at which to begin retrieving data This can be used for fetching the data value in pieces The beginning of the value is offset 0 Return Values Zero if the value was fetched successfully Nonzero if an error occurred Errors CR_INVALID_PARAMETER_NO 2944 Invalid column number CR_NO_DATA 2945 The end of the result set has already been reached 20 6 10 13 mysql_stmt_field_count unsigned int mysql_stmt_fi...

Страница 2234: ... NULL if out of memory Errors CR_OUT_OF_MEMORY 2942 Out of memory 20 6 10 16 mysql_stmt_insert_id my_ulonglong mysql_stmt_insert_id MYSQL_STMT stmt Description Returns the value generated for an AUTO_INCREMENT column by the prepared INSERT or UPDATE statement Use this function after you have executed a prepared INSERT statement on a table which contains an AUTO_INCREMENT field See Section 20 6 6 3...

Страница 2235: ...sql_stmt_param_count MYSQL_STMT stmt Description Returns the number of parameter markers present in the prepared statement Return Values An unsigned long integer representing the number of parameters in a statement Errors None Example See the Example in Section 20 6 10 10 mysql_stmt_execute 20 6 10 19 mysql_stmt_param_metadata MYSQL_RES mysql_stmt_param_metadata MYSQL_STMT stmt This function curre...

Страница 2236: ...nt Return Values Zero if the statement was prepared successfully Nonzero if an error occurred Errors CR_COMMANDS_OUT_OF_SYNC 2942 Commands were executed in an improper order CR_OUT_OF_MEMORY 2942 Out of memory CR_SERVER_GONE_ERROR 2942 The MySQL server has gone away CR_SERVER_LOST 2942 The connection to the server was lost during the query CR_UNKNOWN_ERROR 2941 An unknown error occurred If the pre...

Страница 2237: ...of fields and individual field information This result set pointer can be passed as an argument to any of the field based API functions that process result set metadata such as mysql_num_fields mysql_fetch_field mysql_fetch_field_direct mysql_fetch_fields mysql_field_count mysql_field_seek mysql_field_tell mysql_free_result The result set structure should be freed when you are done with it which y...

Страница 2238: ...Return Values The previous value of the row cursor This value may be passed to a subsequent call to mysql_stmt_row_seek Errors None 20 6 10 24 mysql_stmt_row_tell MYSQL_ROW_OFFSET mysql_stmt_row_tell MYSQL_STMT stmt Description Returns the current position of the row cursor for the last mysql_stmt_fetch This value can be used as an argument to mysql_stmt_row_seek You should use mysql_stmt_row_tell...

Страница 2239: ...er does not have a string or binary type CR_COMMANDS_OUT_OF_SYNC 2942 Commands were executed in an improper order CR_SERVER_GONE_ERROR 2942 The MySQL server has gone away CR_OUT_OF_MEMORY 2942 Out of memory CR_UNKNOWN_ERROR 2941 An unknown error occurred Example The following example demonstrates how to send the data for a TEXT column in chunks It inserts the data value MySQL The most popular Open...

Страница 2240: ...ns a null terminated string containing the SQLSTATE error code for the most recently invoked prepared statement API function that can succeed or fail The error code consists of five characters 00000 means no error The values are specified by ANSI SQL and ODBC For a list of possible values see Appendix C Errors Error Codes and Common Problems Note that not all MySQL errors are yet mapped to SQLSTAT...

Страница 2241: ...slow down mysql_stmt_store_result considerably and most applications don t need max_length If you want max_length to be updated you can call mysql_stmt_attr_set MYSQL_STMT STMT_ATTR_UPDATE_MAX_LENGTH flag to enable this See Section 20 6 10 3 mysql_stmt_attr_set Return Values Zero if the results are buffered successfully Nonzero if an error occurred Errors CR_COMMANDS_OUT_OF_SYNC 2942 Commands were...

Страница 2242: ...on needs to be called before calling pthread_exit to free memory allocated by mysql_thread_init mysql_thread_end is not invoked automatically by the client library It must be called explicitly to avoid a memory leak Return Values None 20 6 11 3 mysql_thread_init my_bool mysql_thread_init void Description This function must be called early within each created thread to initialize thread specific va...

Страница 2243: ...a MySQL C API library no matter whether the application uses libmysqlclient or libmysqld 20 6 12 1 mysql_server_init int mysql_server_init int argc char argv char groups Description This function initializes the MySQL library which must be done before you call any other MySQL function As of MySQL 5 0 3 mysql_server_init is deprecated and you should call mysql_library_init instead See Section 20 6 ...

Страница 2244: ...he format of the string that it returns mysql_info returns a NULL pointer if there is no additional information 20 6 13 3 How to Get the Unique ID for the Last Inserted Row If you insert a record into a table that contains an AUTO_INCREMENT column you can obtain the value stored into that column by calling the mysql_insert_id function You can check from your C applications whether a value was stor...

Страница 2245: ...it or take action to adjust for the loss of state information be sure that auto reconnect is disabled To ensure this call mysql_options with the MYSQL_OPT_RECONNECT option my_bool reconnect 0 mysql_options mysql MYSQL_OPT_RECONNECT reconnect In MySQL 5 0 auto reconnect was enabled by default until MySQL 5 0 3 and disabled by default thereafter The MYSQL_OPT_RECONNECT option is available as of MySQ...

Страница 2246: ...support multiple result processing the C API includes the mysql_more_results and mysql_next_result functions These functions are used at the end of a loop that iterates as long as more results are available Failure to process the result this way may result in a dropped connection to the server Multiple result processing also is required if you execute CALL statements for stored procedures Results ...

Страница 2247: ...real_connect to fully enable multiple statement execution and multiple result processing 2 After calling mysql_query or mysql_real_query and verifying that it succeeds enter a loop within which you process statement results 3 For each iteration of the loop handle the current statement result retrieving either a result set or an affected rows count If an error occurs exit the loop 4 At the end of t...

Страница 2248: ...holders See Section 8 6 3 1 How the Query Cache Operates Prepared statements do not support multi statements that is multiple statements within a single string separated by characters In MySQL 5 0 prepared CALL statements cannot invoke stored procedures that return result sets because prepared statements do not support multiple result sets Nor can the calling application access a stored procedure ...

Страница 2249: ...andle MYSQL_TIME ts MYSQL_BIND bind 3 MYSQL_STMT stmt strmov query INSERT INTO test_table date_field time_field timestamp_field VALUES stmt mysql_stmt_init mysql if stmt fprintf stderr mysql_stmt_init out of memory n exit 0 if mysql_stmt_prepare mysql query strlen query fprintf stderr n mysql_stmt_prepare INSERT failed fprintf stderr n s mysql_stmt_error stmt exit 0 set up input buffers for all 3 ...

Страница 2250: ...l likely configure the MySQL server to set the old_passwords 480 system variable to 1 see Section C 5 2 4 Client does not support authentication protocol This extension is deprecated as of PHP 5 5 0 and its use is highly discouraged All users are encouraged to migrate to either mysqli or PDO_MySQL For further information see Section 20 7 1 3 Choosing an API The PHP distribution and documentation a...

Страница 2251: ... of database server The driver may also call a library such as the MySQL Client Library or the MySQL Native Driver These libraries implement the low level protocol used to communicate with the MySQL database server By way of an example the PHP Data Objects PDO 2309 database abstraction layer may use one of several database specific drivers One of the drivers it has available is the PDO MYSQL drive...

Страница 2252: ...ither the mysqli or PDO_MySQL extensions It is not recommended to use the old mysql extension for new development as it has been deprecated as of PHP 5 5 0 and will be removed in the future A detailed feature comparison matrix is provided below The overall performance of all three extensions is considered to be about the same Although the performance of the extension contributes only a fraction of...

Страница 2253: ...ation for additional details and a listing of features and functionality that it offers Example 20 14 Configure commands for using mysqlnd or libmysqlclient Recommended compiles with mysqlnd configure with mysqli mysqlnd with pdo mysql mysqlnd with mysql mysqlnd Not recommended compiles with libmysqlclient configure with mysqli path to mysql_config with pdo mysql path to mysql_config with mysql pa...

Страница 2254: ...ySQL Server to PHP in is then kept in the memory of the PHP process This allows additional operations like counting the number of rows and moving seeking the current result pointer It also allows issuing further queries on the same connection while working on the result set The downside of the buffered mode is that larger result sets might require quite a lot memory The memory will be kept occupie...

Страница 2255: ...name world my_user my_pass pdo setAttribute PDO MYSQL_ATTR_USE_BUFFERED_QUERY false uresult pdo query SELECT Name FROM City if uresult while row uresult fetch PDO FETCH_ASSOC echo row Name PHP_EOL Example 20 17 Unbuffered query example mysql php conn mysql_connect localhost my_user my_pass db mysql_select_db world uresult mysql_unbuffered_query SELECT Name FROM City if uresult while row mysql_fetc...

Страница 2256: ...will affect mysqli real_escape_string mysqli set_charset utf8 Below are examples that demonstrate how to properly alter the character set at runtime using each each API Example 20 19 Setting the character set example mysqli php mysqli new mysqli localhost my_user my_password world if mysqli set_charset utf8 printf Error loading character set utf8 s n mysqli error else printf Current character set ...

Страница 2257: ...2 1 2 Installation Copyright 1997 2012 the PHP Documentation Group 2230 For compiling simply use the with mysql DIR configuration option where the optional DIR points to the MySQL installation directory Although this MySQL extension is compatible with MySQL 4 1 0 and greater it doesn t support the extra functionality that these versions provide For that use the MySQLi extension If you would like t...

Страница 2258: ...ow do I add my PHP directory to the PATH on Windows for information on how to do this Although copying libmysql dll to the Windows system directory also works because the system directory is by default in the system s PATH it s not recommended As with enabling any PHP extension such as php_mysql dll the PHP directive extension_dir should be set to the directory where the PHP extensions are located...

Страница 2259: ...For further details and definitions of the PHP_INI_ modes see the http www php net manual en configuration changes modes Here s a short explanation of the configuration directives mysql allow_local_infile integer Allow accessing from PHP s perspective local files with LOAD DATA statements mysql allow_persistent boolean Whether to allow persistent connections to MySQL mysql max_persistent integer T...

Страница 2260: ... first one is the link identifier for a database connection the second a resource which holds the result of a query 20 7 2 2 Changelog Copyright 1997 2012 the PHP Documentation Group 2230 The following changes have been made to classes functions methods of this extension General Changelog for the ext mysql extension This changelog references the ext mysql extension Changes to existing functions Th...

Страница 2261: ... This flag is only available with version 4 x of the MySQL client library or newer Version 3 23 x is bundled both with PHP 4 and Windows binaries of PHP 5 The function mysql_fetch_array uses a constant for the different types of result arrays The following constants are defined Table 20 35 MySQL fetch constants Constant Description MYSQL_ASSOC Columns are returned into the array having the fieldna...

Страница 2262: ...link_identifier as the last optional parameter If it is not provided last opened connection is used If it doesn t exist connection is tried to establish with default parameters defined in php ini If it is not successful functions return FALSE 20 7 2 5 1 mysql_affected_rows Copyright 1997 2012 the PHP Documentation Group 2230 mysql_affected_rows Get number of affected rows in previous MySQL operati...

Страница 2263: ...st deletes the record with the same primary key and then inserts the new record This function returns the number of deleted records plus the number of inserted records In the case of INSERT ON DUPLICATE KEY UPDATE queries the return value will be 1 if an insert was performed or 2 for an update of an existing row Examples Example 20 23 mysql_affected_rows example php link mysql_connect localhost my...

Страница 2264: ...DE in foreign key constraints See Also mysql_num_rows mysql_info 20 7 2 5 2 mysql_client_encoding Copyright 1997 2012 the PHP Documentation Group 2230 mysql_client_encoding Returns the name of the character set Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an API guide and rela...

Страница 2265: ...ose Copyright 1997 2012 the PHP Documentation Group 2230 mysql_close Close MySQL connection Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an API guide and related FAQ for more information Alternatives to this function include mysqli_close PDO Assign the value of NULL to the PDO...

Страница 2266: ... The above example will output Connected successfully Notes Note mysql_close will not close persistent links created by mysql_pconnect See Also mysql_connect mysql_free_result 20 7 2 5 4 mysql_connect Copyright 1997 2012 the PHP Documentation Group 2230 mysql_connect Open a connection to a MySQL Server Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead t...

Страница 2267: ...y password is used new_link If a second call is made to mysql_connect with the same arguments no new link will be established but instead the link identifier of the already opened link will be returned The new_link parameter modifies this behavior and makes mysql_connect always open a new link even if mysql_connect was called before with the same parameters In SQL safe mode this parameter is ignor...

Страница 2268: ...ng path to socket syntax php we connect to localhost and socket e g tmp mysql sock variant 1 omit localhost link mysql_connect tmp mysql mysql_user mysql_password if link die Could not connect mysql_error echo Connected successfully mysql_close link variant 2 with localhost link mysql_connect localhost tmp mysql sock mysql_user mysql_password if link die Could not connect mysql_error echo Connecte...

Страница 2269: ...arning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an API guide and related FAQ for more information Alternatives to this function include mysqli_query PDO query Description bool mysql_create_db string database_name resource link_identifier NULL mysql_create_db attempts to create a n...

Страница 2270: ...imilar to Database my_db created successfully Notes Note For backward compatibility the following deprecated alias may be used mysql_createdb Note This function will not be available if the MySQL extension was built against a MySQL 4 x client library See Also mysql_query mysql_select_db 20 7 2 5 6 mysql_data_seek Copyright 1997 2012 the PHP Documentation Group 2230 mysql_data_seek Move internal re...

Страница 2271: ...to mysql_query row_number The desired row number of the new result pointer Return Values Returns TRUE on success or FALSE on failure Examples Example 20 31 mysql_data_seek example php link mysql_connect localhost mysql_user mysql_password if link die Could not connect mysql_error db_selected mysql_select_db sample_db if db_selected die Could not select database mysql_error query SELECT last_name f...

Страница 2272: ...ated FAQ for more information Alternatives to this function include Query SELECT DATABASE Description string mysql_db_name resource result int row mixed field NULL Retrieve the database name from a call to mysql_list_dbs Parameters result The result pointer from a call to mysql_list_dbs row The index into the result set field The field name Return Values Returns the database name on success and FA...

Страница 2273: ...s deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an API guide and related FAQ for more information Alternatives to this function include mysqli_select_db then the query PDO __construct Description resource mysql_db_query string database string query resource link_identifier NULL mysql_db_query selects a ...

Страница 2274: ...ion Use mysql_select_db and mysql_query instead Examples Example 20 33 mysql_db_query alternative example php if link mysql_connect mysql_host mysql_user mysql_password echo Could not connect to mysql exit if mysql_select_db mysql_dbname link echo Could not select database exit sql SELECT foo FROM bar WHERE id 42 result mysql_query sql link if result echo DB Error could not query the database n ec...

Страница 2275: ...ink identifier This function is deprecated it is preferable to use mysql_query to issue an sql DROP DATABASE statement instead Parameters database_name The name of the database that will be deleted link_identifier The MySQL connection If the link identifier is not specified the last link opened by mysql_connect is assumed If no such link is found it will try to create one as if mysql_connect was c...

Страница 2276: ...orCode Description int mysql_errno resource link_identifier NULL Returns the error number from the last MySQL function Errors coming back from the MySQL database backend no longer issue warnings Instead use mysql_errno to retrieve the error code Note that this function only returns the error code from the most recently executed MySQL function not including mysql_error and mysql_errno so if you wan...

Страница 2277: ...be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an API guide and related FAQ for more information Alternatives to this function include mysqli_error PDO errorInfo Description string mysql_error resource link_identifier NULL Returns the error text from the last MySQL function Errors coming back from the MySQL database backend no longer issue...

Страница 2278: ...ttable doesn t exist See Also mysql_errno MySQL error codes 20 7 2 5 12 mysql_escape_string Copyright 1997 2012 the PHP Documentation Group 2230 mysql_escape_string Escapes a string for use in a mysql_query Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an API guide and related ...

Страница 2279: ...n E_DEPRECATED notice 4 3 0 This function became deprecated do not use this function Instead use mysql_real_escape_string Examples Example 20 37 mysql_escape_string example php item Zak s Laptop escaped_item mysql_escape_string item printf Escaped string s n escaped_item The above example will output Escaped string Zak s Laptop Notes Note mysql_escape_string does not escape and _ See Also mysql_re...

Страница 2280: ...ore rows The type of returned array depends on how result_type is defined By using MYSQL_BOTH default you ll get an array with both associative and number indices Using MYSQL_ASSOC you only get associative indices as mysql_fetch_assoc works using MYSQL_NUM you only get number indices as mysql_fetch_row works If two or more columns of the result have the same field names the last column will take p...

Страница 2281: ...e Could not connect mysql_error mysql_select_db mydb result mysql_query SELECT id name FROM mytable while row mysql_fetch_array result MYSQL_BOTH printf ID s Name s row 0 row name mysql_free_result result Notes Performance An important thing to note is that using mysql_fetch_array is not significantly slower than using mysql_fetch_row while it provides a significant added value Note Field names re...

Страница 2282: ...ource that is being evaluated This result comes from a call to mysql_query Return Values Returns an associative array of strings that corresponds to the fetched row or FALSE if there are no more rows If two or more columns of the result have the same field names the last column will take precedence To access the other column s of the same name you either need to access the result with numeric indi...

Страница 2283: ...icantly slower than using mysql_fetch_row while it provides a significant added value Note Field names returned by this function are case sensitive Note This function sets NULL fields to the PHP NULL value See Also mysql_fetch_row mysql_fetch_array mysql_data_seek mysql_query mysql_error 20 7 2 5 15 mysql_fetch_field Copyright 1997 2012 the PHP Documentation Group 2230 mysql_fetch_field Get column...

Страница 2284: ...lumn name table name of the table the column belongs to which is the alias name if one is defined max_length maximum length of the column not_null 1 if the column cannot be NULL primary_key 1 if the column is a primary key unique_key 1 if the column is a unique key multiple_key 1 if the column is a non unique key numeric 1 if the column is numeric blob 1 if the column is a BLOB type the type of th...

Страница 2285: ... aliased name will be returned The original name can be retrieved for instance by using mysqli_result fetch_field See Also mysql_field_seek 20 7 2 5 16 mysql_fetch_lengths Copyright 1997 2012 the PHP Documentation Group 2230 mysql_fetch_lengths Get the length of each output in a result Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_...

Страница 2286: ...example php result mysql_query SELECT id email FROM people WHERE id 42 if result echo Could not run query mysql_error exit row mysql_fetch_assoc result lengths mysql_fetch_lengths result print_r row print_r lengths The above example will output something similar to Array id 42 email user example com Array 0 2 1 16 See Also mysql_field_len mysql_fetch_row strlen 20 7 2 5 17 mysql_fetch_object Copyr...

Страница 2287: ...the properties of and return If not specified a stdClass object is returned params An optional array of parameters to pass to the constructor for class_name objects Return Values Returns an object with string properties that correspond to the fetched row or FALSE if there are no more rows Changelog Version Description 5 0 0 Added the ability to return as a different object Examples Example 20 45 m...

Страница 2288: ...ction are case sensitive Note This function sets NULL fields to the PHP NULL value See Also mysql_fetch_array mysql_fetch_assoc mysql_fetch_row mysql_data_seek mysql_query 20 7 2 5 18 mysql_fetch_row Copyright 1997 2012 the PHP Documentation Group 2230 mysql_fetch_row Get a result row as an enumerated array Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Inst...

Страница 2289: ... FROM people WHERE id 42 if result echo Could not run query mysql_error exit row mysql_fetch_row result echo row 0 42 echo row 1 the email value Notes Note This function sets NULL fields to the PHP NULL value See Also mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_result 20 7 2 5 19 mysql_field_flags Copyright 1997 2012 the PHP Documentation Group ...

Страница 2290: ...is also issued Return Values Returns a string of flags associated with the result or FALSE on failure The following flags are reported if your version of MySQL is current enough to support them not_null primary_key unique_key multiple_key blob unsigned zerofill binary enum auto_increment and timestamp Examples Example 20 48 A mysql_field_flags example php result mysql_query SELECT id email FROM pe...

Страница 2291: ...ription int mysql_field_len resource result int field_offset mysql_field_len returns the length of the specified field Parameters result The result resource that is being evaluated This result comes from a call to mysql_query field_offset The numerical field offset The field_offset starts at 0 If field_offset does not exist an error of level E_WARNING is also issued Return Values The length of the...

Страница 2292: ...i_fetch_field_direct name or orgname PDOStatement getColumnMeta name Description string mysql_field_name resource result int field_offset mysql_field_name returns the name of the specified field index Parameters result The result resource that is being evaluated This result comes from a call to mysql_query field_offset The numerical field offset The field_offset starts at 0 If field_offset does no...

Страница 2293: ...ql_field_seek Copyright 1997 2012 the PHP Documentation Group 2230 mysql_field_seek Set result pointer to a specified field offset Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an API guide and related FAQ for more information Alternatives to this function include mysqli_field_...

Страница 2294: ...extension should be used See also MySQL choosing an API guide and related FAQ for more information Alternatives to this function include mysqli_fetch_field_direct table or orgtable PDOStatement getColumnMeta table Description string mysql_field_table resource result int field_offset Returns the name of the table that the specified field is in Parameters result The result resource that is being eva...

Страница 2295: ...DO_MySQL extension should be used See also MySQL choosing an API guide and related FAQ for more information Alternatives to this function include mysqli_fetch_field_direct type PDOStatement getColumnMeta driver decl_type or pdo_type Description string mysql_field_type resource result int field_offset mysql_field_type is similar to the mysql_field_name function The arguments are identical but the f...

Страница 2296: ...sql_close The above example will output something similar to Your func table has 4 fields and 1 record s The table has the following fields string name 64 not_null primary_key binary int ret 1 not_null string dl 128 not_null string type 9 not_null enum Notes Note For backward compatibility the following deprecated alias may be used mysql_fieldtype See Also mysql_field_name mysql_field_len 20 7 2 5...

Страница 2297: ...UE on success or FALSE on failure If a non resource is used for the result an error of level E_WARNING will be emitted It s worth noting that mysql_query only returns a resource for SELECT SHOW EXPLAIN and DESCRIBE queries Examples Example 20 53 A mysql_free_result example php result mysql_query SELECT id email FROM people WHERE id 42 if result echo Could not run query mysql_error exit Use the res...

Страница 2298: ...es The MySQL client version Examples Example 20 54 mysql_get_client_info example php printf MySQL client info s n mysql_get_client_info The above example will output something similar to MySQL client info 3 23 39 See Also mysql_get_host_info mysql_get_proto_info mysql_get_server_info 20 7 2 5 27 mysql_get_host_info Copyright 1997 2012 the PHP Documentation Group 2230 mysql_get_host_info Get MySQL ...

Страница 2299: ...tion or FALSE on failure Examples Example 20 55 mysql_get_host_info example php link mysql_connect localhost mysql_user mysql_password if link die Could not connect mysql_error printf MySQL host info s n mysql_get_host_info The above example will output something similar to MySQL host info Localhost via UNIX socket See Also mysql_get_client_info mysql_get_proto_info mysql_get_server_info 20 7 2 5 ...

Страница 2300: ...ql_get_proto_info example php link mysql_connect localhost mysql_user mysql_password if link die Could not connect mysql_error printf MySQL protocol version s n mysql_get_proto_info The above example will output something similar to MySQL protocol version 10 See Also mysql_get_client_info mysql_get_host_info mysql_get_server_info 20 7 2 5 29 mysql_get_server_info Copyright 1997 2012 the PHP Docume...

Страница 2301: ...ilure Examples Example 20 57 mysql_get_server_info example php link mysql_connect localhost mysql_user mysql_password if link die Could not connect mysql_error printf MySQL server version s n mysql_get_server_info The above example will output something similar to MySQL server version 4 0 1 alpha See Also mysql_get_client_info mysql_get_host_info mysql_get_proto_info phpversion 20 7 2 5 30 mysql_i...

Страница 2302: ...ok like Statements that are not listed will return FALSE Examples Example 20 58 Relevant MySQL Statements Statements that return string values The numbers are only for illustrating purpose their values will correspond to the query INSERT INTO SELECT String format Records 23 Duplicates 0 Warnings 0 INSERT INTO VALUES String format Records 37 Duplicates 0 Warnings 0 LOAD DATA INFILE String format Re...

Страница 2303: ...s found or established an E_WARNING level error is generated Return Values The ID generated for an AUTO_INCREMENT column by the previous query on success 0 if the previous query does not generate an AUTO_INCREMENT value or FALSE if no MySQL connection was established Examples Example 20 59 mysql_insert_id example php link mysql_connect localhost mysql_user mysql_password if link die Could not conn...

Страница 2304: ...ore information Alternatives to this function include SQL Query SHOW DATABASES Description resource mysql_list_dbs resource link_identifier NULL Returns a result pointer containing the databases available from the current mysql daemon Warning This function has been DEPRECATED as of PHP 5 4 0 Relying on this function is highly discouraged Parameters link_identifier The MySQL connection If the link ...

Страница 2305: ...tibility the following deprecated alias may be used mysql_listdbs See Also mysql_db_name mysql_select_db 20 7 2 5 33 mysql_list_fields Copyright 1997 2012 the PHP Documentation Group 2230 mysql_list_fields List MySQL table fields Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an...

Страница 2306: ...th no arguments If no connection is found or established an E_WARNING level error is generated Return Values A result pointer resource on success or FALSE on failure The returned result can be used with mysql_field_flags mysql_field_len mysql_field_name and mysql_field_type Examples Example 20 61 Alternate to deprecated mysql_list_fields php result mysql_query SHOW COLUMNS FROM sometable if result...

Страница 2307: ...cription resource mysql_list_processes resource link_identifier NULL Retrieves the current MySQL server threads Parameters link_identifier The MySQL connection If the link identifier is not specified the last link opened by mysql_connect is assumed If no such link is found it will try to create one as if mysql_connect was called with no arguments If no connection is found or established an E_WARNI...

Страница 2308: ...ng database resource link_identifier NULL Retrieves a list of table names from a MySQL database This function is deprecated It is preferable to use mysql_query to issue an SQL SHOW TABLES FROM db_name LIKE pattern statement instead Parameters database The name of the database link_identifier The MySQL connection If the link identifier is not specified the last link opened by mysql_connect is assum...

Страница 2309: ...rd compatibility the following deprecated alias may be used mysql_listtables See Also mysql_list_dbs mysql_tablename 20 7 2 5 36 mysql_num_fields Copyright 1997 2012 the PHP Documentation Group 2230 mysql_num_fields Get number of fields in result Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also ...

Страница 2310: ...num_fields result Notes Note For backward compatibility the following deprecated alias may be used mysql_numfields See Also mysql_select_db mysql_query mysql_fetch_field mysql_num_rows 20 7 2 5 37 mysql_num_rows Copyright 1997 2012 the PHP Documentation Group 2230 mysql_num_rows Get number of rows in result Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Inst...

Страница 2311: ... mysql_password mysql_select_db database link result mysql_query SELECT FROM table1 link num_rows mysql_num_rows result echo num_rows Rows n Notes Note If you use mysql_unbuffered_query mysql_num_rows will not return the correct value until all the rows in the result set have been retrieved Note For backward compatibility the following deprecated alias may be used mysql_numrows See Also mysql_affe...

Страница 2312: ...sed when the execution of the script ends Instead the link will remain open for future use mysql_close will not close links established by mysql_pconnect This type of link is therefore called persistent Parameters server The MySQL server It can also include a port number e g hostname port or a path to a local socket e g path to socket for the localhost If the PHP directive mysql default_host is un...

Страница 2313: ...emoved in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an API guide and related FAQ for more information Alternatives to this function include mysqli_ping Description bool mysql_ping resource link_identifier NULL Checks whether or not the connection to the server is working If it has gone down an automatic reconnection is attempted This function can b...

Страница 2314: ...ion is still alive let s run another query result2 mysql_query sql2 See Also mysql_thread_id mysql_list_processes 20 7 2 5 40 mysql_query Copyright 1997 2012 the PHP Documentation Group 2230 mysql_query Send a MySQL query Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an API gui...

Страница 2315: ...or dealing with result tables to access the returned data Use mysql_num_rows to find out how many rows were returned for a SELECT statement or mysql_affected_rows to find out how many rows were affected by a DELETE INSERT REPLACE or UPDATE statement mysql_query will also fail and return FALSE if the user does not have permission to access the table s referenced by the query Examples Example 20 67 ...

Страница 2316: ...ct mysql_error mysql_real_escape_string mysql_result mysql_fetch_assoc mysql_unbuffered_query 20 7 2 5 41 mysql_real_escape_string Copyright 1997 2012 the PHP Documentation Group 2230 mysql_real_escape_string Escapes special characters in a string for use in an SQL statement Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL exten...

Страница 2317: ...t will try to create one as if mysql_connect was called with no arguments If no connection is found or established an E_WARNING level error is generated Return Values Returns the escaped string or FALSE on error Examples Example 20 69 Simple mysql_real_escape_string example php Connect link mysql_connect mysql_host mysql_user mysql_password OR die mysql_error Query query sprintf SELECT FROM users ...

Страница 2318: ...ape and _ These are wildcards in MySQL if combined with LIKE GRANT or REVOKE See Also mysql_set_charset mysql_client_encoding addslashes stripslashes The magic_quotes_gpc directive The magic_quotes_runtime directive 20 7 2 5 42 mysql_result Copyright 1997 2012 the PHP Documentation Group 2230 mysql_result Get result data Warning This extension is deprecated as of PHP 5 5 0 and will be removed in t...

Страница 2319: ...field name tablename fieldname If the column name has been aliased select foo as bar from use the alias instead of the column name If undefined the first field is retrieved Return Values The contents of one cell from a MySQL result set on success or FALSE on failure Examples Example 20 71 mysql_result example php link mysql_connect localhost mysql_user mysql_password if link die Could not connect ...

Страница 2320: ... on the active database Parameters database_name The name of the database that is to be selected link_identifier The MySQL connection If the link identifier is not specified the last link opened by mysql_connect is assumed If no such link is found it will try to create one as if mysql_connect was called with no arguments If no connection is found or established an E_WARNING level error is generate...

Страница 2321: ...t resource link_identifier NULL Sets the default character set for the current connection Parameters charset A valid character set name link_identifier The MySQL connection If the link identifier is not specified the last link opened by mysql_connect is assumed If no such link is found it will try to create one as if mysql_connect was called with no arguments If no connection is found or establish...

Страница 2322: ...L connection If the link identifier is not specified the last link opened by mysql_connect is assumed If no such link is found it will try to create one as if mysql_connect was called with no arguments If no connection is found or established an E_WARNING level error is generated Return Values Returns a string with the status for uptime threads queries open tables flush tables and queries per seco...

Страница 2323: ...tmpdir var tmp See Also mysql_get_server_info mysql_list_processes 20 7 2 5 46 mysql_tablename Copyright 1997 2012 the PHP Documentation Group 2230 mysql_tablename Get table name of field Warning This extension is deprecated as of PHP 5 5 0 and will be removed in the future Instead the MySQLi or PDO_MySQL extension should be used See also MySQL choosing an API guide and related FAQ for more inform...

Страница 2324: ...mple 20 75 mysql_tablename example php mysql_connect localhost mysql_user mysql_password result mysql_list_tables mydb num_rows mysql_num_rows result for i 0 i num_rows i echo Table mysql_tablename result i n mysql_free_result result Notes Note The mysql_num_rows function may be used to determine the number of tables in the result pointer See Also mysql_list_tables mysql_field_table mysql_db_name ...

Страница 2325: ...as called with no arguments If no connection is found or established an E_WARNING level error is generated Return Values The thread ID on success or FALSE on failure Examples Example 20 76 mysql_thread_id example php link mysql_connect localhost mysql_user mysql_password thread_id mysql_thread_id link if thread_id printf current thread id is d n thread_id The above example will output something si...

Страница 2326: ...d the last link opened by mysql_connect is assumed If no such link is found it will try to create one as if mysql_connect was called with no arguments If no connection is found or established an E_WARNING level error is generated Return Values For SELECT SHOW DESCRIBE or EXPLAIN statements mysql_unbuffered_query returns a resource on success or FALSE on error For other type of SQL statements UPDAT...

Страница 2327: ...and how to select the best solution for your application What is a Connector In the MySQL documentation the term connector refers to a piece of software that allows your application to connect to the MySQL database server MySQL provides connectors for a variety of languages including PHP If your PHP application needs to communicate with a database server you will need to write PHP code to perform ...

Страница 2328: ...d disadvantages The following discussion aims to give a brief introduction to the key aspects of each API What is PHP s MySQL Extension This is the original extension designed to allow you to develop PHP applications that interact with a MySQL database The mysql extension provides a procedural interface and is intended for use only with MySQL versions older than 4 1 3 This extension can be used wi...

Страница 2329: ... PHP extension framework its source code is located in the directory ext pdo For further information on PDO see the http www php net book pdo What is the PDO MYSQL driver The PDO MYSQL driver is not an API as such at least from the PHP programmer s perspective In fact the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL specific functionality The programmer still calls the PD...

Страница 2330: ...on introduced 5 0 5 0 Prior to 3 0 Included with PHP 5 x yes yes Yes MySQL development status Active development Active development as of PHP 5 3 Maintenance only Recommended by MySQL for new projects Yes preferred option Yes No API supports Charsets Yes Yes No API supports server side Prepared Statements Yes Yes No API supports client side Prepared Statements No Yes No API supports Stored Procedu...

Страница 2331: ... example will output Please do not use the mysql extension for new developments The object oriented interface In addition to the classical procedural interface users can choose to use the object oriented interface The documentation is organized using the object oriented interface The object oriented interface shows functions grouped by their purpose making it easier to get started The reference se...

Страница 2332: ...es echo Failed to run query mysqli errno mysqli error if row res fetch_assoc echo row _msg The above example will output Possible but bad style See also mysqli __construct mysqli query mysqli_result fetch_assoc mysqli connect_errno mysqli connect_error mysqli errno mysqli error The MySQLi Extension Function Summary 20 7 3 3 2 Connections Copyright 1997 2012 the PHP Documentation Group 2230 The MyS...

Страница 2333: ...ent library detects empty or unset parameters then it may default to the library built in values Built in connection library defaults If the host value is unset or empty then the client library will default to a Unix socket connection on localhost If socket is unset or empty and a Unix socket connection is requested then a connection to the default socket on tmp mysql sock is attempted On Windows ...

Страница 2334: ...ith mysqli max_persistent Please note that the web server may spawn many PHP processes A common complain about persistent connections is that their state is not reset before reuse For example open and unfinished transactions are not automatically rolled back But also authorization changes which happened in the time between putting the connection into the pool and reusing it are not reflected This ...

Страница 2335: ... clients are slow consuming result sets Therefore it is recommended to use buffered result sets mysqli_query combines statement execution and result set buffering PHP applications can navigate freely through buffered results Navigation is fast because the result sets are held in client memory Please keep in mind that it is often easier to scale by client than it is to scale the server Example 20 8...

Страница 2336: ...e used for statement execution With the text protocol the MySQL server converts all data of a result sets into strings before sending This conversion is done regardless of the SQL result set column data type The mysql client libraries receive all column values as strings No further client side casting is done to convert columns back to their native types Instead all values are provided as PHP stri...

Страница 2337: ...nect to MySQL mysqli connect_errno mysqli connect_error if mysqli query DROP TABLE IF EXISTS test mysqli query CREATE TABLE test id INT label CHAR 1 mysqli query INSERT INTO test id label VALUES 1 a echo Table creation failed mysqli errno mysqli error res mysqli query SELECT id label FROM test WHERE id 1 row res fetch_assoc printf id s s n row id gettype row id printf label s s n row label gettype...

Страница 2338: ...s parameter values and sends them to the server The server creates a statement from the statement template and the bound values to execute it using the previously created internal resources Example 20 88 Second stage bind and execute php Prepared statement stage 2 bind and execute id 1 if stmt bind_param i id echo Binding parameters failed stmt errno stmt error if stmt execute echo Execute failed ...

Страница 2339: ...l The above example will output array 4 0 array 1 0 string 1 1 1 array 1 0 string 1 2 2 array 1 0 string 1 3 3 array 1 0 string 1 4 Every prepared statement occupies server resources Statements should be closed explicitly immediately after use If not done explicitly the statement will be closed when the statement handle is freed by PHP Using a prepared statement is not always the most efficient wa...

Страница 2340: ...ho Failed to connect to MySQL mysqli connect_errno mysqli connect_error if mysqli query DROP TABLE IF EXISTS test mysqli query CREATE TABLE test id INT label CHAR 1 mysqli query INSERT INTO test id label VALUES 1 a echo Table creation failed mysqli errno mysqli error stmt mysqli prepare SELECT id label FROM test WHERE id 1 stmt execute res stmt get_result row res fetch_assoc printf id s s n row id...

Страница 2341: ...fetched and transferred from the server to the client for client side buffering The result set takes server resources until all results have been fetched by the client Thus it is recommended to consume results timely If a client fails to fetch all results or the client closes the statement before having fetched all data the data has to be fetched implicitly by mysqli It is also possible to buffer ...

Страница 2342: ...li example com user password database if mysqli connect_errno echo Failed to connect to MySQL mysqli connect_errno mysqli connect_error if mysqli query DROP TABLE IF EXISTS test mysqli query CREATE TABLE test id INT label CHAR 1 mysqli query INSERT INTO test id label VALUES 1 a 2 b 3 c echo Table creation failed mysqli errno mysqli error if stmt mysqli prepare SELECT id label FROM test echo Prepar...

Страница 2343: ... prepared statement emulation The API does not include emulation for client side prepared statement emulation Quick prepared non prepared statement comparison The table below compares server side prepared and non prepared statements Table 20 37 Comparison of prepared and non prepared statements Prepared Statement Non prepared statement Client server round trips SELECT single execution 2 1 Statemen...

Страница 2344: ...re The CALL SQL statement is used to execute a stored procedure Parameter Stored procedures can have IN INOUT and OUT parameters depending on the MySQL version The mysqli interface has no special notion for the different kinds of parameters IN parameter Input parameters are provided with the CALL statement Please make sure values are escaped correctly Example 20 95 Calling a stored procedure php m...

Страница 2345: ...sqli errno mysqli error if res mysqli query SELECT msg as _p_out echo Fetch failed mysqli errno mysqli error row res fetch_assoc echo row _p_out The above example will output Hi Application and framework developers may be able to provide a more convenient API using a mix of session variables and databased catalog inspection However please note the possible performance impact of a custom solution b...

Страница 2346: ... IF EXISTS test mysqli query CREATE TABLE test id INT mysqli query INSERT INTO test id VALUES 1 2 3 echo Table creation failed mysqli errno mysqli error if mysqli query DROP PROCEDURE IF EXISTS p mysqli query CREATE PROCEDURE p READS SQL DATA BEGIN SELECT id FROM test SELECT id 1 FROM test END echo Stored procedure creation failed mysqli errno mysqli error if mysqli multi_query CALL p echo CALL fa...

Страница 2347: ...qli query DROP TABLE IF EXISTS test mysqli query CREATE TABLE test id INT mysqli query INSERT INTO test id VALUES 1 2 3 echo Table creation failed mysqli errno mysqli error if mysqli query DROP PROCEDURE IF EXISTS p mysqli query CREATE PROCEDURE p READS SQL DATA BEGIN SELECT id FROM test SELECT id 1 FROM test echo Stored procedure creation failed mysqli errno mysqli error if stmt mysqli prepare CA...

Страница 2348: ...lti queries must be executed with mysqli_multi_query The individual statements of the statement string are separated by semicolon Then all result sets returned by the executed statements must be fetched The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement Example 20 100 Multiple Statements php mysqli new mysqli...

Страница 2349: ...r succeeds in adding SQL to the statement string but mysqli_multi_query is not used the server will not execute the second injected and malicious SQL statement Example 20 101 SQL Injection php mysqli new mysqli example com user password database res mysqli query SELECT 1 DROP TABLE mysql user if res echo Error executing query mysqli errno mysqli error The above example will output Error executing ...

Страница 2350: ...SET AUTOCOMMIT 0 echo Query failed mysqli errno mysqli error Optional feature packages such as the replication and load balancing plugin can easily monitor API calls The replication plugin offers transaction aware load balancing if transactions are controlled with API calls Transaction aware load balancing is not available if SQL statements are used for setting auto commit mode committing or rolli...

Страница 2351: ...o MySQL mysqli connect_errno mysqli connect_error res mysqli query SELECT 1 AS _one Hello AS _two FROM DUAL var_dump res fetch_fields The above example will output array 2 0 object stdClass 3 13 name string 4 _one orgname string 0 table string 0 orgtable string 0 def string 0 db string 0 catalog string 3 def max_length int 1 length int 1 charsetnr int 63 flags int 32897 type int 8 decimals int 0 1...

Страница 2352: ...irements Copyright 1997 2012 the PHP Documentation Group 2230 In order to have these functions available you must compile PHP with support for the mysqli extension Note The mysqli extension is designed to work with MySQL version 4 1 13 or newer or 5 0 7 or newer For previous versions please see the MySQL extension documentation 20 7 3 4 2 Installation Copyright 1997 2012 the PHP Documentation Grou...

Страница 2353: ...t with mysqli mysqlnd with mysqli path to mysql_config mysqlnd is now supported 5 4 x mysqlnd with mysqli with mysqli path to mysql_config mysqlnd is now the default Note that it is possible to freely mix MySQL extensions and client libraries For example it is possible to enable the MySQL extension to use the MySQL Client Library libmysqlclient while configuring the mysqli extension to use the MyS...

Страница 2354: ...ext Note If when starting the web server an error similar to the following occurs Unable to load dynamic library php_mysqli dll this is because php_mysqli dll and or libmysql dll cannot be found by the system 20 7 3 4 2 2 2 PHP 5 3 0 Copyright 1997 2012 the PHP Documentation Group 2230 On Windows for PHP versions 5 3 and newer the mysqli extension is enabled and uses the MySQL Native Driver by def...

Страница 2355: ... a local database server if no other socket name is specified mysqli default_host string The default server host to use when connecting to the database server if no other host is specified Doesn t apply in safe mode mysqli default_user string The default user name to use when connecting to the database server if no other name is specified Doesn t apply in safe mode mysqli default_pw string The def...

Страница 2356: ...ersistent connections are in a clean state on return from the connection pool before the client process uses them The mysqli extension does this cleanup by automatically calling the C API function mysql_change_user The automatic cleanup feature has advantages and disadvantages though The advantage is that the programmer no longer needs to worry about adding cleanup code as it is called automatical...

Страница 2357: ...g unbuffered resultsets MYSQLI_ASSOC Columns are returned into the array having the fieldname as the array index MYSQLI_NUM Columns are returned into the array having an enumerated index MYSQLI_BOTH Columns are returned into the array having both a numerical index and the fieldname as the associative index MYSQLI_NOT_NULL_FLAG Indicates that a field is defined as NOT NULL MYSQLI_PRI_KEY_FLAG Field...

Страница 2358: ...L Field is defined as INTERVAL MYSQLI_TYPE_ENUM Field is defined as ENUM MYSQLI_TYPE_SET Field is defined as SET MYSQLI_TYPE_TINY_BLOB Field is defined as TINYBLOB MYSQLI_TYPE_MEDIUM_BLOB Field is defined as MEDIUMBLOB MYSQLI_TYPE_LONG_BLOB Field is defined as LONGBLOB MYSQLI_TYPE_BLOB Field is defined as BLOB MYSQLI_TYPE_VAR_STRING Field is defined as VARCHAR MYSQLI_TYPE_STRING Field is defined a...

Страница 2359: ...HOSTS SQL statement MYSQLI_REFRESH_STATUS Reset the status variables like executing the FLUSH STATUS SQL statement MYSQLI_REFRESH_THREADS Flushes the thread cache MYSQLI_REFRESH_SLAVE On a slave replication server resets the master server information and restarts the slave Like executing the RESET SLAVE SQL statement MYSQLI_REFRESH_MASTER On a master replication server removes the binary log files...

Страница 2360: ...ast connect error mysqli errno mysqli_errno N A Returns the error code for the most recent function call mysqli error mysqli_error N A Returns a string description of the last error mysqli field_count mysqli_field_count N A Returns the number of columns for the most recent query mysqli host_info mysqli_get_host_info N A Returns a string representing the type of connection used mysqli protocol_vers...

Страница 2361: ...en a new connection to the MySQL server Note static i e class method mysqli debug mysqli_debug N A Performs debugging operations mysqli dump_debug_info mysqli_dump_debug_info N A Dump debugging information into the log mysqli get_charsetmysqli_get_charset N A Returns a character set object mysqli get_connection_stats mysqli_get_connection_stats N A Returns client connection statistics Available on...

Страница 2362: ...atement for execution mysqli query mysqli_query N A Performs a query on the database mysqli real_connect mysqli_real_connectN A Opens a connection to a mysql server mysqli real_escape_string mysqli escape_string mysqli_real_escape_string mysqli_escape_string Escapes special characters in a string for use in an SQL statement taking into account the current charset of the connection mysqli real_quer...

Страница 2363: ... N A Returns whether thread safety is given or not mysqli use_result mysqli_use_result N A Initiate a result set retrieval Table 20 41 Summary of mysqli_stmt methods MySQL_STMT OOP Interface Procedural Interface Alias Do not use Description Properties mysqli_stmt affected_rows mysqli_stmt_affected_rows N A Returns the total number of rows changed deleted or inserted by the last executed statement ...

Страница 2364: ...ose mysqli_stmt_close N A Closes a prepared statement mysqli_stmt data_seek mysqli_stmt_data_seek N A Seeks to an arbitrary row in statement result set mysqli_stmt execute mysqli_stmt_executemysqli_execute Executes a prepared Query mysqli_stmt fetch mysqli_stmt_fetch mysqli_fetch Fetch results from a prepared statement into the bound variables mysqli_stmt free_result mysqli_stmt_free_result N A Fr...

Страница 2365: ...elds in a result mysqli_result lengths mysqli_fetch_lengths N A Returns the lengths of the columns of the current row in the result set mysqli_result num_rowsmysqli_num_rows N A Gets the number of rows in a result Methods mysqli_result data_seek mysqli_data_seek N A Adjusts the result pointer to an arbitrary row in the result mysqli_result fetch_all mysqli_fetch_all N A Fetches all result rows and...

Страница 2366: ... 20 43 Summary of mysqli_driver methods MySQL_Driver OOP Interface Procedural Interface Alias Do not use Description Properties N A Methods mysqli_driver embedded_server_end mysqli_embedded_server_end N A NOT DOCUMENTED mysqli_driver embedded_server_start mysqli_embedded_server_start N A NOT DOCUMENTED Note Alias functions are provided for backward compatibility purposes only Do not use them in ne...

Страница 2367: ...read_id int mysqli warning_count Methods mysqli __construct string host ini_get mysqli default_host string username ini_get mysqli default_user string passwd ini_get mysqli default_pw string dbname int port ini_get mysqli default_port string socket ini_get mysqli default_socket bool mysqli autocommit bool mode bool mysqli change_user string user string password string database string mysqli charac...

Страница 2368: ... poll array read array error array reject int sec int usec mysqli_stmt mysqli prepare string query mixed mysqli query string query int resultmode MYSQLI_STORE_RESULT bool mysqli real_connect string host string username string passwd string dbname int port string socket int flags string mysqli escape_string string escapestr bool mysqli real_query string query public mysqli_result mysqli reap_async_...

Страница 2369: ...ented style int mysqli affected_rows Procedural style int mysqli_affected_rows mysqli link Returns the number of rows affected by the last INSERT UPDATE REPLACE or DELETE query For SELECT statements mysqli_affected_rows works like mysqli_num_rows Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init Return Values An integer greater than zero indicates th...

Страница 2370: ...CountryCode FROM Language printf Affected rows SELECT d n mysqli affected_rows result close Delete table Language mysqli query DROP TABLE Language close connection mysqli close Procedural style php link mysqli_connect localhost my_user my_password world if link printf Can t connect to localhost Error s n mysqli_connect_error exit Insert rows mysqli_query link CREATE TABLE Language SELECT from Coun...

Страница 2371: ...ocumentation Group 2230 mysqli autocommit mysqli_autocommit Turns on or off auto committing database modifications Description Object oriented style bool mysqli autocommit bool mode Procedural style bool mysqli_autocommit mysqli link bool mode Turns on or off auto commit mode on queries for the database connection To determine the current state of autocommit use the SQL command SELECT autocommit P...

Страница 2372: ...it TRUE if result mysqli query SELECT autocommit row result fetch_row printf Autocommit is s n row 0 result free close connection mysqli close Procedural style php link mysqli_connect localhost my_user my_password world if link printf Can t connect to localhost Error s n mysqli_connect_error exit turn autocommit on mysqli_autocommit link TRUE if result mysqli_query link SELECT autocommit row mysql...

Страница 2373: ...ient permissions to access the desired database If for any reason authorization fails the current user authentication will remain Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init user The MySQL user name password The MySQL password database The database to change to If desired the NULL value may be passed resulting in only changing the user and not ...

Страница 2374: ...atabase s n row 0 result close if result mysqli query SELECT a row result fetch_row if row 0 NULL printf Value of variable a is NULL n result close close connection mysqli close Procedural style php connect database test link mysqli_connect localhost my_user my_password test check connection if link printf Connect failed s n mysqli_connect_error exit Set Variable a mysqli_query link SET a 1 reset ...

Страница 2375: ...tation Group 2230 mysqli character_set_name mysqli_character_set_name Returns the default character set for the database connection Description Object oriented style string mysqli character_set_name Procedural style string mysqli_character_set_name mysqli link Returns the current character set for the database connection Parameters link Procedural style only A link identifier returned by mysqli_co...

Страница 2376: ...y_password world check connection if link printf Connect failed s n mysqli_connect_error exit Print current character set charset mysqli_character_set_name link printf Current character set is s n charset close connection mysqli_close link The above examples will output Current character set is latin1_swedish_ci See Also mysqli_set_charset mysqli_client_encoding mysqli_real_escape_string 20 7 3 9 ...

Страница 2377: ...rver_info mysqli_get_server_version 20 7 3 9 6 mysqli client_version mysqli_get_client_version Copyright 1997 2012 the PHP Documentation Group 2230 mysqli client_version mysqli_get_client_version Returns the MySQL client version as a string Description Object oriented style int mysqli client_version Procedural style int mysqli_get_client_version mysqli link Returns client version number as an inte...

Страница 2378: ...tation Group 2230 mysqli close mysqli_close Closes a previously opened database connection Description Object oriented style bool mysqli close Procedural style bool mysqli_close mysqli link Closes a previously opened database connection Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init Return Values Returns TRUE on success or FALSE on failure Example...

Страница 2379: ...ALSE on failure Examples Example 20 112 mysqli commit example Object oriented style php mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit mysqli query CREATE TABLE Language LIKE CountryLanguage set autocommit to off mysqli autocommit FALSE Insert some values mysqli query INSERT INTO Language VALUES DEU...

Страница 2380: ... 3 9 9 mysqli connect_errno mysqli_connect_errno Copyright 1997 2012 the PHP Documentation Group 2230 mysqli connect_errno mysqli_connect_errno Returns the error code from last connect call Description Object oriented style string mysqli connect_errno Procedural style int mysqli_connect_errno Returns the last error code number from the last call to mysqli_connect Note Client error message numbers ...

Страница 2381: ...ct_errno The above examples will output Connect Error 1045 See Also mysqli_connect mysqli_connect_error mysqli_errno mysqli_error mysqli_sqlstate 20 7 3 9 10 mysqli connect_error mysqli_connect_error Copyright 1997 2012 the PHP Documentation Group 2230 mysqli connect_error mysqli_connect_error Returns a string description of the last connect error Description Object oriented style string mysqli co...

Страница 2382: ... link die Connect Error mysqli_connect_error The above examples will output Connect Error Access denied for user fake_user localhost using password YES Notes Warning The mysqli connect_error property only works properly as of PHP versions 5 2 9 and 5 3 0 Use the mysqli_connect_error function if compatibility with earlier PHP versions is required See Also mysqli_connect mysqli_connect_errno mysqli_...

Страница 2383: ...his parameter the local host is assumed When possible pipes will be used instead of the TCP IP protocol Prepending host by p opens a persistent connection mysqli_change_user is automatically called on connections opened from the connection pool username The MySQL user name passwd If not provided or NULL the MySQL server will attempt to authenticate the user against those user records which have no...

Страница 2384: ... 0 if mysqli connect_error die Connect Error mysqli connect_errno mysqli connect_error Use this instead of connect_error if you need to ensure compatibility with PHP versions prior to 5 2 9 and 5 3 0 if mysqli_connect_error die Connect Error mysqli_connect_errno mysqli_connect_error echo Success mysqli host_info n mysqli close Object oriented style when extending mysqli class php class foo_mysqli ...

Страница 2385: ...r to calling mysqli_real_connect but after mysqli_init Note OO syntax only If a connection fails an object is still returned To check if the connection failed then use either the mysqli_connect_error function or the mysqli connect_error property as in the preceding examples Note If it is necessary to set options such as the connection timeout mysqli_real_connect must be used instead Note Calling t...

Страница 2386: ...debugging operations using the Fred Fish debugging library Parameters message A string representing the debugging operation to perform Return Values Returns TRUE Notes Note To use the mysqli_debug function you must compile the MySQL client library to support debugging Examples Example 20 116 Generating a Trace File php Create a trace file in tmp client trace on the local client machine mysqli_debu...

Страница 2387: ...ALSE on failure See Also mysqli_debug 20 7 3 9 14 mysqli errno mysqli_errno Copyright 1997 2012 the PHP Documentation Group 2230 mysqli errno mysqli_errno Returns the error code for the most recent function call Description Object oriented style int mysqli errno Procedural style int mysqli_errno mysqli link Returns the last error code for the most recent MySQLi function call that can succeed or fa...

Страница 2388: ...T a 1 printf Errorcode d n mysqli errno close connection mysqli close Procedural style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit if mysqli_query link SET a 1 printf Errorcode d n mysqli_errno link close connection mysqli_close link The above examples will output Errorcode 1193 See Also my...

Страница 2389: ...i_connect or mysqli_init Return Values A list of errors each as an associative array containing the errno error and sqlstate Examples Example 20 118 mysqli error_list example Object oriented style php mysqli new mysqli localhost nobody check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit if mysqli query SET a 1 print_r mysqli error_list close connection mysq...

Страница 2390: ...ror Copyright 1997 2012 the PHP Documentation Group 2230 mysqli error mysqli_error Returns a string description of the last error Description Object oriented style string mysqli error Procedural style string mysqli_error mysqli link Returns the last error message for the most recent MySQLi function call that can succeed or fail Parameters link Procedural style only A link identifier returned by my...

Страница 2391: ...ocalhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit if mysqli_query link SET a 1 printf Errormessage s n mysqli_error link close connection mysqli_close link The above examples will output Errormessage Unknown system variable a See Also mysqli_connect_errno mysqli_connect_error mysqli_errno mysqli_sqlstate 20 7 3 9 17 mysq...

Страница 2392: ...eturned by mysqli_connect or mysqli_init Return Values An integer representing the number of fields in a result set Examples Example 20 120 mysqli field_count example Object oriented style php mysqli new mysqli localhost my_user my_password test mysqli query DROP TABLE IF EXISTS friends mysqli query CREATE TABLE friends id int name varchar 20 mysqli query INSERT INTO friends VALUES 1 Hartmut 2 Ulf...

Страница 2393: ...997 2012 the PHP Documentation Group 2230 mysqli get_charset mysqli_get_charset Returns a character set object Description Object oriented style object mysqli get_charset Procedural style object mysqli_get_charset mysqli link Returns a character set object providing several properties of the current active character set Parameters link Procedural style only A link identifier returned by mysqli_con...

Страница 2394: ...li_real_connect db localhost root test var_dump db get_charset The above examples will output object stdClass 2 7 charset string 6 latin1 collation string 17 latin1_swedish_ci dir string 0 min_length int 1 max_length int 1 number int 8 state int 801 See Also mysqli_character_set_name mysqli_set_charset 20 7 3 9 19 mysqli get_client_info mysqli_get_client_info Copyright 1997 2012 the PHP Documentat...

Страница 2395: ...ibrary printf Client library version s n mysqli_get_client_info See Also mysqli_get_client_version mysqli_get_server_info mysqli_get_server_version 20 7 3 9 20 mysqli_get_client_stats Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_get_client_stats Returns client per process statistics Description array mysqli_get_client_stats Returns client per process statistics Available only with m...

Страница 2396: ...buffered_sets 0 unbuffered_sets 0 ps_buffered_sets 0 ps_unbuffered_sets 0 flushed_normal_sets 0 flushed_ps_sets 0 ps_prepared_never_executed 0 ps_prepared_once_executed 0 rows_fetched_from_server_normal 0 rows_fetched_from_server_ps 0 rows_buffered_from_client_normal 0 rows_buffered_from_client_ps 0 rows_fetched_from_client_normal_buffered 0 rows_fetched_from_client_normal_unbuffered 0 rows_fetche...

Страница 2397: ...o_text_fetched_enum 0 proto_text_fetched_set 0 proto_text_fetched_geometry 0 proto_text_fetched_other 0 proto_binary_fetched_null 0 proto_binary_fetched_bit 0 proto_binary_fetched_tinyint 0 proto_binary_fetched_short 0 proto_binary_fetched_int24 0 proto_binary_fetched_int 0 proto_binary_fetched_bigint 0 proto_binary_fetched_decimal 0 proto_binary_fetched_float 0 proto_binary_fetched_double 0 proto...

Страница 2398: ...t need a connection to determine the version of mysql client library printf Client library version d n mysqli_get_client_version See Also mysqli_get_client_info mysqli_get_server_info mysqli_get_server_version 20 7 3 9 22 mysqli get_connection_stats mysqli_get_connection_stats Copyright 1997 2012 the PHP Documentation Group 2230 mysqli get_connection_stats mysqli_get_connection_stats Returns stati...

Страница 2399: ...kets_received_rset_header 0 packets_received_rset_field_meta 0 packets_received_rset_row 0 packets_received_prepare_response 0 packets_received_change_user 0 result_set_queries 0 non_result_set_queries 0 no_index_used 0 bad_index_used 0 slow_queries 0 buffered_sets 0 unbuffered_sets 0 ps_buffered_sets 0 ps_unbuffered_sets 0 flushed_normal_sets 0 flushed_ps_sets 0 ps_prepared_never_executed 0 ps_pr...

Страница 2400: ...ed_decimal 0 proto_text_fetched_float 0 proto_text_fetched_double 0 proto_text_fetched_date 0 proto_text_fetched_year 0 proto_text_fetched_time 0 proto_text_fetched_datetime 0 proto_text_fetched_timestamp 0 proto_text_fetched_string 0 proto_text_fetched_blob 0 proto_text_fetched_enum 0 proto_text_fetched_set 0 proto_text_fetched_geometry 0 proto_text_fetched_other 0 proto_binary_fetched_null 0 pro...

Страница 2401: ...bing the connection represented by the link parameter including the server host name Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init Return Values A character string representing the server hostname and the connection type Examples Example 20 126 mysqli host_info example Object oriented style php mysqli new mysqli localhost my_user my_password worl...

Страница 2402: ...24 mysqli protocol_version mysqli_get_proto_info Copyright 1997 2012 the PHP Documentation Group 2230 mysqli protocol_version mysqli_get_proto_info Returns the version of the MySQL protocol used Description Object oriented style string mysqli protocol_version Procedural style int mysqli_get_proto_info mysqli link Returns an integer representing the MySQL protocol version used by the connection rep...

Страница 2403: ...style php link mysqli_connect localhost my_user my_password check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit print protocol version printf Protocol version d n mysqli_get_proto_info link close connection mysqli_close link The above examples will output Protocol version 10 See Also mysqli_get_host_info 20 7 3 9 25 mysqli server_info mysqli_get_server_info...

Страница 2404: ...le 20 128 mysqli server_info example Object oriented style php mysqli new mysqli localhost my_user my_password check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit print server version printf Server version s n mysqli server_info close connection mysqli close Procedural style php link mysqli_connect localhost my_user my_password check connection if mysqli_co...

Страница 2405: ...ver_version mysqli link The mysqli_get_server_version function returns the version of the server connected to represented by the link parameter as an integer Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init Return Values An integer representing the server version The form of this version number is main_version 10000 minor_version 100 sub_version i e...

Страница 2406: ...close connection mysqli_close link The above examples will output Server version 40102 See Also mysqli_get_client_info mysqli_get_client_version mysqli_get_server_info 20 7 3 9 27 mysqli get_warnings mysqli_get_warnings Copyright 1997 2012 the PHP Documentation Group 2230 mysqli get_warnings mysqli_get_warnings Get result of SHOW WARNINGS Description Object oriented style mysqli_warning mysqli get...

Страница 2407: ...Records 100 Duplicates 0 Warnings 0 INSERT INTO VALUES Records 3 Duplicates 0 Warnings 0 LOAD DATA INFILE Records 1 Deleted 0 Skipped 0 Warnings 0 ALTER TABLE Records 3 Duplicates 0 Warnings 0 UPDATE Rows matched 40 Changed 40 Warnings 0 Note Queries which do not fall into one of the preceding formats are not supported In these situations mysqli_info will return an empty string Parameters link Pro...

Страница 2408: ...ed s n mysqli_connect_error exit mysqli_query link CREATE TEMPORARY TABLE t1 LIKE City INSERT INTO SELECT mysqli_query link INSERT INTO t1 SELECT FROM City ORDER BY ID LIMIT 150 printf s n mysqli_info link close connection mysqli_close link The above examples will output Records 150 Duplicates 0 Warnings 0 See Also mysqli_affected_rows mysqli_warning_count mysqli_num_rows 20 7 3 9 29 mysqli init m...

Страница 2409: ...nsert_id mysqli_insert_id Returns the auto generated id used in the last query Description Object oriented style mixed mysqli insert_id Procedural style mixed mysqli_insert_id mysqli link The mysqli_insert_id function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute If the last query wasn t an INSERT or UPDATE statement or if the modified table does ...

Страница 2410: ...iled s n mysqli_connect_error exit mysqli query CREATE TABLE myCity LIKE City query INSERT INTO myCity VALUES NULL Stuttgart DEU Stuttgart 617000 mysqli query query printf New Record has id d n mysqli insert_id drop table mysqli query DROP TABLE myCity close connection mysqli close Procedural style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno...

Страница 2411: ...ead specified by the processid parameter This value must be retrieved by calling the mysqli_thread_id function To stop a running query you should use the SQL command KILL QUERY processid Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init Return Values Returns TRUE on success or FALSE on failure Examples Example 20 132 mysqli kill example Object orient...

Страница 2412: ...ine our thread id thread_id mysqli_thread_id link Kill connection mysqli_kill link thread_id This should produce an error if mysqli_query link CREATE TABLE myCity LIKE City printf Error s n mysqli_error link exit close connection mysqli_close link The above examples will output Error MySQL server has gone away See Also mysqli_thread_id 20 7 3 9 32 mysqli more_results mysqli_more_results Copyright ...

Страница 2413: ...sult 20 7 3 9 33 mysqli multi_query mysqli_multi_query Copyright 1997 2012 the PHP Documentation Group 2230 mysqli multi_query mysqli_multi_query Performs a query on the database Description Object oriented style bool mysqli multi_query string query Procedural style bool mysqli_multi_query mysqli link string query Executes one or multiple queries which are concatenated by a semicolon To retrieve t...

Страница 2414: ...mysqli_connect_error exit query SELECT CURRENT_USER query SELECT Name FROM City ORDER BY ID LIMIT 20 5 execute multi query if mysqli multi_query query do store first result set if result mysqli store_result while row result fetch_row printf s n row 0 result free print divider if mysqli more_results printf n while mysqli next_result close connection mysqli close Procedural style php link mysqli_con...

Страница 2415: ...stricht Dordrecht Leiden Haarlemmermeer See Also mysqli_query mysqli_use_result mysqli_store_result mysqli_next_result mysqli_more_results 20 7 3 9 34 mysqli next_result mysqli_next_result Copyright 1997 2012 the PHP Documentation Group 2230 mysqli next_result mysqli_next_result Prepare next result from multi_query Description Object oriented style bool mysqli next_result Procedural style bool mys...

Страница 2416: ...d style bool mysqli options int option mixed value Procedural style bool mysqli_options mysqli link int option mixed value Used to set extra connect options and affect behavior for a connection This function may be called multiple times to set several options mysqli_options should be called after mysqli_init and before mysqli_real_connect Parameters link Procedural style only A link identifier ret...

Страница 2417: ...rn Values Returns TRUE on success or FALSE on failure Changelog Version Description 5 5 0 The MYSQLI_SERVER_PUBLIC_KEY option was added Examples See mysqli_real_connect Notes Note MySQLnd always assumes the server default charset This charset is sent during connection hand shake authentication which mysqlnd will use Libmysqlclient uses the default charset set in the my cnf or by an explicit call t...

Страница 2418: ...k identifier returned by mysqli_connect or mysqli_init Return Values Returns TRUE on success or FALSE on failure Examples Example 20 134 mysqli ping example Object oriented style php mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit check if server is alive if mysqli ping printf Our connection is ok n ...

Страница 2419: ...ll connections Description Object oriented style public int mysqli poll array read array error array reject int sec int usec Procedural style int mysqli_poll array read array error array reject int sec int usec Warning This function is currently not documented only its argument list is available Poll connections Available only with mysqlnd The method can be used as static Parameters read error rej...

Страница 2420: ...rs reject 1 continue foreach links as link if result link reap_async_query print_r result fetch_row if is_object result mysqli_free_result result else die sprintf MySQLi Error s mysqli_error link processed while processed count all_links The above example will output Array 0 test See Also mysqli_query mysqli_reap_async_query 20 7 3 9 38 mysqli prepare mysqli_prepare Copyright 1997 2012 the PHP Doc...

Страница 2421: ...appropriate positions Note The markers are legal only in certain places in SQL statements For example they are allowed in the VALUES list of an INSERT statement to specify column values for a row or in a comparison with a column in a WHERE clause to specify a comparison value However they are not allowed for identifiers such as table or column names in the select list that names the columns to be ...

Страница 2422: ... s is in district s n city district close statement stmt close close connection mysqli close Procedural style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit city Amersfoort create a prepared statement if stmt mysqli_prepare link SELECT District FROM City WHERE Name bind parameters for markers ...

Страница 2423: ...T Procedural style mixed mysqli_query mysqli link string query int resultmode MYSQLI_STORE_RESULT Performs a query against the database For non DML queries not INSERT UPDATE or DELETE this function is similar to calling mysqli_real_query followed by either mysqli_use_result or mysqli_store_result Note In the case where you pass a statement to mysqli_query that is longer than max_allowed_packet of ...

Страница 2424: ...ailable with mysqlnd it is possible to perform query asynchronously mysqli_poll is then used to get results from such queries Return Values Returns FALSE on failure For successful SELECT SHOW DESCRIBE or EXPLAIN queries mysqli_query will return a mysqli_result object For other successful queries mysqli_query will return TRUE Changelog Version Description 5 3 0 Added the ability of async queries Ex...

Страница 2425: ...if mysqli_query link CREATE TEMPORARY TABLE myCity LIKE City TRUE printf Table myCity successfully created n Select queries return a resultset if result mysqli_query link SELECT Name FROM City LIMIT 10 printf Select returned d rows n mysqli_num_rows result free result set mysqli_free_result result If we have to retrieve large amount of data we use MYSQLI_USE_RESULT if result mysqli_query link SELE...

Страница 2426: ...et int flags Establish a connection to a MySQL database engine This function differs from mysqli_connect mysqli_real_connect needs a valid object which has to be created by function mysqli_init With the mysqli_options function you can set various options for connection There is a flags parameter Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init host ...

Страница 2427: ... flags you can set different connection options Table 20 46 Supported flags Name Description MYSQLI_CLIENT_COMPRESS Use compression protocol MYSQLI_CLIENT_FOUND_ROWS return number of matched rows not the number of affected rows MYSQLI_CLIENT_IGNORE_SPACE Allow spaces after function names Makes all function names reserved words MYSQLI_CLIENT_INTERACTIVE Allow interactive_timeout seconds instead of ...

Страница 2428: ...blic function __construct host user pass db parent init if parent options MYSQLI_INIT_COMMAND SET AUTOCOMMIT 0 die Setting MYSQLI_INIT_COMMAND failed if parent options MYSQLI_OPT_CONNECT_TIMEOUT 5 die Setting MYSQLI_OPT_CONNECT_TIMEOUT failed if parent real_connect host user pass db die Connect Error mysqli_connect_errno mysqli_connect_error db new foo_mysqli localhost my_user my_password my_db ec...

Страница 2429: ...et set in the my cnf or by an explicit call to mysqli_options prior to calling mysqli_real_connect but after mysqli_init See Also mysqli_connect mysqli_init mysqli_options mysqli_ssl_set mysqli_close 20 7 3 9 41 mysqli real_escape_string mysqli_real_escape_string Copyright 1997 2012 the PHP Documentation Group 2230 mysqli real_escape_string mysqli_real_escape_string Escapes special characters in a...

Страница 2430: ...t or mysqli_init escapestr The string to be escaped Characters encoded are NUL ASCII 0 n r and Control Z Return Values Returns an escaped string Examples Example 20 139 mysqli real_escape_string example Object oriented style php mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit mysqli query CREATE TEMP...

Страница 2431: ...nk INSERT into myCity Name VALUES city printf d Row inserted n mysqli_affected_rows link mysqli_close link The above examples will output Error 42000 1 Row inserted Notes Note For those accustomed to using mysql_real_escape_string note that the arguments of mysqli_real_escape_string differ from what mysql_real_escape_string expects The link identifier comes first in mysqli_real_escape_string where...

Страница 2432: ...t query The query as a string Data inside the query should be properly escaped Return Values Returns TRUE on success or FALSE on failure See Also mysqli_query mysqli_store_result mysqli_use_result 20 7 3 9 43 mysqli reap_async_query mysqli_reap_async_query Copyright 1997 2012 the PHP Documentation Group 2230 mysqli reap_async_query mysqli_reap_async_query Get result from async query Description Ob...

Страница 2433: ... Procedural style int mysqli_refresh resource link int options Flushes tables or caches or resets the replication server information Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init options The options to refresh using the MYSQLI_REFRESH_ constants as documented within the MySQLi constants documentation See also the official MySQL Refresh documentat...

Страница 2434: ... localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit disable autocommit mysqli autocommit FALSE mysqli query CREATE TABLE myCity LIKE City mysqli query ALTER TABLE myCity Type InnoDB mysqli query INSERT INTO myCity SELECT FROM City LIMIT 50 commit insert mysqli commit delete all rows mysqli query DELETE FROM myCity if res...

Страница 2435: ...SERT INTO myCity SELECT FROM City LIMIT 50 commit insert mysqli_commit link delete all rows mysqli_query link DELETE FROM myCity if result mysqli_query link SELECT COUNT FROM myCity row mysqli_fetch_row result printf d rows in table myCity n row 0 Free result mysqli_free_result result Rollback mysqli_rollback link if result mysqli_query link SELECT COUNT FROM myCity row mysqli_fetch_row result pri...

Страница 2436: ...ype INSERT UPDATE and similar are master queries SELECT is slave and FLUSH REPAIR and similar are admin Warning This function is currently not documented only its argument list is available Warning This function has been DEPRECATED and REMOVED as of PHP 5 3 0 20 7 3 9 47 mysqli select_db mysqli_select_db Copyright 1997 2012 the PHP Documentation Group 2230 mysqli select_db mysqli_select_db Selects...

Страница 2437: ...ew mysqli localhost my_user my_password test check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit return name of current default database if result mysqli query SELECT DATABASE row result fetch_row printf Default database is s n row 0 result close change db to world db mysqli select_db world return name of current default database if result mysqli query SELE...

Страница 2438: ...i_free_result result mysqli_close link The above examples will output Default database is test Default database is world See Also mysqli_connect mysqli_real_connect 20 7 3 9 48 mysqli send_query mysqli_send_query Copyright 1997 2012 the PHP Documentation Group 2230 mysqli send_query mysqli_send_query Send the query and return Description Object oriented style bool mysqli send_query string query Pr...

Страница 2439: ...ier returned by mysqli_connect or mysqli_init charset The charset to be set as default Return Values Returns TRUE on success or FALSE on failure Notes Note To use this function on a Windows platform you need MySQL client library version 4 1 11 or above for MySQL 5 0 you need 5 0 6 or above Note This is the preferred way to change the charset Using mysqli_query to set it such as SET NAMES utf8 is n...

Страница 2440: ...tf8 s n mysqli_error link else printf Current character set s n mysqli_character_set_name link mysqli_close link The above examples will output Current character set utf8 See Also mysqli_character_set_name mysqli_real_escape_string List of character sets that MySQL supports 20 7 3 9 50 mysqli set_local_infile_default mysqli_set_local_infile_default Copyright 1997 2012 the PHP Documentation Group 2...

Страница 2441: ...handler mysqli link callable read_func Procedural style bool mysqli_set_local_infile_handler mysqli link callable read_func Set callback function for LOAD DATA LOCAL INFILE command The callbacks task is to read input from the file specified in the LOAD DATA LOCAL INFILE and to reformat it into the format understood by LOAD DATA INFILE The returned data needs to match the format specified in the LO...

Страница 2442: ...buffer buflen errmsg buffer fgets stream echo buffer convert to upper case and replace delimiter with TAB buffer strtoupper str_replace t buffer return strlen buffer echo Input n db set_local_infile_handler callme db query LOAD DATA LOCAL INFILE input txt INTO TABLE t1 db set_local_infile_default res db query SELECT FROM t1 echo nResult n while row res fetch_assoc echo join row n Procedural style ...

Страница 2443: ...ate Copyright 1997 2012 the PHP Documentation Group 2230 mysqli sqlstate mysqli_sqlstate Returns the SQLSTATE error from previous MySQL operation Description Object oriented style string mysqli sqlstate Procedural style string mysqli_sqlstate mysqli link Returns a string containing the SQLSTATE error code for the last error The error code consists of five characters 00000 means no error The values...

Страница 2444: ...t_errno printf Connect failed s n mysqli_connect_error exit Table City already exists so we should get an error if mysqli query CREATE TABLE City ID INT Name VARCHAR 30 printf Error SQLSTATE s n mysqli sqlstate mysqli close Procedural style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit Table ...

Страница 2445: ...hat MySQL Native Driver does not support SSL before PHP 5 3 3 so calling this function when using MySQL Native Driver will result in an error MySQL Native Driver is enabled by default on Microsoft Windows from PHP version 5 3 onwards Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init key The path name to the key file cert The path name to the certific...

Страница 2446: ...and This includes uptime in seconds and the number of running threads questions reloads and open tables Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init Return Values A string describing the server status FALSE if an error occurred Examples Example 20 145 mysqli stat example Object oriented style php mysqli new mysqli localhost my_user my_password w...

Страница 2447: ...5 mysqli stmt_init mysqli_stmt_init Copyright 1997 2012 the PHP Documentation Group 2230 mysqli stmt_init mysqli_stmt_init Initializes a statement and returns an object for use with mysqli_stmt_prepare Description Object oriented style mysqli_stmt mysqli stmt_init Procedural style mysqli_stmt mysqli_stmt_init mysqli link Allocates and initializes a statement object suitable for mysqli_stmt_prepare...

Страница 2448: ...lt returns FALSE in case the query didn t return a result set if the query was for example an INSERT statement This function also returns FALSE if the reading of the result set failed You can check if you have got an error by checking if mysqli_error doesn t return an empty string if mysqli_errno returns a non zero value or if mysqli_field_count returns a non zero value Also possible reason for th...

Страница 2449: ...ead ID will be other Therefore you should get the thread ID only when you need it Note The thread ID is assigned on a connection by connection basis Hence if the connection is broken and then re established a new thread ID will be assigned To kill a running query you can use the SQL command KILL QUERY processid Parameters link Procedural style only A link identifier returned by mysqli_connect or m...

Страница 2450: ...nect_error exit determine our thread id thread_id mysqli_thread_id link Kill connection mysqli_kill link thread_id This should produce an error if mysqli_query link CREATE TABLE myCity LIKE City printf Error s n mysqli_error link exit close connection mysqli_close link The above examples will output Error MySQL server has gone away See Also mysqli_kill 20 7 3 9 58 mysqli thread_safe mysqli_thread_...

Страница 2451: ...before the results of a query can be retrieved and one or the other must be called to prevent the next query on that database connection from failing Note The mysqli_use_result function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek to move to a particular row within the set To use this functionality the result set must be stor...

Страница 2452: ... mysqli close Procedural style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit query SELECT CURRENT_USER query SELECT Name FROM City ORDER BY ID LIMIT 20 5 execute multi query if mysqli_multi_query link query do store first result set if result mysqli_use_result link while row mysqli_fetch_row ...

Страница 2453: ...ct oriented style int mysqli warning_count Procedural style int mysqli_warning_count mysqli link Returns the number of warnings from the last query in the connection Note For retrieving warning messages you can use the SQL command SHOW WARNINGS limit row_count Parameters link Procedural style only A link identifier returned by mysqli_connect or mysqli_init Return Values Number of warnings or zero ...

Страница 2454: ...al style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit mysqli_query link CREATE TABLE myCity LIKE City a remarkable long city name in Wales query INSERT INTO myCity CountryCode Name VALUES GBR Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch mysqli_query link query if mysqli_warning...

Страница 2455: ...ray mysqli_stmt error_list string mysqli_stmt error int mysqli_stmt field_count int mysqli_stmt insert_id int mysqli_stmt num_rows int mysqli_stmt param_count string mysqli_stmt sqlstate Methods int mysqli_stmt attr_get int attr bool mysqli_stmt attr_set int attr int mode bool mysqli_stmt bind_param string types mixed var1 mixed bool mysqli_stmt bind_result mixed var1 mixed bool mysqli_stmt close ...

Страница 2456: ...ocedural style int mysqli_stmt_affected_rows mysqli_stmt stmt Returns the number of rows affected by INSERT UPDATE or DELETE query This function only works with queries which update a table In order to get the number of rows from a SELECT query use mysqli_stmt_num_rows instead Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init Return Values An integer greater...

Страница 2457: ...tatement stmt execute printf rows inserted d n stmt affected_rows close statement stmt close close connection mysqli close Example 20 150 Procedural style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit create temp table mysqli_query link CREATE TEMPORARY TABLE myCountry LIKE Country query INSE...

Страница 2458: ...ent attribute Description Object oriented style int mysqli_stmt attr_get int attr Procedural style int mysqli_stmt_attr_get mysqli_stmt stmt int attr Gets the current value of a statement attribute Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init attr The attribute that you want to get Return Values Returns FALSE if the attribute is not found otherwise retu...

Страница 2459: ...ELD max_length value MYSQLI_STMT_ATTR_CURSOR_TYPE Type of cursor to open for statement when mysqli_stmt_execute is invoked mode can be MYSQLI_CURSOR_TYPE_NO_CURSOR the default or MYSQLI_CURSOR_TYPE_READ_ONLY MYSQLI_STMT_ATTR_PREFETCH_ROWS Number of rows to fetch from server at a time when using a cursor mode can be in the range from 1 to the maximum value of unsigned long The default is 1 If you u...

Страница 2460: ...x allowed packet size max_allowed_packet you have to specify b in types and use mysqli_stmt_send_long_data to send the data in packets Note Care must be taken when using mysqli_stmt_bind_param in conjunction with call_user_func_array Note that mysqli_stmt_bind_param requires parameters to be passed by reference whereas call_user_func_array can accept as a parameter a list of variables that can rep...

Страница 2461: ...yLanguage VALUES stmt bind_param sssd code language official percent code DEU language Bavarian official F percent 11 2 execute prepared statement stmt execute printf d Row inserted n stmt affected_rows close statement and connection stmt close Clean up table CountryLanguage mysqli query DELETE FROM CountryLanguage WHERE Language Bavarian printf d Row deleted n mysqli affected_rows close connectio...

Страница 2462: ... above examples will output 1 Row inserted 1 Row deleted See Also mysqli_stmt_bind_result mysqli_stmt_execute mysqli_stmt_fetch mysqli_prepare mysqli_stmt_send_long_data mysqli_stmt_errno mysqli_stmt_error 20 7 3 10 5 mysqli_stmt bind_result mysqli_stmt_bind_result Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_stmt bind_result mysqli_stmt_bind_result Binds variables to a prepared sta...

Страница 2463: ...d Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init var1 The variable to be bound Return Values Returns TRUE on success or FALSE on failure Examples Example 20 153 Object oriented style php mysqli new mysqli localhost my_user my_password world if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit prepare statement if stmt mysqli prepare...

Страница 2464: ...li_stmt_close stmt close connection mysqli_close link The above examples will output AFG Afghanistan ALB Albania DZA Algeria ASM American Samoa AND Andorra See Also mysqli_stmt_bind_param mysqli_stmt_execute mysqli_stmt_fetch mysqli_prepare mysqli_stmt_prepare mysqli_stmt_init mysqli_stmt_errno mysqli_stmt_error 20 7 3 10 6 mysqli_stmt close mysqli_stmt_close Copyright 1997 2012 the PHP Documentat...

Страница 2465: ...Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_stmt data_seek mysqli_stmt_data_seek Seeks to an arbitrary row in statement result set Description Object oriented style void mysqli_stmt data_seek int offset Procedural style void mysqli_stmt_data_seek mysqli_stmt stmt int offset Seeks to an arbitrary result pointer in the statement result set mysqli_stmt_store_result must be called prio...

Страница 2466: ...h printf City s Countrycode s n name code close statement stmt close close connection mysqli close Example 20 156 Procedural style php Open a connection link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit query SELECT Name CountryCode FROM City ORDER BY Name if stmt mysqli_prepare link query execute qu...

Страница 2467: ...mysqli_stmt errno Procedural style int mysqli_stmt_errno mysqli_stmt stmt Returns the error code for the most recently invoked statement function that can succeed or fail Client error message numbers are listed in the MySQL errmsg h header file server error message numbers are listed in mysqld_error h In the MySQL source distribution you can find a complete list of error messages and error numbers...

Страница 2468: ...d n stmt errno close statement stmt close close connection mysqli close Example 20 158 Procedural style php Open a connection link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit mysqli_query link CREATE TABLE myCountry LIKE Country mysqli_query link INSERT INTO myCountry SELECT FROM Country query SELEC...

Страница 2469: ...tmt Returns an array of errors for the most recently invoked statement function that can succeed or fail Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init Return Values A list of errors each as an associative array containing the errno error and sqlstate Examples Example 20 159 Object oriented style php Open a connection mysqli new mysqli localhost my_user m...

Страница 2470: ...rrno printf Connect failed s n mysqli_connect_error exit mysqli_query link CREATE TABLE myCountry LIKE Country mysqli_query link INSERT INTO myCountry SELECT FROM Country query SELECT Name Code FROM myCountry ORDER BY Name if stmt mysqli_prepare link query drop table mysqli_query link DROP TABLE myCountry execute query mysqli_stmt_execute stmt echo Error n print_r mysql_stmt_error_list stmt close ...

Страница 2471: ...tmt Returns a containing the error message for the most recently invoked statement function that can succeed or fail Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init Return Values A string that describes the error An empty string if no error occurred Examples Example 20 161 Object oriented style php Open a connection mysqli new mysqli localhost my_user my_p...

Страница 2472: ...n if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit mysqli_query link CREATE TABLE myCountry LIKE Country mysqli_query link INSERT INTO myCountry SELECT FROM Country query SELECT Name Code FROM myCountry ORDER BY Name if stmt mysqli_prepare link query drop table mysqli_query link DROP TABLE myCountry execute query mysqli_stmt_execute stmt printf Error s n mysqli_stmt_erro...

Страница 2473: ... using the mysqli_stmt_affected_rows function Likewise if the query yields a result set the mysqli_stmt_fetch function is used Note When using mysqli_stmt_execute the mysqli_stmt_fetch function must be used to fetch the data prior to performing any additional queries Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init Return Values Returns TRUE on success or F...

Страница 2474: ...y close connection mysqli close Example 20 164 Procedural style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit mysqli_query link CREATE TABLE myCity LIKE City Prepare an insert statement query INSERT INTO myCity Name CountryCode District VALUES stmt mysqli_prepare link query mysqli_stmt_bind_p...

Страница 2475: ...stmt_bind_param 20 7 3 10 12 mysqli_stmt fetch mysqli_stmt_fetch Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_stmt fetch mysqli_stmt_fetch Fetch results from a prepared statement into the bound variables Description Object oriented style bool mysqli_stmt fetch Procedural style bool mysqli_stmt_fetch mysqli_stmt stmt Fetch the result from a prepared statement into the variables bound...

Страница 2476: ...mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit query SELECT Name CountryCode FROM City ORDER by ID DESC LIMIT 150 5 if stmt mysqli prepare query execute statement stmt execute bind result variables stmt bind_result name code fetch values while stmt fetch printf s s n name code close statement stmt close close connection mysqli close Example 20 166 Procedural style php lin...

Страница 2477: ...ahassee USA Salinas USA Santa Clarita USA Springfield USA See Also mysqli_prepare mysqli_stmt_errno mysqli_stmt_error mysqli_stmt_bind_result 20 7 3 10 13 mysqli_stmt field_count mysqli_stmt_field_count Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_stmt field_count mysqli_stmt_field_count Returns the number of field in the given statement Description Object oriented style int mysqli_...

Страница 2478: ...tatement which was allocated by mysqli_stmt_store_result Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init Return Values No value is returned See Also mysqli_stmt_store_result 20 7 3 10 15 mysqli_stmt get_result mysqli_stmt_get_result Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_stmt get_result mysqli_stmt_get_result Gets a result set from a p...

Страница 2479: ... connect_errno mysqli connect_error query SELECT Name Population Continent FROM Country WHERE Continent ORDER BY Name LIMIT 1 stmt mysqli stmt_init if stmt prepare query print Failed to prepare statement n else stmt bind_param s continent continent_array array Europe Africa Asia North America foreach continent_array as continent stmt execute result stmt get_result while row result fetch_array MYSQ...

Страница 2480: ...nent mysqli_stmt_execute stmt result mysqli_stmt_get_result stmt while row mysqli_fetch_array result MYSQLI_NUM foreach row as r print r print n mysqli_stmt_close stmt mysqli_close link The above examples will output Albania 3401200 Europe Algeria 31471000 Africa Afghanistan 22720000 Asia Anguilla 8000 North America See Also mysqli_prepare mysqli_stmt_result_metadata mysqli_stmt_fetch mysqli_fetch...

Страница 2481: ... INSERT operation Description Object oriented style int mysqli_stmt insert_id Procedural style mixed mysqli_stmt_insert_id mysqli_stmt stmt Warning This function is currently not documented only its argument list is available 20 7 3 10 18 mysqli_stmt more_results mysqli_stmt_more_results Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_stmt more_results mysqli_stmt_more_results Check if...

Страница 2482: ...oriented style method public bool mysqli_stmt next_result Procedural style bool mysqli_stmt_next_result mysql_stmt stmt Reads the next result from a multiple query Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init Return Values Returns TRUE on success or FALSE on failure Errors Exceptions Emits an E_STRICT level error if a result set does not exist and sugge...

Страница 2483: ..._stmt_num_rows may be called immediately Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init Return Values An integer representing the number of rows in result set Examples Example 20 169 Object oriented style php Open a connection mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_co...

Страница 2484: ...result mysqli_stmt_store_result stmt printf Number of rows d n mysqli_stmt_num_rows stmt close statement mysqli_stmt_close stmt close connection mysqli_close link The above examples will output Number of rows 20 See Also mysqli_stmt_affected_rows mysqli_prepare mysqli_stmt_store_result 20 7 3 10 21 mysqli_stmt param_count mysqli_stmt_param_count Copyright 1997 2012 the PHP Documentation Group 2230...

Страница 2485: ...ct_errno printf Connect failed s n mysqli_connect_error exit if stmt mysqli prepare SELECT Name FROM Country WHERE Name OR Code marker stmt param_count printf Statement has d markers n marker close statement stmt close close connection mysqli close Example 20 172 Procedural style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect fai...

Страница 2486: ..._bind_result before executing the statement or fetching rows Note In the case where you pass a statement to mysqli_stmt_prepare that is longer than max_allowed_packet of the server the returned error codes are different depending on whether you are using MySQL Native Driver mysqlnd or MySQL Client Library libmysqlclient The behavior is as follows mysqlnd on Linux returns an error code of 1153 The ...

Страница 2487: ...to be returned by a SELECT statement or to specify both operands of a binary operator such as the equal sign The latter restriction is necessary because it would be impossible to determine the parameter type In general parameters are legal only in Data Manipulation Language DML statements and not in Data Definition Language DDL statements Return Values Returns TRUE on success or FALSE on failure E...

Страница 2488: ... exit city Amersfoort create a prepared statement stmt mysqli_stmt_init link if mysqli_stmt_prepare stmt SELECT District FROM City WHERE Name bind parameters for markers mysqli_stmt_bind_param stmt s city execute query mysqli_stmt_execute stmt bind result variables mysqli_stmt_bind_result stmt district fetch value mysqli_stmt_fetch stmt printf s is in district s n city district close statement mys...

Страница 2489: ..._long_data unbuffered result sets and current errors It does not clear bindings or stored result sets Stored result sets will be cleared when executing the prepared statement or closing it To prepare a statement with another query use function mysqli_stmt_prepare Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init Return Values Returns TRUE on success or FALSE...

Страница 2490: ...ield_tell mysqli_free_result The result set structure should be freed when you are done with it which you can do by passing it to mysqli_free_result Note The result set returned by mysqli_stmt_result_metadata contains only metadata It does not contain any row results The rows are obtained by using the statement handle with mysqli_stmt_fetch Parameters stmt Procedural style only A statement identif...

Страница 2491: ...NTO friends VALUES 1 Hartmut 2 Ulf stmt mysqli_prepare link SELECT id name FROM friends mysqli_stmt_execute stmt get resultset for metadata result mysqli_stmt_result_metadata stmt retrieve field information from metadata result set field mysqli_fetch_field result printf Fieldname s n field name close resultset mysqli_free_result result close connection mysqli_close link See Also mysqli_prepare mys...

Страница 2492: ...am_nr Indicates which parameter to associate the data with Parameters are numbered beginning with 0 data A string containing data to be sent Return Values Returns TRUE on success or FALSE on failure Examples Example 20 177 Object oriented style php stmt mysqli prepare INSERT INTO messages message VALUES null NULL stmt bind_param b null fp fopen messages txt r while feof fp stmt send_long_data 0 fr...

Страница 2493: ...e SQLSTATE error code for the last error The error code consists of five characters 00000 means no error Notes Note Note that not all MySQL errors are yet mapped to SQLSTATE s The value HY000 general error is used for unmapped errors Examples Example 20 178 Object oriented style php Open a connection mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno pri...

Страница 2494: ... if stmt mysqli_prepare link query drop table mysqli_query link DROP TABLE myCountry execute query mysqli_stmt_execute stmt printf Error s n mysqli_stmt_sqlstate stmt close statement mysqli_stmt_close stmt close connection mysqli_close link The above examples will output Error 42S02 See Also mysqli_stmt_errno mysqli_stmt_error 20 7 3 10 27 mysqli_stmt store_result mysqli_stmt_store_result Copyrigh...

Страница 2495: ...produced a result set by checking if mysqli_stmt_result_metadata returns NULL Parameters stmt Procedural style only A statement identifier returned by mysqli_stmt_init Return Values Returns TRUE on success or FALSE on failure Examples Example 20 180 Object oriented style php Open a connection mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno printf Conn...

Страница 2496: ...r of rows d n mysqli_stmt_num_rows stmt free result mysqli_stmt_free_result stmt close statement mysqli_stmt_close stmt close connection mysqli_close link The above examples will output Number of rows 20 See Also mysqli_prepare mysqli_stmt_result_metadata mysqli_stmt_fetch 20 7 3 11 The mysqli_result class mysqli_result Copyright 1997 2012 the PHP Documentation Group 2230 Represents the result set...

Страница 2497: ...t fetch_assoc object mysqli_result fetch_field_direct int fieldnr object mysqli_result fetch_field array mysqli_result fetch_fields object mysqli_result fetch_object string class_name array params mixed mysqli_result fetch_row bool mysqli_result field_seek int fieldnr void mysqli_result free 20 7 3 11 1 mysqli_result current_field mysqli_field_tell Copyright 1997 2012 the PHP Documentation Group 2...

Страница 2498: ...orld check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit query SELECT Name SurfaceArea from Country ORDER BY Code LIMIT 5 if result mysqli query query Get field information for all columns while finfo result fetch_field get fieldpointer offset currentfield result current_field printf Column d n currentfield printf Name s n finfo name printf Table s n finfo ...

Страница 2499: ...th printf Flags d n finfo flags printf Type d n n finfo type mysqli_free_result result close connection mysqli_close link The above examples will output Column 1 Name Name Table Country max Len 11 Flags 1 Type 254 Column 2 Name SurfaceArea Table Country max Len 10 Flags 32769 Type 4 See Also mysqli_fetch_field mysqli_field_seek 20 7 3 11 2 mysqli_result data_seek mysqli_data_seek Copyright 1997 20...

Страница 2500: ...eturn Values Returns TRUE on success or FALSE on failure Notes Note This function can only be used with buffered results attained from the use of the mysqli_store_result or mysqli_query functions Examples Example 20 184 Object oriented style php Open a connection mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_...

Страница 2501: ... printf City s Countrycode s n row 0 row 1 free result set mysqli_free_result result close connection mysqli_close link The above examples will output City Benin City Countrycode NGA See Also mysqli_store_result mysqli_fetch_row mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_object mysqli_query mysqli_num_rows 20 7 3 11 3 mysqli_result fetch_all mysqli_fetch_all Copyright 1997 2012 the PHP Doc...

Страница 2502: ... MySQL Native Driver Only Available only with mysqlnd As mysqli_fetch_all returns all the rows as an array in a single step it may consume more memory than some similar functions such as mysqli_fetch_array which only returns one row at a time from the result set Further if you need to iterate over the result set you will need a looping construct that will further impact performance For these reaso...

Страница 2503: ...numerically indexed version of the row must be used Parameters result Procedural style only A result set identifier returned by mysqli_query mysqli_store_result or mysqli_use_result resulttype This optional parameter is a constant indicating what type of array should be produced from the current row data The possible values for this parameter are the constants MYSQLI_ASSOC MYSQLI_NUM or MYSQLI_BOT...

Страница 2504: ...er my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit query SELECT Name CountryCode FROM City ORDER by ID LIMIT 3 result mysqli_query link query numeric array row mysqli_fetch_array result MYSQLI_NUM printf s s n row 0 row 1 associative array row mysqli_fetch_array result MYSQLI_ASSOC printf s s n row Name row CountryCode associative and ...

Страница 2505: ... sensitive Note This function sets NULL fields to the PHP NULL value Parameters result Procedural style only A result set identifier returned by mysqli_query mysqli_store_result or mysqli_use_result Return Values Returns an associative array of strings representing the fetched row in the result set where each key in the array represents the name of one of the result set s columns or NULL if there ...

Страница 2506: ...al style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit query SELECT Name CountryCode FROM City ORDER by ID DESC LIMIT 50 5 if result mysqli_query link query fetch associative array while row mysqli_fetch_assoc result printf s s n row Name row CountryCode free result set mysqli_free_result res...

Страница 2507: ...92 168 1 1 root 127 0 0 1 dude localhost lebowski localhost root 192 168 1 1 root 127 0 0 1 dude localhost lebowski localhost See Also mysqli_fetch_array mysqli_fetch_row mysqli_fetch_object mysqli_query mysqli_data_seek 20 7 3 11 6 mysqli_result fetch_field_direct mysqli_fetch_field_direct Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_result fetch_field_direct mysqli_fetch_field_dir...

Страница 2508: ...le name if an alias was specified def The default value for this field represented as a string max_length The maximum width of the field for the result set length The width of the field as specified in the table definition charsetnr The character set number for the field flags An integer representing the bit flags for the field type The data type used for this field decimals The number of decimals...

Страница 2509: ...ld information for column SurfaceArea finfo mysqli_fetch_field_direct result 1 printf Name s n finfo name printf Table s n finfo table printf max Len d n finfo max_length printf Flags d n finfo flags printf Type d n finfo type mysqli_free_result result close connection mysqli_close link The above examples will output Name SurfaceArea Table Country max Len 10 Flags 32769 Type 4 See Also mysqli_num_...

Страница 2510: ...roperties Property Description name The name of the column orgname Original column name if an alias was specified table The name of the table this field belongs to if not calculated orgtable Original table name if an alias was specified def Reserved for default value currently always db Database since PHP 5 3 6 catalog The catalog name always def since PHP 5 3 6 max_length The maximum width of the...

Страница 2511: ...l style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit query SELECT Name SurfaceArea from Country ORDER BY Code LIMIT 5 if result mysqli_query link query Get field information for all fields while finfo mysqli_fetch_field result printf Name s n finfo name printf Table s n finfo table printf ma...

Страница 2512: ...with the single difference that instead of returning one object at a time for each field the columns are returned as an array of objects Parameters result Procedural style only A result set identifier returned by mysqli_query mysqli_store_result or mysqli_use_result Return Values Returns an array of objects which contains field definition information or FALSE if no field information is available T...

Страница 2513: ...mation for all columns finfo result fetch_fields foreach finfo as val printf Name s n val name printf Table s n val table printf max Len d n val max_length printf Flags d n val flags printf Type d n n val type result close close connection mysqli close Example 20 196 Procedural style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect...

Страница 2514: ...ocumentation Group 2230 mysqli_result fetch_object mysqli_fetch_object Returns the current row of a result set as an object Description Object oriented style object mysqli_result fetch_object string class_name array params Procedural style object mysqli_fetch_object mysqli_result result string class_name array params The mysqli_fetch_object will return the current row result set as an object where...

Страница 2515: ...rows in resultset Note Field names returned by this function are case sensitive Note This function sets NULL fields to the PHP NULL value Changelog Version Description 5 0 0 Added the ability to return as a different object Examples Example 20 197 Object oriented style php mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysql...

Страница 2516: ...yCode free result set mysqli_free_result result close connection mysqli_close link The above examples will output Pueblo USA Arvada USA Cape Coral USA Green Bay USA Santa Clara USA See Also mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_row mysqli_query mysqli_data_seek 20 7 3 11 10 mysqli_result fetch_row mysqli_fetch_row Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_result fetc...

Страница 2517: ...ore rows in result set Note This function sets NULL fields to the PHP NULL value Examples Example 20 199 Object oriented style php mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit query SELECT Name CountryCode FROM City ORDER by ID DESC LIMIT 50 5 if result mysqli query query fetch object array while ...

Страница 2518: ...i_fetch_assoc mysqli_fetch_object mysqli_query mysqli_data_seek 20 7 3 11 11 mysqli_result field_count mysqli_num_fields Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_result field_count mysqli_num_fields Get the number of fields in a result Description Object oriented style int mysqli_result field_count Procedural style int mysqli_num_fields mysqli_result result Returns the number of...

Страница 2519: ..._count printf Result set has d fields n field_cnt close result set result close close connection mysqli close Example 20 202 Procedural style php link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit if result mysqli_query link SELECT FROM City ORDER BY ID LIMIT 1 determine number of fields in result set...

Страница 2520: ...et The next call to mysqli_fetch_field will retrieve the field definition of the column associated with that offset Note To seek to the beginning of a row pass an offset value of zero Parameters result Procedural style only A result set identifier returned by mysqli_query mysqli_store_result or mysqli_use_result fieldnr The field number This value must be in the range from 0 to number of fields 1 ...

Страница 2521: ...ysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit query SELECT Name SurfaceArea from Country ORDER BY Code LIMIT 5 if result mysqli_query link query Get field information for 2nd column mysqli_field_seek result 1 finfo mysqli_fetch_field result printf Name s n finfo name printf Table s n finfo table printf...

Страница 2522: ...emory associated with the result Note You should always free your result with mysqli_free_result when your result object is not needed anymore Parameters result Procedural style only A result set identifier returned by mysqli_query mysqli_store_result or mysqli_use_result Return Values No value is returned See Also mysqli_query mysqli_stmt_store_result mysqli_store_result mysqli_use_result 20 7 3 ...

Страница 2523: ...if an error occurred mysqli_fetch_lengths is valid only for the current row of the result set It returns FALSE if you call it before calling mysqli_fetch_row array object or after retrieving all rows in the result Examples Example 20 205 Object oriented style php mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_...

Страница 2524: ...Length 3 Field 2 has Length 5 Field 3 has Length 13 Field 4 has Length 9 Field 5 has Length 6 Field 6 has Length 1 Field 7 has Length 6 Field 8 has Length 4 Field 9 has Length 6 Field 10 has Length 6 Field 11 has Length 5 Field 12 has Length 44 Field 13 has Length 7 Field 14 has Length 3 Field 15 has Length 2 20 7 3 11 15 mysqli_result num_rows mysqli_num_rows Copyright 1997 2012 the PHP Documenta...

Страница 2525: ...ing Examples Example 20 207 Object oriented style php mysqli new mysqli localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit if result mysqli query SELECT Code Name FROM Country ORDER BY Name determine number of rows result set row_cnt result num_rows printf Result set has d rows n row_cnt close result set result close clo...

Страница 2526: ...sqli_query 20 7 3 12 The mysqli_driver class mysqli_driver Copyright 1997 2012 the PHP Documentation Group 2230 MySQLi Driver mysqli_driver mysqli_driver Properties public readonly string client_info public readonly string client_version public readonly string driver_version public readonly string embedded public bool reconnect public int report_mode Methods void mysqli_driver embedded_server_end ...

Страница 2527: ...mbedded_server_end Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_driver embedded_server_end mysqli_embedded_server_end Stop embedded server Description Object oriented style void mysqli_driver embedded_server_end Procedural style void mysqli_embedded_server_end Warning This function is currently not documented only its argument list is available 20 7 3 12 2 mysqli_driver embedded_ser...

Страница 2528: ...g Depending on the flags it reports errors from mysqli function calls or queries that don t use an index or use a bad index Parameters flags Table 20 54 Supported flags Name Description MYSQLI_REPORT_OFF Turns reporting off MYSQLI_REPORT_ERROR Report errors from mysqli function calls MYSQLI_REPORT_STRICT Throw mysqli_sql_exception for errors instead of warnings MYSQLI_REPORT_INDEX Report if no ind...

Страница 2529: ...d index result mysqli query SELECT Name FROM City WHERE population 50000 result close mysqli close catch mysqli_sql_exception e echo e __toString Example 20 210 Procedural style php activate reporting mysqli_report MYSQLI_REPORT_ALL link mysqli_connect localhost my_user my_password world check connection if mysqli_connect_errno printf Connect failed s n mysqli_connect_error exit this query should ...

Страница 2530: ...ssage public sqlstate public errno Methods public mysqli_warning __construct public void mysqli_warning next message Message string sqlstate SQL state errno Error number 20 7 3 13 1 mysqli_warning __construct Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_warning __construct The __construct purpose Description public mysqli_warning __construct Warning This function is currently not do...

Страница 2531: ...ception class mysqli_sql_exception Copyright 1997 2012 the PHP Documentation Group 2230 The mysqli exception handling class mysqli_sql_exception mysqli_sql_exceptionextends RuntimeException Properties protected code protected sqlstate message The error message file The file with the error line The line with the error code The code causing the error sqlstate The sql state with the error 20 7 3 15 A...

Страница 2532: ...esult Description This function is an alias of mysqli_stmt_bind_result Warning This function has been DEPRECATED as of PHP 5 3 0 and REMOVED as of PHP 5 4 0 See Also mysqli_stmt_bind_result 20 7 3 15 3 mysqli_client_encoding Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_client_encoding Alias of mysqli_character_set_name Description This function is an alias of mysqli_character_set_na...

Страница 2533: ...yle bool mysqli_disable_reads_from_master mysqli link Warning This function is currently not documented only its argument list is available Warning This function has been DEPRECATED and REMOVED as of PHP 5 3 0 20 7 3 15 6 mysqli_disable_rpl_parse Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_disable_rpl_parse Disable RPL parse Description bool mysqli_disable_rpl_parse mysqli link War...

Страница 2534: ...e Enable RPL parse Description bool mysqli_enable_rpl_parse mysqli link Warning This function is currently not documented only its argument list is available Warning This function has been DEPRECATED and REMOVED as of PHP 5 3 0 20 7 3 15 9 mysqli_escape_string Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_escape_string Alias of mysqli_real_escape_string Description This function is a...

Страница 2535: ...P 5 4 0 See Also mysqli_stmt_fetch 20 7 3 15 12 mysqli_get_cache_stats Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_get_cache_stats Returns client Zval cache statistics Description array mysqli_get_cache_stats Warning This function is currently not documented only its argument list is available Returns client Zval cache statistics Available only with mysqlnd Parameters Return Values...

Страница 2536: ...sed 0 slow_queries 0 buffered_sets 0 unbuffered_sets 0 ps_buffered_sets 0 ps_unbuffered_sets 0 flushed_normal_sets 0 flushed_ps_sets 0 ps_prepared_never_executed 0 ps_prepared_once_executed 0 rows_fetched_from_server_normal 0 rows_fetched_from_server_ps 0 rows_buffered_from_client_normal 0 rows_buffered_from_client_ps 0 rows_fetched_from_client_normal_buffered 0 rows_fetched_from_client_normal_unb...

Страница 2537: ...text_fetched_string 0 proto_text_fetched_blob 0 proto_text_fetched_enum 0 proto_text_fetched_set 0 proto_text_fetched_geometry 0 proto_text_fetched_other 0 proto_binary_fetched_null 0 proto_binary_fetched_bit 0 proto_binary_fetched_tinyint 0 proto_binary_fetched_short 0 proto_binary_fetched_int24 0 proto_binary_fetched_int 0 proto_binary_fetched_bigint 0 proto_binary_fetched_decimal 0 proto_binary...

Страница 2538: ...ry mysqli link string query Warning This function is currently not documented only its argument list is available Warning This function has been DEPRECATED and REMOVED as of PHP 5 3 0 20 7 3 15 15 mysqli_param_count Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_param_count Alias for mysqli_stmt_param_count Description This function is an alias of mysqli_stmt_param_count Warning This ...

Страница 2539: ...REMOVED as of PHP 5 3 0 20 7 3 15 18 mysqli_rpl_probe Copyright 1997 2012 the PHP Documentation Group 2230 mysqli_rpl_probe RPL probe Description bool mysqli_rpl_probe mysqli link Warning This function is currently not documented only its argument list is available Warning This function has been DEPRECATED and REMOVED as of PHP 5 3 0 20 7 3 15 19 mysqli_send_long_data Copyright 1997 2012 the PHP D...

Страница 2540: ...VED as of PHP 5 3 0 20 7 3 16 Changelog Copyright 1997 2012 the PHP Documentation Group 2230 The following changes have been made to classes functions methods of this extension 20 7 4 MySQL Functions PDO_MYSQL MySQL PDO Copyright 1997 2012 the PHP Documentation Group 2230 PDO_MYSQL is a driver that implements the PHP Data Objects PDO interface to enable access from PHP to MySQL 3 x 4 x and 5 x dat...

Страница 2541: ...er supported 5 3 9 Added SSL support with mysqlnd and OpenSSL 5 3 7 Added SSL support with libmysqlclient and OpenSSL The constants below are defined by this driver and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime In addition these driver specific constants should only be used if you are using this driver Using driver specific attribu...

Страница 2542: ...eger Return the number of found matched rows not the number of changed rows PDO MYSQL_ATTR_IGNORE_SPACE integer Permit spaces after function names Makes all functions names reserved words PDO MYSQL_ATTR_COMPRESS integer Enable network communication compression This is not supported when compiled against mysqlnd PDO MYSQL_ATTR_SSL_CA integer The file path to the SSL certificate authority This exist...

Страница 2543: ...mysql host The hostname on which the database server resides port The port number where the database server is listening dbname The name of the database unix_socket The MySQL Unix socket shouldn t be used with host or port charset The character set See the character set concepts documentation for more information Prior to PHP 5 3 6 this element was silently ignored The same behaviour can be partly...

Страница 2544: ... compiled against mysqlnd a default socket can be set thru the pdo_mysql default_socket setting 20 7 5 MySQL Native Driver Mysqlnd Copyright 1997 2012 the PHP Documentation Group 2230 MySQL Native Driver is a replacement for the MySQL Client Library libmysqlclient MySQL Native Driver is part of the official PHP sources as of PHP 5 3 0 The MySQL database extensions MySQL extension mysqli and PDO MY...

Страница 2545: ...s part of the standard distribution So you do not need MySQL installed in order to build PHP or run PHP database applications Because MySQL Native Driver is written as a PHP extension it is tightly coupled to the workings of PHP This leads to gains in efficiency especially when it comes to memory usage as the driver uses the PHP memory management system It also supports the PHP memory limit Using ...

Страница 2546: ...Authentication Plugin support was added Installation on Unix The MySQL database extensions must be configured to use the MySQL Client Library In order to use the MySQL Native Driver PHP needs to be built specifying that the MySQL database extensions are compiled with MySQL Native Driver support This is done through configuration options prior to building the PHP source code For example to build th...

Страница 2547: ..._public_key PHP_INI_PERDIR Available since PHP 5 5 0 For further details and definitions of the PHP_INI_ modes see the http www php net manual en configuration changes modes Here s a short explanation of the configuration directives mysqlnd collect_statistics boolean Enables the collection of various client statistics which can be accessed through mysqli_get_client_stats mysqli_get_connection_stat...

Страница 2548: ...d F Marks each debugger output line with the name of the source file containing the macro causing the output i Marks each debugger output line with the PID of the current process L Marks each debugger output line with the name of the source file line number of the macro causing the output n Marks each debugger output line with the current function nesting depth o file Similar to a file but overwri...

Страница 2549: ...error message 2006 MySQL Server has gone away The MySQL Client Library sets a default timeout of 365 24 3600 seconds 1 year and waits for other timeouts to occur such as TCP IP timeouts mysqlnd now uses the same very long timeout The value is configurable through a new php ini setting mysqlnd net_read_timeout mysqlnd net_read_timeout gets used by any extension ext mysql ext mysqli PDO_MySQL that u...

Страница 2550: ...d packet The MySQL client server protocol encapsulates all its commands in packets The packets consist of a small header and a body with the actual payload The size of the body is encoded in the header mysqlnd reads the body in chunks of MIN header size mysqlnd net_read_buffer_size bytes If a packet body is larger than mysqlnd net_read_buffer_size bytes mysqlnd has to call read multiple times The ...

Страница 2551: ...mysqli_get_client_stats mysqli_get_connection_stats mysqli_get_cache_stats Note Statistics are aggregated among all extensions that use MySQL Native Driver For example when compiling both ext mysql and ext mysqli against MySQL Native Driver both function calls of ext mysql and ext mysqli will change the statistics There is no way to find out how much a certain API call of any extension that has be...

Страница 2552: ...threads before a result set can be freed Prepared Statements use unbuffered result sets by default However you can use mysqli_stmt_store_result to enable buffered result sets Statistics returned by MySQL Native Driver The following tables show a list of statistics returned by the mysqli_get_client_stats mysqli_get_connection_stats and mysqli_get_cache_stats functions Table 20 59 Returned mysqlnd s...

Страница 2553: ...NFILE INSERT UPDATE SELECT error message Used for debugging CS protocol implementation Note that the total size in bytes includes the size of the header packet 4 bytes see protocol overhead packets_received_rset_header Connection Number of MySQL Client Server protocol result set header packets Used for debugging CS protocol implementation Note that the total size in bytes includes the size of the ...

Страница 2554: ...nse Connection Number of MySQL Client Server protocol OK for Prepared Statement Initialization packets prepared statement init packets Only useful for debugging CS protocol implementation Note that the total size in bytes includes the size of the header packet 4 bytes see protocol overhead bytes_received_change_user_packet Connection Total size in bytes of MySQL Client Server protocol COM_CHANGE_U...

Страница 2555: ...close This statistic is available as of PHP version 5 3 4 bytes_received_real_data_ps Connection Number of bytes of the payload fetched by the PHP client from mysqlnd using the prepared statement protocol This is the size of the actual data contained in result sets that originate from prepared statements and which has been fetched by the PHP client The value will not be increased if the result set...

Страница 2556: ... mysqld start option log slow queries If you want these queries to be reported you can use mysqli_report MYSQLI_REPORT_INDEX to make ext mysqli throw an exception If you prefer a warning instead of an exception use mysqli_report MYSQLI_REPORT_INDEX MYSQLI_REPORT_STRICT slow_queries Connection SQL statements that took more than long_query_time seconds to execute and required at least min_examined_r...

Страница 2557: ...ust be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error If the application does not fetch all rows from an unbuffered result set mysqlnd does implicitly fetch the result set to clear the line See also rows_skipped_normal rows_skipped_ps Some possible causes for an implicit flush Faulty client application Client stopped reading after it found wh...

Страница 2558: ...fetched from MySQL regardless if the client application has consumed them or not Some of the rows may not have been fetched by the client application but have been flushed implicitly See also packets_received_rset_row rows_buffered_from_client_normal rows_buffered_from_client_ps Connection Total number of successfully buffered rows originating from a normal query or a prepared statement This is th...

Страница 2559: ...ult implicit_free_result Connection Process only during prepared statement cleanup Total number of freed result sets The free is always considered explicit but for result sets created by an init command for example mysqli_options MYSQLI_INIT_COMMAND proto_text_fetched_null proto_text_fetched_bit proto_text_fetched_tinyint proto_text_fetched_short proto_text_fetched_int24 proto_text_fetched_int pro...

Страница 2560: ..._fetched_string MYSQL_TYPE_TINY_BLOB MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB MYSQL_TYPE_BLOB proto_text_fetched_blob MYSQL_TYPE_ENUM proto_text_fetched_enum MYSQL_TYPE_SET proto_text_fetched_set MYSQL_TYPE_GEOMETRY proto_text_fetched_geometry Any MYSQL_TYPE_ not listed before there should be none proto_text_fetched_other Note that the MYSQL_ type constants may not be associated with the very s...

Страница 2561: ...ysqli link real_connect will cause a reconnect But link new mysqli link connect will not because link connect will explicitly close the existing connection before a new connection is established pconnect_success Connection Total number of successful persistent connection attempts Note that connect_success holds the sum of successful persistent and non persistent connection attempts The number of s...

Страница 2562: ... if your script stops unexpectedly and PHP shuts down the connections for you init_command_executed_count Connection Total number of init command executions for example mysqli_options MYSQLI_INIT_COMMAND The number of successful executions is init_command_executed_count init_command_failed_count init_command_failed_count Connection Total number of failed init commands Table 20 62 Returned mysqlnd ...

Страница 2563: ...unt mem_emalloc_ammount mem_ecalloc_count mem_ecalloc_ammount mem_erealloc_count mem_erealloc_ammount mem_efree_count mem_malloc_count mem_malloc_ammount mem_calloc_count mem_calloc_ammount mem_realloc_count mem_realloc_ammount mem_free_count Process Memory management calls Development only command_buffer_too_small Connection Number of network command buffer extensions while sending commands from ...

Страница 2564: ...string column with a very long default value 1900 bytes No bug report on this exists it should happen rarely As of PHP 5 3 2 mysqlnd does not allow setting buffers smaller than 4096 bytes connection_reused 20 7 5 6 Notes Copyright 1997 2012 the PHP Documentation Group 2230 This section provides a collection of miscellaneous notes on MySQL Native Driver usage Using mysqlnd means using PHP streams f...

Страница 2565: ...made 100 transparent to PHP applications No application changes are needed because plugins operate on a different layer The mysqlnd plugin can be thought of as operating in a layer below mysqlnd The following list represents some possible applications of mysqlnd plugins Load Balancing Read Write Splitting An example of this is the PECL mysqlnd_ms Master Slave extension This extension splits read w...

Страница 2566: ...mon a background process MySQL Proxy can recall earlier decisions as all state can be retained However a mysqlnd plugin is bound to the request based lifecycle of PHP MySQL Proxy can also share one time computed results among multiple application servers A mysqlnd plugin would need to store data in a persistent medium to be able to do this Another daemon would need to be used for this purpose such...

Страница 2567: ...on number as follows Table 20 65 MYSQLND_VERSION_ID calculation table Version part Example Major 10000 5 10000 50000 Minor 100 0 100 0 Patch 7 7 MYSQLND_VERSION_ID 50007 During development developers should refer to the mysqlnd version number for compatibility and version tests as several iterations of mysqlnd could occur during the lifetime of a PHP development branch with a single PHP version nu...

Страница 2568: ...ion required for request processing As the request cycle ends the engine calls the request shutdown RSHUTDOWN function of each extension so the extension can perform any cleanup required How a plugin works A mysqlnd plugin works by intercepting calls made to mysqlnd by extensions that use mysqlnd This is achieved by obtaining the mysqlnd function table backing it up and replacing it by a custom fu...

Страница 2569: ...in_ object _data family When allocating an object mysqlnd reserves space at the end of the object to hold a void pointer to arbitrary data mysqlnd reserves space for one void pointer per plugin The following table shows how to calculate the position of the pointer for a specific plugin Table 20 67 Pointer calculations for mysqlnd Memory address Contents 0 Beginning of the mysqlnd object C struct n...

Страница 2570: ...tocol MYSQLND_PROTOCOL MINIT or later Yes mysqlnd_protocol_get_methods or object method function table manipulation You must not manipulate function tables at any time later than MINIT if it is not allowed according to the above table Some classes contain a pointer to the method function table All instances of such a class will share the same function table To avoid chaos in particular in threaded...

Страница 2571: ... status Derived method must call parent Destructor Connection yes after method execution free_contents end_psession Resultset yes after method execution free_result Resultset Meta yes after method execution free Statement yes after method execution dtor free_stmt_content Network yes after method execution free Wire protocol yes after method execution free The destructors are the appropriate place ...

Страница 2572: ... API Application services or modules Application service APIs or module APIs The mysqlnd plugin concept employs these features and additionally enjoys an open architecture No Restrictions A plugin has full access to the inner workings of mysqlnd There are no security limits or restrictions Everything can be overwritten to implement friendly or hostile algorithms It is recommended you only deploy p...

Страница 2573: ...ls its connect method which has been subclassed by ext mysqlnd_plugin ext mysqlnd_plugin calls the userspace hook proxy connect registered by the user The userspace hook changes the connection host IP from 192 168 2 29 to 127 0 0 1 and returns the connection established by parent connect ext mysqlnd_plugin performs the equivalent of parent connect 127 0 0 1 by calling the original mysqlnd method f...

Страница 2574: ...pace callback b Or original mysqlnd method if userspace callback not set You need to carry out the following 1 Write a class mysqlnd_plugin_connection in C 2 Accept and register proxy object through mysqlnd_plugin_set_conn_proxy 3 Call userspace proxy methods from C optimization zend_interfaces h Userspace object methods can either be called using call_user_function or you can operate at a level c...

Страница 2575: ..._conn_proxy fetch_userspace_proxy if global_user_conn_proxy call userspace proxy ret MY_ZEND_CALL_METHOD_WRAPPER global_user_conn_proxy host else or original mysqlnd method do nothing be transparent ret org_methods connect conn host user passwd passwd_len db db_len port socket mysql_flags TSRMLS_CC return ret Calling userspace simple arguments my_mysqlnd_plugin c MYSQLND_METHOD my_conn_class conne...

Страница 2576: ...f an overwritten method As a result of subclassing it is possible to refine only selected methods and you can choose to have pre or post hooks Buildin class mysqlnd_plugin_connection connect my_mysqlnd_plugin_classes c PHP_METHOD mysqlnd_plugin_connection connect simplified zval mysqlnd_rsrc MYSQLND conn char host int host_len if zend_parse_parameters ZEND_NUM_ARGS TSRMLS_CC rs mysqlnd_rsrc host h...

Страница 2577: ... application changes required dependent on the required usage scenario Lazy connections connections to master and slave servers are not opened before a SQL statement is executed Optional automatic use of master after the first write in a web request to lower the possible impact of replication lag Can be used with any MySQL clustering solution MySQL Replication Read write splitting is done by the p...

Страница 2578: ...ct queries to a specific group Grouping can be used to partition shard the data or to cure the issue of hotspots with updates MySQL Replication filters are supported through the table filter 20 7 6 2 Limitations Copyright 1997 2012 the PHP Documentation Group 2230 The built in read write split mechanism is very basic Every query which starts with SELECT is considered a read request to be sent to a...

Страница 2579: ... to use with support for the mysqlnd library PECL mysqlnd_ms is a plugin for the mysqlnd library To use the plugin with any of the PHP MySQL extensions the extension has to use the mysqlnd library Then load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_ms enable Example 20 215 Enabling the plugin php ini mysqlnd_ms ...

Страница 2580: ...nt and can cause issues in certain cases The reference sections about connection pooling and switching transaction handling fail over load balancing and read write splitting all provide more details And potential pitfalls are described later in this guide It is the responsibility of the application to handle potential issues caused by connection switches by configuring a master with at least one s...

Страница 2581: ...vior of those extensions Whenever a connection to MySQL is being opened the plugin compares the host parameter value of the connect call with the section names from the plugin specific configuration file If for example the plugin specific configuration file has a section myapp then the section should be referenced by opening a MySQL connection to the host myapp Example 20 219 Plugin specific confi...

Страница 2582: ...ecuting statements php Load balanced following myapp section rules from the plugins config file mysqli new mysqli myapp username password database if mysqli_connect_errno Of course your error handling is nicer die sprintf d s n mysqli_connect_errno mysqli_connect_error Statements will be run on the master if mysqli query DROP TABLE IF EXISTS test printf d s n mysqli errno mysqli error if mysqli qu...

Страница 2583: ... myrole master printf d s n mysqli errno mysqli error Connection 2 run on slave because SELECT if res mysqli query SELECT myrole AS _role printf d s n mysqli errno mysqli error else row res fetch_assoc res close printf myrole s n row _role mysqli close The above example will output myrole The example opens a load balanced connection and executes two statements The first statement SET myrole master...

Страница 2584: ...rewall Three SQL hints are supported by the plugin The MYSQLND_MS_MASTER_SWITCH hint makes the plugin run a statement on the master MYSQLND_MS_SLAVE_SWITCH enforces the use of the slave and MYSQLND_MS_LAST_USED_SWITCH will run a statement on the same server that was used for the previous statement The plugin scans the beginning of a statement for the existence of an SQL hint SQL hints are only rec...

Страница 2585: ...no mysqli_connect_error Force use of master master has always fresh and current data if mysqli query sprintf s SELECT critical_data FROM important_table MYSQLND_MS_MASTER_SWITCH printf d s n mysqli errno mysqli error A use case may include the creation of tables on a slave If an SQL hint is not given then the plugin will send CREATE and INSERT statements to the master Use the SQL hint MYSQLND_MS_S...

Страница 2586: ...on No kind of MySQL load balancer can detect transaction boundaries without any kind of hint from the application You can either use SQL hints to work around this limitation Alternatively you can activate transaction API call monitoring In the latter case you must use API calls only to control transactions see below Example 20 228 Plugin config with one slave and one master myapp myapp master mast...

Страница 2587: ...g SQL statements such as SET AUTOCOMMIT 0 This makes it possible for the plugin to become transaction aware In this case you do not need to use SQL hints If using PHP 5 4 0 or newer API calls that enable autocommit mode and when setting the plugin configuration option trx_stickiness master the plugin can automatically disable load balancing and connection switches for SQL transactions In this conf...

Страница 2588: ...ined in the transaction handling concepts section 20 7 6 4 6 Service level and consistency Copyright 1997 2012 the PHP Documentation Group 2230 Version requirement Service levels have been introduced in PECL mysqlnd_ms version 1 2 0 alpha mysqlnd_ms_set_qos is available with PHP 5 4 0 or newer Different types of MySQL cluster solutions offer different service and data consistency levels to their u...

Страница 2589: ... consistency stale data allowed if mysqlnd_ms_set_qos mysqli MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL die sprintf d s n mysqli errno mysqli error Plugin picks any slave stale data is allowed if res mysqli query SELECT item price FROM specials die sprintf d s n mysqli errno mysqli error Service levels can be set in the plugins configuration file and at runtime using mysqlnd_ms_set_qos In the example the...

Страница 2590: ...NTUAL die sprintf d s n mysqli errno mysqli error The eventual consistency service level can be used with an optional parameter to set a maximum slave lag for choosing slaves If set the plugin checks SHOW SLAVE STATUS for all configured slaves In case of the example only slaves for which Slave_IO_Running Yes Slave_SQL_Running Yes and Seconds_Behind_Master 4 is true are considered for executing the...

Страница 2591: ...e 20 236 Fail over not set myapp master master_0 host localhost socket tmp mysql sock slave slave_0 host 127 0 0 1 port 3306 Example 20 237 No slave within time limit php mysqli new mysqli myapp username password database if mysqli Of course your error handling is nicer die sprintf d s n mysqli_connect_errno mysqli_connect_error Read from slaves lagging no more than four seconds ret mysqlnd_ms_set...

Страница 2592: ...nter is incremented whenever a transaction is committed on the master Slaves replicate the table The counter serves two purposes In case of a master failure it helps the database administrator to identify the most recent slave for promoting it to the new master The most recent slave is the one with the highest counter value Applications can use the global transaction ID to search for slaves which ...

Страница 2593: ...ocalhost socket tmp mysql sock slave slave_0 host 127 0 0 1 port 3306 global_transaction_id_injection on_commit UPDATE test trx SET trx_id trx_id 1 report_error true Example 20 240 Transparent global transaction ID injection php mysqli new mysqli myapp username password database if mysqli Of course your error handling is nicer die sprintf d s n mysqli_connect_errno mysqli_connect_error auto commit...

Страница 2594: ...inding an efficient solution for inclusion in the manual We appreciate your input Example 20 241 Plugin config SQL for fetching GTID myapp master master_0 host localhost socket tmp mysql sock slave slave_0 host 127 0 0 1 port 3306 global_transaction_id_injection on_commit UPDATE test trx SET trx_id trx_id 1 fetch_last_gtid SELECT MAX trx_id FROM test trx report_error true Example 20 242 Obtaining ...

Страница 2595: ...SQL statement which will return a GTID equal or greater to that created for the previous statement It is exactly the GTID created for the previous statement if no other clients have incremented the GTID in the time span between the statement execution and the SELECT to fetch the GTID Otherwise it is greater Example 20 243 Plugin config Checking for a certain GTID myapp master master_0 host localho...

Страница 2596: ...to high otherwise Use of the server side global transaction ID feature Starting with MySQL 5 6 5 m8 the MySQL Replication system features server side global transaction IDs Transaction identifiers are automatically generated and maintained by the server Users do not need to take care of maintaining them There is no need to setup any tables in advance or for setting on_commit A client side emulatio...

Страница 2597: ...ity of service to request read your writes Request session consistency read your writes if mysqlnd_ms_set_qos mysqli MYSQLND_MS_QOS_CONSISTENCY_SESSION die sprintf d s n mysqli errno mysqli error Assuming PECL mysqlnd has been explicitly told to deliver no consistency level higher than eventual consistency it is possible to replace a database node read access with a client side cache using time to...

Страница 2598: ...tual consistency and explicitly allow for caching This is done by calling mysqlnd_ms_set_qos Then the result set of every read only statement is cached for upto that many seconds as allowed with mysqlnd_ms_set_qos The actual TTL is lower or equal to the value set with mysqlnd_ms_set_qos The value passed to the function sets the maximum age seconds of the data delivered To calculate the actual TTL ...

Страница 2599: ...he usage If needed you can switch to read your writes session consistency In that case the cache will not be used and fresh data is read 20 7 6 4 9 Failover Copyright 1997 2012 the PHP Documentation Group 2230 By default the plugin does not attempt to fail over if connecting to a host fails This prevents pitfalls related to connection state It is recommended to manually handle connection errors in...

Страница 2600: ...Documentation Group 2230 Database clustering is done for various reasons Clusters can improve availability fault tolerance and increase performance by applying a divide and conquer approach as work is distributed over many machines Clustering is sometimes combined with partitioning and sharding to further break up a large complex task into smaller more manageable units The mysqlnd_ms plugin aims t...

Страница 2601: ...simulate_slave_failure port 0 slave_1 host 127 0 0 1 port 3311 filters node_groups Partition_A master master_0 slave slave_0 roundrobin Example 20 253 Manual partitioning using SQL hints php function select mysqli msg hint Note weak test two connections to two servers may have the same thread id sql sprintf SELECT CONNECTION_ID AS _thread s AS _hint FROM DUAL msg if hint sql hint sql if res mysqli...

Страница 2602: ...rver If a query is recognized as read only it will be sent to one of the configured slave servers Statements are considered read only if they either start with SELECT the SQL hint ms slave or a slave had been chosen for running the previous query and the query started with the SQL hint ms last_used In all other cases the query will be sent to the MySQL replication master server For better portabil...

Страница 2603: ...ables Table locks Session system variables and session user variables The current database set using USE and other state chaining SQL commands Prepared statements HANDLER variables Locks acquired with GET_LOCK Connection switches happen right before queries are executed The plugin does not switch the current connection until the next statement is executed Replication issues See also the MySQL refe...

Страница 2604: ...llowing connection library calls each changed state and their execution is recorded for later use when lazy connections are opened This helps ensure that the connection state of all connections in the connection pool are comparable Library call Notes Version change_user User password and database recorded for future use Since 1 1 0 select_db Database recorded for future use Since 1 1 0 set_charset...

Страница 2605: ...ples of using SQL hints or the API monitoring in the examples section The details behind the API monitoring which makes the plugin transaction aware are described below Beginning with PHP 5 4 0 the mysqlnd library allows this plugin to subclass the library C API call set_autocommit to detect the status of autocommit mode The PHP MySQL extensions either issue a query such as SET AUTOCOMMIT 0 1 or u...

Страница 2606: ..._connect_errno mysqli_connect_error Connection 1 connection bound SQL user variable no SELECT thus run on master if mysqli query SET myrole master printf d s n mysqli errno mysqli error Connection 2 run on slave because SELECT provoke connection error if res mysqli query SELECT myrole AS _role printf d s n mysqli errno mysqli error else row res fetch_assoc res close printf myrole s n row _role mys...

Страница 2607: ...the default random once type Example 20 257 Most basic failover php mysqli new mysqli myapp username password database if mysqli_connect_errno Of course your error handling is nicer die sprintf d s n mysqli_connect_errno mysqli_connect_error Connection 1 connection bound SQL user variable no SELECT thus run on master if mysqli query SET myrole master printf d s n mysqli errno mysqli error Connecti...

Страница 2608: ...rvers and the slave server selected by the plugin is not available the plugin will raise an error after not executing the statement Default manual failover It is up to the application to handle the error and if required re issue the query to trigger the selection of another slave server for statement execution The plugin will make no attempts to failover automatically because the plugin cannot ens...

Страница 2609: ... you can assign to a server is 65535 Given two slaves of which one shall act as a standby and has been assigned a weight of 1 the standby will have to handle far less than one percent of the overall workload Failover and primary copy Please note if using a primary copy cluster such as MySQL Replication it is difficult to do connection failover in case of a master failure At any time there is only ...

Страница 2610: ...tement to a specific location by invoking mysqlnd_ms_is_select Note The built in read write splitter is not aware of multi statements Multi statements are seen as one statement The splitter will check the beginning of the statement to decide where to run the statement If for example a multi statement begins with SELECT 1 FROM DUAL INSERT INTO test id VALUES 1 the plugin will run it on a slave alth...

Страница 2611: ...he rest of the PHP request Output slave_0 Output of slave_0 and the statement to be executed is passed as input to the next filter Here roundrobin server list passed to filter is slave_0 Filter roundrobin Server list consists of one server only round robin will always return the same server If trying to use such a filter sequence the plugin may emit a warning like mysqlnd_ms Error while creating f...

Страница 2612: ...ta consistency levels that can be achieved The plugin knows about eventual consistency session consistency strong consistency Depending how a cluster is used it may be possible to achieve higher service levels than the default one For example a read from an asynchronous MySQL replication slave is eventual consistent Thus one may say the default consistency level of a MySQL replication cluster is e...

Страница 2613: ...e done the application can return to default service level Switching between service levels is only possible using mysqlnd_ms_set_qos Performance considerations A MySQL replication cluster cannot tell clients which slaves are capable of delivering which level of service Thus in some cases clients need to query the slaves to check their status PECL mysqlnd_ms transparently runs the necessary SQL in...

Страница 2614: ...side transparent global transaction ID injection In its most basic form a global transaction identifier is a counter which is incremented for every transaction executed on the master The counter is held in a table on the master Slaves replicate the counter table In case of a master failure a database administrator can easily identify the most recent slave for promiting it as a new master The most ...

Страница 2615: ...e following properties differ Client side emulation as shown in the manual is using an easy to compare sequence number for global transactions Multi master is not handled to keep the manual examples easy Server side built in feature is using a combination of a server identifier and a sequence number as a global transaction identifier Comparison cannot use numeric algebra Instead a SQL function mus...

Страница 2616: ...rol of cache usage and can request fresh data at any time if need be Thec ache usage can be enabled and disabled time during the execution of a script The cache will be used if mysqlnd_ms_set_qos sets the quality of service to eventual consistency and enables cache usage Cache usage is disabled by requesting higher consistency levels for example session consistency read your writes Once the qualit...

Страница 2617: ... the costs of the cache decision Suggestions on a better algorithm are always welcome 20 7 6 5 12 Supported clusters Copyright 1997 2012 the PHP Documentation Group 2230 Any application using any kind of MySQL cluster is faced with the same tasks Identify nodes capable of executing a given statement with the required service level Load balance requests within the list of candidates Automatic fail ...

Страница 2618: ...i for MySQL Replication myapp master master_1 host localhost socket tmp mysql57 sock slave slave_0 host 127 0 0 1 port 3308 slave_1 host 192 168 2 28 port 3306 filters random sticky 1 Primary copy with multi primaries MMM MySQL Multi Master MySQL Replication allows you to create cluster topologies with multiple masters primaries Write write conflicts are not handled by the replication system This ...

Страница 2619: ...r are called masters in the plugin configuration as they accept both reads and writes for their partition Using synchronous update everywhere clusters such as MySQL Cluster MySQL Cluster is a synchronous cluster solution All cluster nodes accept read and write requests In the context of the plugin all nodes shall be considered as masters Use the load balancing and fail over features only Disable t...

Страница 2620: ... empty slave list and to make the failover logic loop over all configured masters before emitting an error Please note the warnings about automatic failover given in the previous sections Example 20 262 Multiple primaries multi master php ini mysqlnd_ms enable 1 mysqlnd_ms config_file path to mysqlnd_ms_plugin ini mysqlnd_ms multi_master 1 mysqlnd_ms disable_rw_split 1 Example 20 263 Synchronous u...

Страница 2621: ... Runtime Configuration Copyright 1997 2012 the PHP Documentation Group 2230 The behaviour of these functions is affected by settings in php ini Table 20 72 Mysqlnd_ms Configure Options Name Default Changeable Changelog mysqlnd_ms enable 0 PHP_INI_SYSTEM mysqlnd_ms force_config_usage 0 PHP_INI_SYSTEM mysqlnd_ms ini_file PHP_INI_SYSTEM mysqlnd_ms config_file PHP_INI_SYSTEM mysqlnd_ms collect_statist...

Страница 2622: ...ependently of read write splitting If read write splitting is disabled only servers from the master list will be used for statement execution All configured slave servers will be ignored The SQL hint MYSQLND_MS_USE_SLAVE will not be recognized If found the statement will be redirected to a master Disabling read write splitting impacts the return value of mysqlnd_ms_query_is_select The function wil...

Страница 2623: ...nvert a PHP array to JSON php config array myapp array master array master_0 array host localhost socket tmp mysql sock slave array file_put_contents mysqlnd_ms ini json_encode config JSON_PRETTY_PRINT printf mysqlnd_ms ini file created n printf Dumping file contents n printf s n str_repeat 80 echo file_get_contents mysqlnd_ms ini printf n s n str_repeat 80 The above example will output mysqlnd_ms...

Страница 2624: ...0 0 1 or localhost If for example an application connects to localhost and a plugin configuration section localhost exists the semantics of the connect operation are changed The application will no longer only use the MySQL server running on the host localhost but the plugin will start to load balance MySQL queries following the rules from the localhost configuration section This way you can load ...

Страница 2625: ...rs of a server list and done so using the JSON object type Example 20 267 Master list using symbolic names master master_0 host localhost It is recommended to index the server lists with symbolic server names The alias names will be shown in error messages The order of servers is preserved and taken into account by mysqlnd_ms If for example you configure round robin load balancing strategy the fir...

Страница 2626: ...entry Filters replace the pick setting from prior versions The new random and roundrobin provide the same functionality Example 20 269 New roundrobin filter old functionality myapp master master_0 host localhost slave slave_0 host 192 168 78 136 port 3306 slave_1 host 192 168 78 137 port 3306 filters roundrobin The function mysqlnd_ms_set_user_pick_server has been removed Setting a callback is now...

Страница 2627: ...s are additionally buffered and emitted when a connection attempt is made Use the configuration directive mysqlnd_ms force_config_usage to set the error type used to display buffered errors By default an error of type E_WARNING will be emitted Example 20 272 Improved configuration file validation since 1 5 0 php mysqli new mysqli myapp username password database The above example will output Warni...

Страница 2628: ...OR when the plugin tries to connect to the server The error message may read mysqlnd_ms Cannot find host in s section in config in s on line d Since 1 1 0 port Database server TCP IP port Since 1 1 0 socket Database server Unix domain socket Since 1 1 0 db Database schemata Since 1 1 0 user MySQL database user Since 1 1 0 password MySQL database user password Since 1 1 0 connect_flags Connection f...

Страница 2629: ...rching for replicas which can offer a higher level of consistency than eventual consistency The statement must contain a placeholder GTID which is to be replaced with the global transaction identifier searched for by the plugin Please check the quickstart for examples Since 1 2 0 report_errors Whether to emit an error of type warning if an issue occurs while executing any of the configured SQL sta...

Страница 2630: ...s If no load balancing policy is set the plugin will default to random_once The random_once policy picks a random slave server when running the first read only statement The slave server will be used for all read only statements until the PHP script execution ends No load balancing policy is set and thus defaulting takes place if neither the random nor the roundrobin are part of a configuration se...

Страница 2631: ... pick a random server whenever a read only statement is to be executed The random once strategy picks a random slave server once and continues using the slave for the rest of the PHP web request Random once is a default if load balancing is not configured through a filter If the random filter is not given any arguments it stands for random load balancing policy Example 20 275 Random load balancing...

Страница 2632: ... Referencing error E_RECOVERABLE_ERROR mysqli_real_connect mysqlnd_ms Unknown server slave3 Using a wrong alias name with weight may result in an error similar to the shown above If weight is omitted the default weight of all servers is one Example 20 278 Assigning a weight for load balancing myapp master master1 host localhost socket var run mysql mysql sock slave slave1 host 192 168 2 28 port 33...

Страница 2633: ... input Outputs one server A filter sequence such as random roundrobin may cause a warning and an error message to be set on the connection handle when executing a statement List of filter arguments Keyword Description Version sticky Enables or disabled random once load balancing policy See above Since 1 2 0 weight Assigns a load balancing weight priority to a server Please see above for a descript...

Страница 2634: ...f a callback is recommended to expert users only because the callback has to cover all cases otherwise handled by the plugin The plugin will invoke the callback function for selecting a server from the lists of configured master and slave servers The callback function inspects the query to run and picks a server for query execution by returning the hosts URI as found in the master and slave list I...

Страница 2635: ... the application catches the error to ignore it follow up errors may be set on the connection handle for example mysqlnd_ms Specified callback pick_server is not a valid callback with the error code 2000 and the sqlstate HY000 Furthermore a warning may be emitted The following parameters are passed from the plugin to the callback Parameter Description Version connected_host URI of the currently co...

Страница 2636: ... 136 port 3306 filters user callback pick_server php function pick_server connected query masters slaves last_used_connection static slave_idx 0 static num_slaves NULL if is_null num_slaves num_slaves count slaves default fallback to the plugins build in logic ret NULL printf User has connected to s n connected printf deciding where to run s n query where mysqlnd_ms_query_is_select query switch wh...

Страница 2637: ... DUAL some read only query for a slave ret tcp 192 168 2 27 3306 User has connected to myapp deciding where to run SELECT 2 FROM DUAL some read only query for a slave ret tcp 192 168 78 136 3306 User has connected to myapp deciding where to run SELECT FROM table_on_slave_a_only access to table available only on slave A detected ret tcp 192 168 2 27 3306 Filter user_multi object The user_multi diff...

Страница 2638: ...st of servers to use The callback must return an array in s on line d In case the server list is not empty but has invalid servers key ids in it an error of type E_RECOVERABLE will the thrown with an error message like mysqlnd_ms User multi filter callback has returned an invalid list of servers to use Server id is negative in s on line d or similar Whether an error is emitted in case of an empty ...

Страница 2639: ...e group name Because user defined node group name is used as is as part of a SQL hint you should choose the name that is compliant with the SQL language Each node group entry must contain a list of master servers Additional slave servers are allowed Failing to provide a list of master for a node group name_of_group may cause an error of type E_RECOVERABLE_ERROR like mysqlnd_ms No masters configure...

Страница 2640: ...n this is acceptable In some cases higher consistency levels are needed for the application to work correct In those cases the quality_of_service can filter out cluster nodes which cannot deliver the necessary quality of service The quality_of_service filter can be replaced or created at runtime A successful call to mysqlnd_ms_set_qos removes all existing qos filter entries from the filter list an...

Страница 2641: ...t slave slave_0 host 192 168 2 27 port 3306 slave_1 host 192 168 78 136 port 3306 filters quality_of_service eventual_consistency age 123 session_consistency Request session consistency read your writes Allows use of all masters and all slaves which are in sync with the master If no further parameters are given slaves are filtered out as there is no reliable way to test if a slave has caught up to...

Страница 2642: ...er server Please note the automatic failover logic is applied when opening connections only Once a connection has been opened no automatic attempts are made to reopen it in case of an error If for example the server a connection is connected to is shut down and the user attempts to run a statement on the connection no automatic failover will be tried Instead an error will be reported If using fail...

Страница 2643: ...r Since 1 4 0 remember_failed Remember failures for the duration of a web request Default false If set to true the plugin will remember failed hosts and skip the hosts in all future load balancing made for the duration of the current web request Since 1 4 0 The feature is only available together with the random and roundrobin load balancing filter Use of the setting is recommended max_retries Maxi...

Страница 2644: ...connection pool The few dispatched actions are applied to already opened connections only Lazy connections opened in the future are not affected Only some settings are remembered and applied when lazy connections are opened Example 20 287 Disabling lazy connection myapp master master_0 host localhost slave slave_0 host 192 168 78 136 port 3306 lazy_connections 0 Please see also server_charset to o...

Страница 2645: ...r for the connection This has the additional benefit of removing the need to align the charset configuration of all servers used No matter what the default charset on any of the servers is the plugin will set the configured one as a default The plugin does not stop the user from changing the charset at any time using the set_charset call or corresponding SQL statements Please note that the use of ...

Страница 2646: ...9 Master on write for consistent reads myapp master master_0 host localhost slave slave_0 host 192 168 78 136 port 3306 master_on_write 1 Please note the quality_of_service filter introduced in version 1 2 0 alpha It gives finer control for example for achieving read your writes and it offers additional functionality introducing service levels All transaction stickiness settings including trx_stic...

Страница 2647: ...e offered by SQL statements The mysqli API has been modified to use these calls Since version 1 5 0 PECL mysqlnd_ms can monitor not only mysqli_autocommit but also mysqli_begin mysqli_commit and mysqli_rollback to detect transaction boundaries and stop load balancing for the duration of a transaction Example 20 290 Using master to execute transactions myapp master master_0 host localhost slave sla...

Страница 2648: ...before the plugin continues load balancing and switches the server Likewise you will want to start a new transaction immediately thereafter and disable auto commit mode again Not handling failed queries and not ending a failed transaction using API calls may cause all following commands emit errors such as Commands out of sync you can t run this command now Thus it is important to handle all error...

Страница 2649: ...application without changing the applications source code The master slave and pick configuration directives use a list like syntax Configuration directives supporting list like syntax may appear multiple times in a configuration section The plugin maintains the order in which entries appear when interpreting them For example the below example shows two slave configuration directives in the config...

Страница 2650: ...uted If using roundrobin the plugin iterates over the list of configured slave servers to pick a server for statement execution If the plugin reaches the end of the list it wraps around to the beginning of the list and picks the first configured slave server Setting more than one load balancing policy for a configuration section makes only sense in conjunction with user and mysqlnd_ms_set_user_pic...

Страница 2651: ...help with replication lag If an application runs an INSERT the plugin will by default use the master to execute all following statements including SELECT statements This helps to avoid problems with reads from slaves which have not replicated the INSERT yet trx_stickiness string Transaction stickiness policy Supported policies disabled default master Experimental feature The setting requires 5 4 0...

Страница 2652: ...ervers to be used for testing The most basic configuration is as follows putenv MYSQL_TEST_HOST localhost putenv MYSQL_TEST_PORT 3306 putenv MYSQL_TEST_USER root putenv MYSQL_TEST_PASSWD putenv MYSQL_TEST_DB test putenv MYSQL_TEST_ENGINE MyISAM putenv MYSQL_TEST_SOCKET putenv MYSQL_TEST_SKIP_CONNECT_FAILURE 1 putenv MYSQL_TEST_CONNECT_FLAGS 0 putenv MYSQL_TEST_EXPERIMENTAL 0 replication cluster em...

Страница 2653: ... root db test port 3306 flags 131072 mysqlnd_ms connect mysqlnd_ms_config_json_section_exists info section myapp len 5 mysqlnd_ms_config_json_sub_section_exists info section myapp len 5 info ret 1 mysqlnd_ms_config_json_sub_section_exists info ret 1 mysqlnd_ms_config_json_section_exists The debug log is not only useful for plugin developers but also to find the cause of user errors For example if ...

Страница 2654: ...considerations The statement has been load balanced using round robin policy as you can easily guess from the functions name mysqlnd_ms_choose_connection_rr It has been sent to a master server running on host localhost user root db test port 3306 flags 131072 persistent 0 state 0 20 7 6 6 8 Monitoring Copyright 1997 2012 the PHP Documentation Group 2230 Plugin activity can be monitored using the m...

Страница 2655: ...r die sprintf d s n mysqli_connect_errno mysqli_connect_error stats_before mysqlnd_ms_get_stats if res mysqli query SELECT Read request FROM DUAL var_dump res fetch_all stats_after mysqlnd_ms_get_stats if stats_after use_slave stats_before use_slave echo According to the statistics the read request has not been run on a slave Statistics are aggregated for all plugin activities and all connections ...

Страница 2656: ... comments The plugin supports three SQL hints to direct queries to either the MySQL slave servers the MySQL master server or the last used MySQL server SQL hints must be placed at the beginning of a query to be recognized by the plugin For better portability it is recommended to use the string constants MYSQLND_MS_MASTER_SWITCH MYSQLND_MS_SLAVE_SWITCH and MYSQLND_MS_LAST_USED_SWITCH instead of the...

Страница 2657: ...lnd_ms_set_qos Session consistency is defined as read your writes The client is guaranteed to see his latest changes MYSQLND_MS_QOS_CONSISTENCY_STRONG integer Use to request the service level strong consistency from the mysqlnd_ms_set_qos Strong consistency is used to ensure all clients see each others changes MYSQLND_MS_QOS_OPTION_GTID integer Used as a service level option with mysqlnd_ms_set_qo...

Страница 2658: ... SQL statement from the fetch_last_gtid entry of the global_transaction_id_injection section from the plugins configuration file The function may be called after the GTID has been incremented Notes Note mysqlnd_ms_get_last_gtid requires PHP 5 4 0 and PECL mysqlnd_ms 1 2 0 Internally it is using a mysqlnd library C functionality not available with PHP 5 3 Examples Example 20 297 mysqlnd_ms_get_last...

Страница 2659: ... host socket If you want to distinguish connections from each other use a combination of scheme and thread_id as a unique key Neither scheme nor thread_id alone are sufficient to distinguish two connections from each other Two servers may assign the same thread_id to two different connections Thus connections in the pool may have the same thread_id Also do not rely on uniqueness of scheme in a poo...

Страница 2660: ...ql sock host_info string 25 Localhost via UNIX socket host string 0 port int 3306 socket_or_pipe string 15 tmp mysql sock thread_id int 46253 last_message string 0 errno int 0 error string 0 sqlstate string 5 00000 20 7 6 8 3 mysqlnd_ms_get_stats Copyright 1997 2012 the PHP Documentation Group 2230 mysqlnd_ms_get_stats Returns query distribution and connection statistics Description array mysqlnd_...

Страница 2661: ...other filter it is no longer guaranteed that the statement which increments use_slave will be executed on the slaves The meaning for version 1 1 0 is as follows Number of statements sent to the slaves Statements directed to a slave by the user filter an user defined callback are not included The latter are counted by use_slave_callback Since 1 0 0 use_master The semantics of this statistic has cha...

Страница 2662: ...er for statement execution Since 1 0 0 use_master_callback Number of statements sent to a master because an user defined callback has chosen a master server for statement execution Since 1 0 0 non_lazy_connections_slave_success Number of successfully opened slave connections from configurations not using lazy connections The total number of successfully opened slave connections is non_lazy_connect...

Страница 2663: ...failed SQL injections in commit mode as part of the plugins client side global transaction id emulation Since 1 2 0 gtid_implicit_commit_injections_success Number of successful SQL injections when implicit commit is detected as part of the plugins client side global transaction id emulation Implicit commit happens for example when autocommit has been turned off a query is executed and autocommit i...

Страница 2664: ...ve_failure string 1 0 lazy_connections_master_success string 1 0 lazy_connections_master_failure string 1 0 trx_autocommit_on string 1 0 trx_autocommit_off string 1 0 trx_master_forced string 1 0 gtid_autocommit_injections_success string 1 0 gtid_autocommit_injections_failure string 1 0 gtid_commit_injections_success string 1 0 gtid_commit_injections_failure string 1 0 gtid_implicit_commit_injecti...

Страница 2665: ...le and replicate wild do db Please consult the MySQL Reference Manual to learn more about this MySQL Server feature The supported placeholders are zero or more literals one literal Placeholders can be escaped using Return Values Returns TRUE table_name is matched by wildcard Otherwise returns FALSE Examples Example 20 300 mysqlnd_ms_match_wild example php var_dump mysqlnd_ms_match_wild schema_name...

Страница 2666: ...ction returns a value of MYSQLND_MS_QUERY_USE_SLAVE if the query can be run on a slave because it is considered read only A value of MYSQLND_MS_QUERY_USE_LAST_USED is returned to recommend running the query on the last used server This can either be a MySQL replication master server or a MySQL replication slave server If read write splitting has been disabled by setting mysqlnd_ms disable_rw_split...

Страница 2667: ... Quality of Service filter implements the necessary logic The filter can either be configured in the plugins configuration file or at runtime using mysqlnd_ms_set_qos Similar results can be achieved with PECL mysqlnd_ms 1 2 0 if using SQL hints to force the use of a certain type of node or using the master_on_write plugin configuration option The first requires more code and causes more work on th...

Страница 2668: ...AL service level to filter out asynchronous slaves that lag more seconds behind the master than option_value If set the plugin will only consider slaves for reading if SHOW SLAVE STATUS reports Slave_IO_Running Yes Slave_SQL_Running Yes and Seconds_Behind_Master option_value Please note searching appropriate slaves is an expensive and slow operation Use the feature sparsely in version 1 2 0 Future...

Страница 2669: ... MYSQLND_MS_LAST_USED_SWITCH Using SQL hints one can control for example whether a query shall be send to the MySQL replication master server or one of the slave servers By help of SQL hints it is not possible to pick a certain slave server for query execution Full control on server selection can be gained using a callback function Use of a callback is recommended to expert users only because the ...

Страница 2670: ... 1 1 0 It has been replaced by the user filter Please check the Change History for upgrade notes Examples Example 20 303 mysqlnd_ms_set_user_pick_server example myapp master localhost slave 192 168 2 27 3306 slave 192 168 78 136 3306 pick user php function pick_server connected query master slaves last_used static slave_idx 0 static num_slaves NULL if is_null num_slaves num_slaves count slaves def...

Страница 2671: ...e The above example will output User has connected to myapp deciding where to run SELECT 1 FROM DUAL some read only query for a slave ret tcp 192 168 2 27 3306 User has connected to myapp deciding where to run SELECT 2 FROM DUAL some read only query for a slave ret tcp 192 168 78 136 3306 User has connected to myapp deciding where to run SELECT FROM table_on_slave_a_only access to table available ...

Страница 2672: ...ork in other cases they did not The new behaviour is more consistent SQL hints will always be ignore for the duration of a transaction if transaction stickiness is enabled Please note transaction boundary detection continues to be based on API call monitoring SQL commands controlling transactions are not monitored BC break and bug fix Calls to mysqlnd_ms_set_qos will fail when done in the middle o...

Страница 2673: ...ly transaction aware way Please note PDO_MySQL has not been updated yet to utilize the new mysqlnd API calls Thus transaction boundary detection with PDO_MySQL continues to be limited to the monitoring by passing in PDO ATTR_AUTOCOMMIT to PDO setAttribute Introduced trx_stickiness on This trx_stickiness option differs from trx_stickiness master as it tries to execute a read only transaction on a s...

Страница 2674: ...lave connection fails The number of attempts can be limited using the max_retries option Failed hosts can be remembered and skipped in load balancing for the rest of the web request max_retries and remember_failed are considered experimental although decent stability is given Syntax and semantics may change in the future without prior notice 20 7 6 9 3 PECL mysqlnd_ms 1 3 series Copyright 1997 201...

Страница 2675: ...ersion 1 2 the focus continues to be on supporting MySQL database clusters with asynchronous replication The plugin tries to make using the cluster introducing a quality of service filter which applications can use to define what service quality they need from the cluster Service levels provided are eventual consistency with optional maximum age slave slag session consistency and strong consistenc...

Страница 2676: ... and quality assurance has been improved Feature changes Added the chainable filter concept BC break mysqlnd_ms_set_user_pick_server has been removed Thehttp svn php net viewvc pecl mysqlnd_ms trunk user filter has been introduced to replace it The filter offers similar functionality but see below for an explanation of the differences New powerful JSON based configuration syntax Lazy connections i...

Страница 2677: ...ease date 04 2011 Motto theme bug fix release 1 0 0 alpha Release date 04 2011 Motto theme Cover replication basics to test user feedback The first release of practical use It features basic automatic read write splitting SQL hints to overrule automatic redirection load balancing of slave requests lazy connections and optional automatic use of the master after the first write The public feature se...

Страница 2678: ...ts issued with mysqli or PDO_MySQL which are the only two PHP MySQL APIs to offer prepared statement support 20 7 7 3 On the name Copyright 1997 2012 the PHP Documentation Group 2230 The shortcut mysqlnd_qc stands for mysqlnd query cache plugin The name was chosen for a quick and dirty proof of concept In the beginning the developers did not expect to continue using the code base Sometimes PECL my...

Страница 2679: ...API calls of any of the existing PHP MySQL extensions Flexible storage various storage handler Various storage handler are supported to offer different scopes for cache entries Different scopes allow for different degrees in sharing cache entries among clients default built in process memory scope process one or more web requests depending on PHP deployment model used APC shared memory scope singl...

Страница 2680: ...qc is a plugin for the mysqlnd library To use the plugin with any of the existing PHP MySQL extensions APIs the extension has to use the mysqlnd library Then load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_qc enable_qc Example 20 304 Enabling the plugin php ini mysqlnd_qc enable_qc 1 20 7 7 4 3 Caching queries Co...

Страница 2681: ... id 1 var_dump res fetch_assoc res free printf Total time uncached query 6fs n microtime true start Cache hit start microtime true res mysqli query MYSQLND_QC_ENABLE_SWITCH SELECT id FROM test WHERE id 1 var_dump res fetch_assoc res free printf Total time cached query 6fs n microtime true start The above examples will output something similar to array 1 id string 1 1 Total time uncached query 0 00...

Страница 2682: ...hint is present because of mysqlnd_qc cache_by_default 1 res mysqli query SELECT id FROM test WHERE id 1 var_dump res fetch_assoc res free mysqli query DELETE FROM test WHERE id 1 Cache hit no automatic invalidation and still valid res mysqli query SELECT id FROM test WHERE id 1 var_dump res fetch_assoc res free Cache miss query must not be cached because of the SQL hint res mysqli query MYSQLND_Q...

Страница 2683: ...ing similar to array 2 id string 1 1 _time string 19 2012 01 11 15 43 10 Total time 0 000540s array 2 id string 1 1 _time string 19 2012 01 11 15 43 11 Total time 0 000555s array 2 id string 1 1 _time string 19 2012 01 11 15 43 12 Total time 0 000549s It is possible to enable caching for all statements including those which has columns in their result set for which MySQL reports no table such as t...

Страница 2684: ...string 1 1 _time string 19 2012 01 11 15 47 45 Total time 0 000546s array 2 id string 1 1 _time string 19 2012 01 11 15 47 45 Total time 0 000187s array 2 id string 1 1 _time string 19 2012 01 11 15 47 45 Total time 0 000167s Note Although mysqlnd_qc cache_no_table 1 has been created for use with mysqlnd_qc cache_by_default 1 it is bound it The plugin will evaluate the mysqlnd_qc cache_no_table wh...

Страница 2685: ... test mysqli query INSERT INTO test id VALUES NOW Of course a real life script should do better error handling die sprintf d s n mysqli errno mysqli error select latest row but cache results query MYSQLND_QC_ENABLE_SWITCH query SELECT id AS _time FROM test if res mysqli query query row res fetch_assoc printf d s n mysqli errno mysqli error res free printf Wall time s DB row time s n date H i s row...

Страница 2686: ...1 MYSQLND_QC_ENABLE_SWITCH MYSQLND_QC_TTL_SWITCH res mysqli query sql var_dump res fetch_assoc res free mysqli query DELETE FROM test WHERE id 1 sleep 1 Cache hit no automatic invalidation and still valid res mysqli query sql var_dump res fetch_assoc res free sleep 2 Cache miss cache entry has expired res mysqli query sql var_dump res fetch_assoc res free printf Script runtime t d seconds n microt...

Страница 2687: ...ad of the global default Example 20 311 Setting a callback with mysqlnd_qc_set_is_select mysqlnd_qc enable_qc 1 mysqlnd_qc collect_statistics 1 php callback which decides if query is cached function is_select query static patterns array true use default from mysqlnd_qc ttl SELECT s s FROM s test ismU true 3 use TTL 3 seconds SELECT s s FROM s news ismU 3 check if query does match pattern foreach p...

Страница 2688: ...uests can no longer be served from the cache but try to run the underlying query on the database server Until the cache entry is refreshed more and more clients contact the database server In the worst case a total lost of service is the result The overload can be avoided using a storage handler which limits the reuse of cache entries to few clients Then at the average its likely that only a limit...

Страница 2689: ...he functions trace contains one entry for every query issued before the function is called Example 20 313 Collecting a query trace mysqlnd_qc enable_qc 1 mysqlnd_qc collect_query_trace 1 php connect to MySQL mysqli new mysqli host user password schema port socket dummy queries to fill the query trace for i 0 i 2 i res mysqli query SELECT 1 AS _one FROM DUAL res free dump trace var_dump mysqlnd_qc_...

Страница 2690: ..._qc enable_qc 1 mysqlnd_qc collect_query_trace 1 php connect to MySQL mysqli new mysqli host user password schema port socket mysqli query DROP TABLE IF EXISTS test mysqli query CREATE TABLE test id INT mysqli query INSERT INTO test id VALUES 1 2 3 dummy queries to fill the query trace for i 0 i 3 i res mysqli query SELECT id FROM test WHERE id mysqli real_escape_string i res free trace mysqlnd_qc...

Страница 2691: ...lection has been enabled through their corresponding PHP configuration directives Data collection is disabled by default for performance considerations It is configurable with the mysqlnd_qc time_statistics option which determines if timing information should be collected Collection of time statistics is enabled by default but only performed if data collection as such has been enabled Recording ti...

Страница 2692: ... 3 136 receive_bytes_replayed string 3 136 send_bytes_recorded string 2 84 send_bytes_replayed string 2 84 slam_stale_refresh string 1 0 slam_stale_hit string 1 0 request_counter int 1 process_hash int 1929695233 For a quick overview call mysqlnd_qc_get_core_stats It delivers cache usage cache timing and traffic related statistics Values are aggregated on a per process basis for all queries issued...

Страница 2693: ...mp mysqlnd_qc_get_cache_info The above examples will output something similar to array 4 num_entries int 2 handler string 7 default handler_version string 5 1 0 0 data array 2 Localhost via UNIX socket 3306 root test qc on SELECT id FROM test WHERE id 1 array 2 statistics array 11 rows int 1 stored_size int 71 cache_hits int 1 run_time int 391 store_time int 27 min_run_time int 16 max_run_time int...

Страница 2694: ...min_store_time int 6 max_store_time int 6 avg_run_time int 5 avg_store_time int 3 metadata array 1 0 array 8 name string 2 id orig_name string 2 id table string 4 test orig_table string 4 test db string 4 test max_length int 0 length int 11 type int 3 It is possible to further break down the granularity of statistics to the level of the normalized statement string The normalized statement string i...

Страница 2695: ...mysqli query INSERT INTO test id VALUES 1 2 3 dummy queries to fill the query trace for i 1 i 4 i query sprintf s SELECT id FROM test WHERE id d MYSQLND_QC_ENABLE_SWITCH i 2 res mysqli query query res free var_dump mysqlnd_qc_get_normalized_query_trace_log The above examples will output something similar to array 4 0 array 9 query string 25 DROP TABLE IF EXISTS test occurences int 0 eligible_for_c...

Страница 2696: ...an be found which give an example how to write a cache monitor Please follow the instructions given in the source Since PECL mysqlnd_qc 1 1 0 it is possible to write statistics into a log file Please see mysqlnd_qc collect_statistics_log_file 20 7 7 4 9 Beyond TTL user defined storage Copyright 1997 2012 the PHP Documentation Group 2230 The query cache plugin supports the use of user defined stora...

Страница 2697: ...p __cache key if tmp valid_until time unset __cache key ret NULL else ret __cache key data else ret NULL return ret function return_to_cache key Called on cache hit after cached data has been processed may be used for reference counting printf t s d n __FUNCTION__ func_num_args function add_query_to_cache_if_not_exists key data ttl run_time store_time row_count global __cache printf t s d n __FUNC...

Страница 2698: ...imes count details cached_run_time 0 return stats function clear_cache global __cache printf t s d n __FUNCTION__ func_num_args __cache array return TRUE Install procedural user defined storage handler if mysqlnd_qc_set_user_handlers get_hash find_query_in_cache return_to_cache add_query_to_cache_if_not_exists query_is_select update_query_run_time_stats get_stats clear_cache printf Failed to insta...

Страница 2699: ...y_is_select INSERT INTO test id VALUES 1 2 FALSE Cache put cache miss query_is_select SELECT id FROM test WHERE id 1 5 get_hash 5 find_query_in_cache 1 add_query_to_cache_if_not_exists 6 array 1 id string 1 1 query_is_select DELETE FROM test WHERE id 1 FALSE Cache hit query_is_select SELECT id FROM test WHERE id 1 5 get_hash 5 find_query_in_cache 1 return_to_cache 1 update_query_run_time_stats 3 a...

Страница 2700: ...PC and PECL mysqlnd_qc support into PHP For using MEMCACHE storage handler Use libmemcache 0 38 or newer PECL mysqlnd_qc 1 2 has been tested with libmemcache 1 4 0 For using sqlite storage handler Use the sqlite3 extension that bundled with PHP 20 7 7 5 2 Installation Copyright 1997 2012 the PHP Documentation Group 2230 This PECL extension is not bundled with PHP Information for installing this PE...

Страница 2701: ...It is evaluated by the core of the plugin mysqlnd_qc cache_no_table integer Whether to cache queries with no table name in any of columns meta data of their result set for example SELECT SLEEP 1 SELECT NOW SELECT SUBSTRING mysqlnd_qc use_request_time integer Use PHP global request time to avoid gettimeofday system calls If using APC storage handler it should be set to the value of apc use_request_...

Страница 2702: ...er memcache server host mysqlnd_qc memc_port integer MEMCACHE storage handler memcached server port mysqlnd_qc sqlite_data_file string sqlite storage handler data file Any setting but memory may be of little practical value 20 7 7 6 Predefined Constants Copyright 1997 2012 the PHP Documentation Group 2230 The constants below are defined by this extension and will only be available when the extensi...

Страница 2703: ...tions to the slave the cache key shall not be formed from the user hostname or other settings that may vary for the various slave connections Instead PECL mysqlnd_ms provides an identifier which refers to the group of slave connections that shall be enabled to share cache entries no matter which physical slave connection was to generate the cache entry Use of this feature outside of PECL mysqlnd_m...

Страница 2704: ...lnd_qc Functions Copyright 1997 2012 the PHP Documentation Group 2230 20 7 7 7 1 mysqlnd_qc_clear_cache Copyright 1997 2012 the PHP Documentation Group 2230 mysqlnd_qc_clear_cache Flush all cache contents Description bool mysqlnd_qc_clear_cache Flush all cache contents Flushing the cache is a storage handler responsibility All built in storage handler but the memcache storage handler support flush...

Страница 2705: ...n has no parameters Return Values Returns an array of available built in storage handler For each storage handler the version number and version string is given Examples Example 20 321 mysqlnd_qc_get_available_handlers example php var_dump mysqlnd_qc_get_available_handlers The above examples will output array 5 default array 2 version string 5 1 0 0 version_number int 100000 user array 2 version s...

Страница 2706: ...he information is the PHP process Depending on the PHP deployment model a process may serve one or more web requests Values are aggregated for all cache activities on a per storage handler basis It is not possible to tell how much queries originating from mysqli PDO_MySQL or mysql API calls have contributed to the aggregated data values Use mysqlnd_qc_get_core_stats to get timing data aggregated f...

Страница 2707: ...se see also the example below The following data is given for every cache entry statistics array Statistics of the cache entry Since 1 0 0 Property Description Version rows Number of rows of the cached result set Since 1 0 0 stored_size The size of the cached result set in bytes This is the size of the payload The value is not suited for calculating the total memory consumption of all cache entrie...

Страница 2708: ... the cached statement Since 1 0 0 avg_store_time Average store time of the cached statement Since 1 0 0 max_run_time Average run time of the cached statement Since 1 0 0 max_store_time Average store time of the cached statement Since 1 0 0 valid_until Timestamp when the cache entry expires Since 1 1 0 metadata array Metadata of the cache entry This is the metadata provided by MySQL together with t...

Страница 2709: ...the field Details may vary by MySQL server version Since 1 0 0 type The data type of the field Details may vary by the MySQL server in use This is the MySQL C API type constants value It is recommended to use type constants provided by the mysqli extension to test for its meaning You should not test for certain type values by comparing with certain numbers Since 1 0 0 The APC storage handler retur...

Страница 2710: ...ysqlnd_qc_get_cache_info The above examples will output array 4 num_entries int 1 handler string 7 default handler_version string 5 1 0 0 data array 1 Localhost via UNIX socket 3306 user schema qc on SELECT id FROM test array 2 statistics array 11 rows int 6 stored_size int 101 cache_hits int 0 run_time int 471 store_time int 27 min_run_time int 0 max_run_time int 0 min_store_time int 0 max_store_...

Страница 2711: ... will also disable the collection of time related statistics The PHP configuration setting mysqlnd_qc collect_time_statistics controls the collection of time related statistics The scope of the core statistics is the PHP process Depending on your deployment model a PHP process may handle one or multiple requests Statistics are aggregated for all cache entries and all storage handler It is not poss...

Страница 2712: ...ocess has filled the cache You may want to use num_entries from mysqlnd_qc_get_cache_info if the handler supports it default APC Since 1 0 0 query_should_cache Statement is considered cacheable based on query string analysis The statement may or may not be added to the cache See also cache_put Since 1 0 0 query_should_not_cache Statement is considered not cacheable based on query string analysis S...

Страница 2713: ... of such a query is SELECT SLEEP 1 To cache those statements you have to change default value of the PHP configuration directive mysqlnd_qc cache_no_table and set mysqlnd_qc cache_no_table 1 Often it is not desired to cache such statements Since 1 0 0 query_uncached_use_result Statement would have been cached if a buffered result set had been used The situation is also considered as a cache miss a...

Страница 2714: ... send_bytes_recorded Recorded outgoing network traffic bytes send from MySQL to PHP The traffic may or may not have been added to the cache The traffic is the total for all queries regardless if cached or not Since 1 0 0 send_bytes_replayed Network traffic replayed during cache This is the total amount of outgoing traffic saved because of the usage of the query cache plugin Since 1 0 0 slam_stale_...

Страница 2715: ...found_in_cache string 1 1 query_uncached_other string 1 0 query_uncached_no_table string 1 0 query_uncached_no_result string 1 0 query_uncached_use_result string 1 0 query_aggr_run_time_cache_hit string 1 4 query_aggr_run_time_cache_put string 3 395 query_aggr_run_time_total string 3 399 query_aggr_store_time_cache_hit string 1 2 query_aggr_store_time_cache_put string 1 8 query_aggr_store_time_tot...

Страница 2716: ...malized query stringand further detail information Key Description query Normalized statement string occurences How many statements have matched the normalized statement string in addition to the one which has created the log entry The value is zero if a statement has been normalized its normalized representation has been added to the log but no further queries inspected by PECL mysqlnd_qc have th...

Страница 2717: ...1 var_dump res fetch_assoc res free cache put res mysqli query MYSQLND_QC_ENABLE_SWITCH SELECT id FROM test WHERE id 2 var_dump res fetch_assoc res free cache hit res mysqli query MYSQLND_QC_ENABLE_SWITCH SELECT id FROM test WHERE id 2 var_dump res fetch_assoc res free var_dump mysqlnd_qc_get_normalized_query_trace_log The above examples will output array 1 id string 1 1 array 1 id string 1 2 arra...

Страница 2718: ...INSERT INTO test id VALUES occurences int 0 eligible_for_caching bool false avg_run_time int 0 min_run_time int 0 max_run_time int 0 avg_store_time int 0 min_store_time int 0 max_store_time int 0 3 array 9 query string 31 SELECT id FROM test WHERE id occurences int 2 eligible_for_caching bool true avg_run_time int 159 min_run_time int 12 max_run_time int 307 avg_store_time int 10 min_store_time in...

Страница 2719: ...seconds The collection of all times and the necessary gettimeofday system calls can be disabled by setting the PHP configuration directive mysqlnd_qc time_statistics to 0 store_time Query result set store time in milliseconds The collection of all times and the necessary gettimeofday system calls can be disabled by setting the PHP configuration directive mysqlnd_qc time_statistics to 0 eligible_fo...

Страница 2720: ...s mysqli query MYSQLND_QC_ENABLE_SWITCH SELECT id FROM test WHERE id 2 var_dump res fetch_assoc res free var_dump mysqlnd_qc_get_query_trace_log The above examples will output array 1 id string 1 1 array 1 id string 1 2 array 1 id string 1 2 array 6 0 array 8 query string 25 DROP TABLE IF EXISTS test origin string 102 0 qc php 4 mysqli query DROP TABLE IF E 1 main run_time int 0 store_time int 0 e...

Страница 2721: ... false was_already_in_cache bool false 3 array 8 query string 32 SELECT id FROM test WHERE id 1 origin string 102 0 qc php 9 mysqli query SELECT id FROM 1 main run_time int 0 store_time int 25 eligible_for_caching bool false no_table bool false was_added bool false was_already_in_cache bool false 4 array 8 query string 41 qc on SELECT id FROM test WHERE id 2 origin string 103 0 qc php 14 mysqli qu...

Страница 2722: ...ion_option Sets a condition for automatic caching of statements which do not contain the necessary SQL hints to enable caching of them Parameters condition_type Type of the condition The only allowed value is MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN condition Parameter for the condition set with condition_type Parameter type and structure depend on condition_type If condition_type equals MYSQLND_Q...

Страница 2723: ...s TRUE on success or FALSE on FAILURE See Also Quickstart pattern based caching 20 7 7 7 8 mysqlnd_qc_set_is_select Copyright 1997 2012 the PHP Documentation Group 2230 mysqlnd_qc_set_is_select Installs a callback which decides whether a statement is cached Description mixed mysqlnd_qc_set_is_select string callback Installs a callback which decides whether a statement is cached There are several w...

Страница 2724: ... s test ismU true 3 use TTL 3 seconds SELECT s s FROM s news ismU 3 check if query does match pattern foreach patterns as pattern ttl if preg_match pattern query printf is_select 45s cache n query return ttl printf is_select 45s do not cache n query return false mysqlnd_qc_set_is_select is_select Connect create and populate test table mysqli new mysqli host user password schema mysqli query DROP T...

Страница 2725: ...g the name of a built in storage handler or an object of type mysqlnd_qc_handler_default The names of the built in storage handler are default APC MEMCACHE sqlite Return Values Returns TRUE on success or FALSE on failure If changing the storage handler fails a catchable fatal error will be thrown The query cache cannot operate if the previous storage handler has been shutdown but no new storage ha...

Страница 2726: ...Name of the user function implementing the storage handler find_in_cache functionality return_to_cache Name of the user function implementing the storage handler return_to_cache functionality add_query_to_cache_if_not_exists Name of the user function implementing the storage handler add_query_to_cache_if_not_exists functionality query_is_select Name of the user function implementing the storage ha...

Страница 2727: ...pyright 1997 2012 the PHP Documentation Group 2230 1 1 0 stable Release date 04 2012 Motto theme PHP 5 4 compatibility schema pattern based caching and mysqlnd_ms support 1 1 0 beta Release date 04 2012 Motto theme PHP 5 4 compatibility schema pattern based caching and mysqlnd_ms support 1 1 0 alpha Release date 04 2012 Motto theme PHP 5 4 compatibility schema pattern based caching and mysqlnd_ms ...

Страница 2728: ...eta or later to transparently replace MySQL Replication slave reads with cache accesses if the user explicitly allows Bug fixes Fixed Bug 59959 config m4 wrong library 64bit memcached handler builds Credits Remi Collet 20 7 7 8 3 PECL mysqlnd_qc 1 0 series Copyright 1997 2012 the PHP Documentation Group 2230 1 0 1 stable Release date 12 2010 Motto theme Prepared statement support Added support for...

Страница 2729: ..._uh gives users access to MySQL user names MySQL password used by any of the PHP MySQL extensions to connect to MySQL It allows monitoring of all queries and prepared statements exposing the statement string to the user Therefore the extension should be installed with care The PHP_INI_SYSTEM configuration setting mysqlnd_uh enable can be used to prevent users from hooking mysqlnd calls Code obfusc...

Страница 2730: ...strongly recommended to always call the parent method implementation when subclassing MysqlndUhConnection or MysqlndUhPreparedStatement To prevent the worst case the extension performs some sanity checks Please see also the Mysqlnd_uh Configure Options 20 7 8 4 1 Setup Copyright 1997 2012 the PHP Documentation Group 2230 The plugin is implemented as a PHP extension See the installation instruction...

Страница 2731: ...the functionality of the proxy followed by registering a new proxy object Proxy objects are installed by mysqlnd_uh_set_connection_proxy and mysqlnd_uh_set_statement_proxy Example 20 331 Installing a proxy php class proxy extends MysqlndUhConnection public function connect res host user passwd db port socket mysql_flags printf s s n __METHOD__ var_export func_get_args true ret parent connect res h...

Страница 2732: ...has been disabled by setting PHP Warning mysqlnd_uh_set_connection_proxy Mysqlnd User Handler The plugin has been disabled by setting t To monitor mysqlnd you have to write your own proxy object subclassing MysqlndUhConnection Please see the function reference for a the list of methods that can be subclassed Alternatively you can use reflection to inspect the built in MysqlndUhConnection Create a ...

Страница 2733: ...nt_proxy new stmt_proxy mysqli new mysqli localhost root test stmt mysqli prepare SELECT mysqlnd hacking made easy AS _msg FROM DUAL The above example will output stmt_proxy prepare SELECT mysqlnd hacking made easy AS _msg FROM DUAL 20 7 8 4 4 Basic query monitoring Copyright 1997 2012 the PHP Documentation Group 2230 Basic monitoring of a query statement is easy with PECL mysqlnd_uh Combined with...

Страница 2734: ...all this method In the example the query function is invoked by a PDO call By default PDO_MySQL is using prepared statement emulation All native prepared statements are prepared with the prepare method of mysqlnd exported through MysqlndUhPreparedStatement prepare Subclass MysqlndUhPreparedStatement and overwrite prepare for native prepared statement monitoring 20 7 8 5 Installing Configuring Copy...

Страница 2735: ...turn value types of user hooks as E_WARNING level errors This is recommended for detecting errors 20 7 8 5 4 Resource Types Copyright 1997 2012 the PHP Documentation Group 2230 This extension has no resource types defined 20 7 8 6 Predefined Constants Copyright 1997 2012 the PHP Documentation Group 2230 The constants below are defined by this extension and will only be available when the extension...

Страница 2736: ...ient Server protocol command COM_PING MYSQLND_UH_MYSQLND_COM_TIME integer MySQL Client Server protocol command COM_TIME MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT integer MySQL Client Server protocol command COM_DELAYED_INSERT MYSQLND_UH_MYSQLND_COM_CHANGE_USER integer MySQL Client Server protocol command COM_CHANGE_USER MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP integer MySQL Client Server protocol command CO...

Страница 2737: ...rotocol packet EOF MYSQLND_UH_MYSQLND_PROT_CMD_PACKET integer MySQL Client Server protocol packet command MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET integer MySQL Client Server protocol packet result set header MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET integer MySQL Client Server protocol packet resultset field MYSQLND_UH_MYSQLND_PROT_ROW_PACKET integer MySQL Client Server protocol packet row MYSQLN...

Страница 2738: ...ed protocol is to be used MYSQLND_UH_MYSQLND_OPTION_OPT_NAMED_PIPE integer Option named pipe to use for connection Windows MYSQLND_UH_MYSQLND_OPTION_INIT_COMMAND integer Option init command to execute upon connect MYSQLND_UH_MYSQLND_READ_DEFAULT_FILE integer Option MySQL server default file to read upon connect MYSQLND_UH_MYSQLND_READ_DEFAULT_GROUP integer Option MySQL server default file group to...

Страница 2739: ...s MYSQLND_UH_MYSQLND_OPT_NET_READ_BUFFER_SIZE integer Option mysqlnd network buffer size for reading from the server MYSQLND_UH_MYSQLND_OPT_SSL_KEY integer Option SSL key MYSQLND_UH_MYSQLND_OPT_SSL_CERT integer Option SSL certificate MYSQLND_UH_MYSQLND_OPT_SSL_CA integer Option SSL CA MYSQLND_UH_MYSQLND_OPT_SSL_CAPATH integer Option Path to SSL CA MYSQLND_UH_MYSQLND_OPT_SSL_CIPHER integer Option S...

Страница 2740: ...xample 1 0 0 alpha MYSQLND_UH_VERSION_ID integer Plugin version number for example 10000 20 7 8 7 The MysqlndUhConnection class MysqlndUhConnection Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection MysqlndUhConnection Methods public bool MysqlndUhConnection changeUser mysqlnd_connection connection string user string password string database bool silent int passwd_len public ...

Страница 2741: ...tServerStatistics mysqlnd_connection connection public int MysqlndUhConnection getServerVersion mysqlnd_connection connection public string MysqlndUhConnection getSqlstate mysqlnd_connection connection public array MysqlndUhConnection getStatistics mysqlnd_connection connection public int MysqlndUhConnection getThreadId mysqlnd_connection connection public int MysqlndUhConnection getWarningCount m...

Страница 2742: ...MysqlndUhConnection serverDumpDebugInformation mysqlnd_connection connection public bool MysqlndUhConnection setAutocommit mysqlnd_connection connection int mode public bool MysqlndUhConnection setCharset mysqlnd_connection connection string charset public bool MysqlndUhConnection setClientOption mysqlnd_connection connection int option int value public void MysqlndUhConnection setServerOption mys...

Страница 2743: ...blic bool MysqlndUhConnection changeUser mysqlnd_connection connection string user string password string database bool silent int passwd_len Changes the user of the specified mysqlnd database connection Parameters connection Mysqlnd connection handle Do not modify user The MySQL user name password The MySQL password database The MySQL database to change to silent Controls if mysqlnd is allowed to...

Страница 2744: ...est 4 false 5 3 proxy changeUser returns false bool false See Also mysqlnd_uh_set_connection_proxy mysqli_change_user 20 7 8 7 2 MysqlndUhConnection charsetName Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection charsetName Returns the default character set for the database connection Description public string MysqlndUhConnection charsetName mysqlnd_connection connection Retu...

Страница 2745: ...se connection Description public bool MysqlndUhConnection close mysqlnd_connection connection int close_type Closes a previously opened database connection Note Failing to call the parent implementation may cause memory leaks or crash PHP This is not considered a bug Please keep in mind that the mysqlnd library functions have never been designed to be exposed to the user space Parameters connectio...

Страница 2746: ...func_get_args true printf close_type s n close_type_to_string close_type WARNING you must call the parent ret parent close res close_type printf s returns s n __METHOD__ var_export ret true return ret mysqlnd_uh_set_connection_proxy new proxy mysqli new mysqli localhost root test mysqli close The above example will output proxy close array 0 NULL 1 0 close_type MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT pr...

Страница 2747: ...cify the default database to be used when performing queries port Specifies the port number to attempt to connect to the MySQL server socket Specifies the socket or named pipe that should be used If NULL mysqlnd will default to tmp mysql sock mysql_flags Connection options Return Values Returns TRUE on success Otherwise returns FALSE Examples Example 20 340 MysqlndUhConnection connect example php ...

Страница 2748: ... documented only its argument list is available Parameters This function has no parameters Return Values 20 7 8 7 6 MysqlndUhConnection endPSession Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection endPSession End a persistent connection Description public bool MysqlndUhConnection endPSession mysqlnd_connection connection End a persistent connection Warning This function is ...

Страница 2749: ...set_connection_proxy 20 7 8 7 7 MysqlndUhConnection escapeString Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection escapeString Escapes special characters in a string for use in an SQL statement taking into account the current charset of the connection Description public string MysqlndUhConnection escapeString mysqlnd_connection connection string escape_string Escapes specia...

Страница 2750: ..._real_escape_string mysql_real_escape_string 20 7 8 7 8 MysqlndUhConnection getAffectedRows Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection getAffectedRows Gets the number of affected rows in a previous MySQL operation Description public int MysqlndUhConnection getAffectedRows mysqlnd_connection connection Gets the number of affected rows in a previous MySQL operation Para...

Страница 2751: ...on Group 2230 MysqlndUhConnection getErrorNumber Returns the error code for the most recent function call Description public int MysqlndUhConnection getErrorNumber mysqlnd_connection connection Returns the error code for the most recent function call Parameters connection Mysqlnd connection handle Do not modify Return Values Error code for the most recent function call Examples MysqlndUhConnection...

Страница 2752: ...rrno proxy getErrorNumber array 0 NULL proxy getErrorNumber returns 1064 int 1064 close See Also mysqlnd_uh_set_connection_proxy MysqlndUhConnection getErrorString mysqli_errno mysql_errno 20 7 8 7 10 MysqlndUhConnection getErrorString Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection getErrorString Returns a string description of the last error Description public string Mys...

Страница 2753: ...ar_dump mysqli error printf close n mysqli close The above example will output connect proxy getErrorString array 0 NULL proxy getErrorString returns query errno proxy getErrorString array 0 NULL proxy getErrorString returns You have an error in your SQL syntax check the manual that corresponds to you string 168 You have an error in your SQL syntax check the manual that corresponds to your MySQL s...

Страница 2754: ... __METHOD__ var_export ret true return ret mysqlnd_uh_set_connection_proxy new proxy mysqli new mysqli localhost root test mysqli query WILL_I_EVER_LEARN_SQL var_dump mysqli field_count mysqli query SELECT 1 2 3 FROM DUAL var_dump mysqli field_count The above example will output proxy getFieldCount array 0 NULL proxy getFieldCount returns 0 int 0 proxy getFieldCount array 0 NULL proxy getFieldCoun...

Страница 2755: ...ntf s returns s n __METHOD__ var_export ret true return ret mysqlnd_uh_set_connection_proxy new proxy mysqli new mysqli localhost root test var_dump mysqli host_info The above example will output proxy getHostInformation array 0 NULL proxy getHostInformation returns Localhost via UNIX socket string 25 Localhost via UNIX socket See Also mysqlnd_uh_set_connection_proxy mysqli_get_host_info mysql_get...

Страница 2756: ...STS test mysqli query CREATE TABLE test id INT AUTO_INCREMENT PRIMARY KEY col VARCHAR 255 mysqli query INSERT INTO test col VALUES a var_dump mysqli insert_id The above example will output proxy getLastInsertId array 0 NULL proxy getLastInsertId returns 1 int 1 See Also mysqlnd_uh_set_connection_proxy mysqli_insert_id mysql_insert_id 20 7 8 7 14 MysqlndUhConnection getLastMessage Copyright 1997 20...

Страница 2757: ...ysqli localhost root test var_dump mysqli info mysqli query DROP TABLE IF EXISTS test var_dump mysqli info The above example will output proxy getLastMessage array 0 NULL proxy getLastMessage returns string 0 proxy getLastMessage array 0 NULL proxy getLastMessage returns string 0 See Also mysqlnd_uh_set_connection_proxy mysqli_info mysql_info 20 7 8 7 15 MysqlndUhConnection getProtocolInformation ...

Страница 2758: ...t test var_dump mysqli protocol_version The above example will output proxy getProtocolInformation array 0 NULL proxy getProtocolInformation returns 10 int 10 See Also mysqlnd_uh_set_connection_proxy mysqli_get_proto_info mysql_get_proto_info 20 7 8 7 16 MysqlndUhConnection getServerInformation Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection getServerInformation Returns th...

Страница 2759: ...returns 5 1 45 debug log string 16 5 1 45 debug log See Also mysqlnd_uh_set_connection_proxy mysqli_get_server_info mysql_get_server_info 20 7 8 7 17 MysqlndUhConnection getServerStatistics Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection getServerStatistics Gets the current system status Description public string MysqlndUhConnection getServerStatistics mysqlnd_connection c...

Страница 2760: ...l_stat 20 7 8 7 18 MysqlndUhConnection getServerVersion Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection getServerVersion Returns the version of the MySQL server as an integer Description public int MysqlndUhConnection getServerVersion mysqlnd_connection connection Returns the version of the MySQL server as an integer Parameters connection Mysqlnd connection handle Do not m...

Страница 2761: ... Description public string MysqlndUhConnection getSqlstate mysqlnd_connection connection Returns the SQLSTATE error from previous MySQL operation Parameters connection Mysqlnd connection handle Do not modify Return Values The SQLSTATE code Examples Example 20 354 MysqlndUhConnection getSqlstate example php class proxy extends MysqlndUhConnection public function getSqlstate res printf s s n __METHO...

Страница 2762: ...ction getStatistics mysqlnd_connection connection Returns statistics about the client connection Warning This function is currently not documented only its argument list is available Parameters connection Mysqlnd connection handle Do not modify Return Values Connection statistics collected by mysqlnd Examples Example 20 355 MysqlndUhConnection getStatistics example php class proxy extends MysqlndU...

Страница 2763: ...index_used 0 bad_index_used 0 slow_queries 0 buffered_sets 0 unbuffered_sets 0 ps_buffered_sets 0 ps_unbuffered_sets 0 flushed_normal_sets 0 flushed_ps_sets 0 ps_prepared_never_executed 0 ps_prepared_once_executed 0 rows_fetched_from_server_normal 0 rows_fetched_from_server_ps 0 rows_buffered_from_client_normal 0 rows_buffered_from_client_ps 0 rows_fetched_from_client_normal_buffered 0 rows_fetche...

Страница 2764: ...0 proto_text_fetched_time 0 proto_text_fetched_datetime 0 proto_text_fetched_timestamp 0 proto_text_fetched_string 0 proto_text_fetched_blob 0 proto_text_fetched_enum 0 proto_text_fetched_set 0 proto_text_fetched_geometry 0 proto_text_fetched_other 0 proto_binary_fetched_null 0 proto_binary_fetched_bit 0 proto_binary_fetched_tinyint 0 proto_binary_fetched_short 0 proto_binary_fetched_int24 0 proto...

Страница 2765: ...ts_sent string 1 2 packets_received string 1 2 protocol_overhead_in string 1 8 protocol_overhead_out string 1 8 bytes_received_ok_packet string 1 0 bytes_received_eof_packet string 1 0 bytes_received_rset_header_packet string 1 0 bytes_received_rset_field_meta_packet string 1 0 bytes_received_rset_row_packet string 1 0 bytes_received_prepare_response_packet string 1 0 bytes_received_change_user_pa...

Страница 2766: ...ps string 1 0 rows_fetched_from_client_normal_buffered string 1 0 rows_fetched_from_client_normal_unbuffered string 1 0 rows_fetched_from_client_ps_buffered string 1 0 rows_fetched_from_client_ps_unbuffered string 1 0 rows_fetched_from_client_ps_cursor string 1 0 rows_affected_normal string 1 0 rows_affected_ps string 1 0 rows_skipped_normal string 1 0 rows_skipped_ps string 1 0 copy_on_write_save...

Страница 2767: ...malloc_count string 1 0 mem_malloc_amount string 1 0 mem_calloc_count string 1 0 mem_calloc_amount string 1 0 mem_realloc_count string 1 0 mem_realloc_amount string 1 0 mem_free_count string 1 0 mem_free_amount string 1 0 mem_estrndup_count string 1 0 mem_strndup_count string 1 0 mem_estndup_count string 1 0 mem_strdup_count string 1 0 proto_text_fetched_null string 1 0 proto_text_fetched_bit stri...

Страница 2768: ...etched_short string 1 0 proto_binary_fetched_int24 string 1 0 proto_binary_fetched_int string 1 0 proto_binary_fetched_bigint string 1 0 proto_binary_fetched_decimal string 1 0 proto_binary_fetched_float string 1 0 proto_binary_fetched_double string 1 0 proto_binary_fetched_date string 1 0 proto_binary_fetched_year string 1 0 proto_binary_fetched_time string 1 0 proto_binary_fetched_datetime strin...

Страница 2769: ...ange_user string 1 0 com_binlog_dump string 1 0 com_table_dump string 1 0 com_connect_out string 1 0 com_register_slave string 1 0 com_stmt_prepare string 1 0 com_stmt_execute string 1 0 com_stmt_send_long_data string 1 0 com_stmt_close string 1 0 com_stmt_reset string 1 0 com_stmt_set_option string 1 0 com_stmt_fetch string 1 0 com_deamon string 1 0 bytes_received_real_data_normal string 1 0 byte...

Страница 2770: ...public function getThreadId res printf s s n __METHOD__ var_export func_get_args true ret parent getThreadId res printf s returns s n __METHOD__ var_export ret true return ret mysqlnd_uh_set_connection_proxy new proxy mysqli new mysqli localhost root test var_dump mysqli thread_id The above example will output proxy getThreadId array 0 NULL proxy getThreadId returns 27646 int 27646 See Also mysqln...

Страница 2771: ...true ret parent getWarningCount res printf s returns s n __METHOD__ var_export ret true return ret mysqlnd_uh_set_connection_proxy new proxy mysqli new mysqli localhost root test var_dump mysqli warning_count The above example will output proxy getWarningCount array 0 NULL proxy getWarningCount returns 0 int 0 See Also mysqlnd_uh_set_connection_proxy mysqli_warning_count 20 7 8 7 23 MysqlndUhConne...

Страница 2772: ...ection public function init res printf s s n __METHOD__ var_export func_get_args true ret parent init res printf s returns s n __METHOD__ var_export ret true return ret mysqlnd_uh_set_connection_proxy new proxy mysqli new mysqli localhost root test The above example will output proxy init array 0 NULL proxy init returns true See Also mysqlnd_uh_set_connection_proxy 20 7 8 7 24 MysqlndUhConnection ...

Страница 2773: ...ort ret true return ret mysqlnd_uh_set_connection_proxy new proxy mysqli new mysqli localhost root test mysqli kill mysqli thread_id The above example will output proxy killConnection array 0 NULL 1 27650 proxy killConnection returns true See Also mysqlnd_uh_set_connection_proxy mysqli_kill 20 7 8 7 25 MysqlndUhConnection listFields Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhCon...

Страница 2774: ...set_connection_proxy new proxy mysql mysql_connect localhost root mysql_select_db test mysql mysql_query DROP TABLE IF EXISTS test_a mysql mysql_query CREATE TABLE test_a id INT col1 VARCHAR 255 mysql res mysql_list_fields test test_a mysql printf num_rows d n mysql_num_rows res while row mysql_fetch_assoc res var_dump row The above example will output proxy listFields array 0 NULL 1 test_a 2 prox...

Страница 2775: ...n listMethod example php class proxy extends MysqlndUhConnection public function listMethod res query pattern par1 printf s s n __METHOD__ var_export func_get_args true ret parent listMethod res query pattern par1 printf s returns s n __METHOD__ var_export ret true return ret mysqlnd_uh_set_connection_proxy new proxy mysql mysql_connect localhost root res mysql_list_dbs mysql printf num_rows d n m...

Страница 2776: ...ery results from a multi query Description public bool MysqlndUhConnection moreResults mysqlnd_connection connection Check if there are any more query results from a multi query Parameters connection Mysqlnd connection handle Do not modify Return Values Returns TRUE on success Otherwise returns FALSE Examples Example 20 362 MysqlndUhConnection moreResults example php class proxy extends MysqlndUhC...

Страница 2777: ...ULL proxy moreResults returns true array 1 _two string 1 2 proxy moreResults array 0 NULL proxy moreResults returns false See Also mysqlnd_uh_set_connection_proxy mysqli_more_results 20 7 8 7 28 MysqlndUhConnection nextResult Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection nextResult Prepare next result from multi_query Description public bool MysqlndUhConnection nextResul...

Страница 2778: ...tch_assoc printf s n str_repeat 40 while mysqli more_results mysqli next_result The above example will output array 1 _one string 1 1 proxy nextResult array 0 NULL proxy nextResult returns true array 1 _two string 1 2 See Also mysqlnd_uh_set_connection_proxy mysqli_next_result 20 7 8 7 29 MysqlndUhConnection ping Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection ping Pings a...

Страница 2779: ... new mysqli localhost root test mysqli ping The above example will output proxy ping array 0 NULL proxy ping returns true See Also mysqlnd_uh_set_connection_proxy mysqli_ping mysql_ping 20 7 8 7 30 MysqlndUhConnection query Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection query Performs a query on the database Description public bool MysqlndUhConnection query mysqlnd_connec...

Страница 2780: ...t proxy query array 0 NULL 1 SELECT Welcome mysqlnd_uh FROM DUAL proxy query returns true array 1 How about query rewriting string 26 How about query rewriting See Also mysqlnd_uh_set_connection_proxy mysqli_query mysql_query 20 7 8 7 31 MysqlndUhConnection queryReadResultsetHeader Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection queryReadResultsetHeader Read a result set h...

Страница 2781: ...y mysqli new mysqli localhost root test res mysqli query SELECT Welcome mysqlnd_uh FROM DUAL var_dump res fetch_assoc The above example will output proxy queryReadResultsetHeader array 0 NULL 1 NULL proxy queryReadResultsetHeader returns true array 1 Welcome mysqlnd_uh string 19 Welcome mysqlnd_uh See Also mysqlnd_uh_set_connection_proxy 20 7 8 7 32 MysqlndUhConnection reapQuery Copyright 1997 201...

Страница 2782: ...onn1 thread_id array link conn1 processed false conn2 thread_id array link conn2 processed false saved_errors array do poll_links poll_errors poll_reject array foreach links as thread_id link if link processed poll_links link link poll_errors link link poll_reject link link if 0 count poll_links break if 0 num_ready mysqli_poll poll_links poll_errors poll_reject 0 200000 continue if empty poll_err...

Страница 2783: ...eshServer Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection refreshServer Flush or reset tables and caches Description public bool MysqlndUhConnection refreshServer mysqlnd_connection connection int options Flush or reset tables and caches Warning This function is currently not documented only its argument list is available Parameters connection Mysqlnd connection handle Do ...

Страница 2784: ...tion_proxy 20 7 8 7 34 MysqlndUhConnection restartPSession Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection restartPSession Restart a persistent mysqlnd connection Description public bool MysqlndUhConnection restartPSession mysqlnd_connection connection Restart a persistent mysqlnd connection Parameters connection Mysqlnd connection handle Do not modify Return Values Return...

Страница 2785: ...l MysqlndUhConnection selectDb mysqlnd_connection connection string database Selects the default database for database queries Parameters connection Mysqlnd connection handle Do not modify database The database name Return Values Returns TRUE on success Otherwise returns FALSE Examples Example 20 370 MysqlndUhConnection selectDb example php class proxy extends MysqlndUhConnection public function s...

Страница 2786: ...nnection sendClose mysqlnd_connection connection Sends a close command to MySQL Parameters connection Mysqlnd connection handle Do not modify Return Values Returns TRUE on success Otherwise returns FALSE Examples Example 20 371 MysqlndUhConnection sendClose example php class proxy extends MysqlndUhConnection public function sendClose res printf s s n __METHOD__ var_export func_get_args true ret pa...

Страница 2787: ... string query Sends a query to MySQL Parameters connection Mysqlnd connection handle Do not modify query The query string Return Values Returns TRUE on success Otherwise returns FALSE Examples Example 20 372 MysqlndUhConnection sendQuery example php class proxy extends MysqlndUhConnection public function sendQuery res query printf s s n __METHOD__ var_export func_get_args true ret parent sendQuery...

Страница 2788: ...eters connection Mysqlnd connection handle Do not modify Return Values Returns TRUE on success Otherwise returns FALSE Examples Example 20 373 MysqlndUhConnection serverDumpDebugInformation example php class proxy extends MysqlndUhConnection public function serverDumpDebugInformation res printf s s n __METHOD__ var_export func_get_args true ret parent serverDumpDebugInformation res printf s return...

Страница 2789: ... on auto commit or not Return Values Returns TRUE on success Otherwise returns FALSE Examples Example 20 374 MysqlndUhConnection setAutocommit example php class proxy extends MysqlndUhConnection public function setAutocommit res mode printf s s n __METHOD__ var_export func_get_args true ret parent setAutocommit res mode printf s returns s n __METHOD__ var_export ret true return ret mysqlnd_uh_set_...

Страница 2790: ...arset The charset to be set as default Return Values Returns TRUE on success Otherwise returns FALSE Examples Example 20 375 MysqlndUhConnection setCharset example php class proxy extends MysqlndUhConnection public function setCharset res charset printf s s n __METHOD__ var_export func_get_args true ret parent setCharset res charset printf s returns s n __METHOD__ var_export ret true return ret my...

Страница 2791: ...D_SHARED_MEMORY_BASE_NAME MYSQLND_UH_MYSQLND_SHARED_MEMORY_BASE_NAME MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT MYSQLND_UH_MYSQLND_OPT_USE_RESULT MYSQLND_UH_MYSQLND_OPT_USE_RESULT MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION MYSQLND_UH_MYSQLND_OPT_USE_...

Страница 2792: ...ing option var_export value true ret parent setClientOption res option value printf s returns s n __METHOD__ var_export ret true return ret mysqlnd_uh_set_connection_proxy new proxy mysqli new mysqli localhost root test The above example will output proxy setClientOption array 0 NULL 1 210 2 3221225472 Option MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET set to 3221225472 proxy setClientOption returns...

Страница 2793: ...MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_OFF ret MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON break return ret class proxy extends MysqlndUhConnection public function setServerOption res option printf s s n __METHOD__ var_export func_get_args true printf Option s set n server_option_to_string option ret parent setServerOption res option printf s returns s n __METHOD__ var_export ret true return r...

Страница 2794: ...ME level Return Values 20 7 8 7 44 MysqlndUhConnection simpleCommand Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection simpleCommand Sends a basic COM_ command Description public bool MysqlndUhConnection simpleCommand mysqlnd_connection connection int command string arg int ok_packet bool silent bool ignore_upsert_status Sends a basic COM_ command to MySQL Parameters connect...

Страница 2795: ..._UH_MYSQLND_COM_STMT_EXECUTE MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA MYSQLND_UH_MYSQLND_COM_STMT_CLOSE MYSQLND_UH_MYSQLND_COM_STMT_CLOSE MYSQLND_UH_MYSQLND_COM_STMT_RESET MYSQLND_UH_MYSQLND_COM_STMT_RESET MYSQLND_UH_MYSQLND_COM_SET_OPTION MYSQLND_UH_MYSQLND_COM_SET_OPTION MYSQLND_UH_MYSQLND_COM_STMT_FETCH MYSQLND_UH_MYSQLND_COM_STMT_FETCH MYSQLND_UH_MY...

Страница 2796: ...mpleCommand returns true See Also mysqlnd_uh_set_connection_proxy 20 7 8 7 45 MysqlndUhConnection simpleCommandHandleResponse Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection simpleCommandHandleResponse Process a response for a basic COM_ command send to the client Description public bool MysqlndUhConnection simpleCommandHandleResponse mysqlnd_connection connection int ok_p...

Страница 2797: ..._COM_REGISTER_SLAVED MYSQLND_UH_MYSQLND_COM_STMT_PREPARE MYSQLND_UH_MYSQLND_COM_STMT_PREPARE MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA MYSQLND_UH_MYSQLND_COM_STMT_CLOSE MYSQLND_UH_MYSQLND_COM_STMT_CLOSE MYSQLND_UH_MYSQLND_COM_STMT_RESET MYSQLND_UH_MYSQLND_COM_STMT_RESET MYSQLND_UH_MY...

Страница 2798: ...ponse returns true See Also mysqlnd_uh_set_connection_proxy 20 7 8 7 46 MysqlndUhConnection sslSet Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection sslSet Used for establishing secure connections using SSL Description public bool MysqlndUhConnection sslSet mysqlnd_connection connection string key string cert string ca string capath string cipher Used for establishing secure...

Страница 2799: ...sslSet array 0 NULL 1 key 2 cert 3 ca 4 capath 5 cipher proxy sslSet returns true See Also mysqlnd_uh_set_connection_proxy mysqli_ssl_set 20 7 8 7 47 MysqlndUhConnection stmtInit Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection stmtInit Initializes a statement and returns a resource for use with mysqli_statement prepare Description public resource MysqlndUhConnection stmtIn...

Страница 2800: ...mtInit array 0 NULL resource 19 of type Mysqlnd Connection proxy stmtInit returns NULL resource 246 of type Mysqlnd Prepared Statement internal only you must not modify it int 1 See Also mysqlnd_uh_set_connection_proxy mysqli_stmt_init 20 7 8 7 48 MysqlndUhConnection storeResult Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection storeResult Transfers a result set from the las...

Страница 2801: ...ning AS _msg FROM DUAL res mysqli store_result var_dump res fetch_assoc The above example will output proxy storeResult array 0 NULL proxy storeResult returns NULL resource 475 of type Mysqlnd Resultset internal only you must not modify it array 1 _msg string 27 Also called buffered result proxy storeResult array 0 NULL proxy storeResult returns NULL resource 730 of type Mysqlnd Resultset internal...

Страница 2802: ... res printf s returns s n __METHOD__ var_export ret true return ret mysqlnd_uh_set_connection_proxy new proxy mysqli new mysqli localhost root test mysqli commit The above example will output proxy txCommit array 0 NULL proxy txCommit returns true See Also mysqlnd_uh_set_connection_proxy mysqli_commit 20 7 8 7 50 MysqlndUhConnection txRollback Copyright 1997 2012 the PHP Documentation Group 2230 M...

Страница 2803: ...ollback The above example will output proxy txRollback array 0 NULL proxy txRollback returns true See Also mysqlnd_uh_set_connection_proxy mysqli_commit 20 7 8 7 51 MysqlndUhConnection useResult Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhConnection useResult Initiate a result set retrieval Description public resource MysqlndUhConnection useResult mysqlnd_connection connection In...

Страница 2804: ...ult array 0 NULL proxy useResult returns NULL resource 425 of type Mysqlnd Resultset internal only you must not modify it array 1 _msg string 13 Good morning See Also mysqlnd_uh_set_connection_proxy mysqli_use_result mysqli_real_query 20 7 8 8 The MysqlndUhPreparedStatement class MysqlndUhPreparedStatement Copyright 1997 2012 the PHP Documentation Group 2230 MysqlndUhPreparedStatement MysqlndUhPre...

Страница 2805: ...ool MysqlndUhPreparedStatement execute mysqlnd_prepared_statement statement Executes a prepared Query Parameters statement Mysqlnd prepared statement handle Do not modify Resource of type Mysqlnd Prepared Statement internal only you must not modify it Return Values Returns TRUE on success Otherwise returns FALSE Examples Example 20 386 MysqlndUhPreparedStatement execute example php class stmt_prox...

Страница 2806: ... execution Description public bool MysqlndUhPreparedStatement prepare mysqlnd_prepared_statement statement string query Prepare an SQL statement for execution Parameters statement Mysqlnd prepared statement handle Do not modify Resource of type Mysqlnd Prepared Statement internal only you must not modify it query The query to be prepared Return Values Returns TRUE on success Otherwise returns FALS...

Страница 2807: ..._mysqlnd Converts a MySQL connection handle into a mysqlnd connection handle Description resource mysqlnd_uh_convert_to_mysqlnd mysqli mysql_connection Converts a MySQL connection handle into a mysqlnd connection handle After conversion you can execute mysqlnd library calls on the connection handle This can be used to access mysqlnd functionality not made available through user space API calls The...

Страница 2808: ...rt_to_mysqlnd mysql_connection Create Proxy to call mysqlnd connection class methods obj new MySQLndUHConnection Call mysqlnd_conn get_thread_id var_dump obj getThreadId mysqlnd Use SQL to fetch connection thread id var_dump mysql_connection query SELECT CONNECTION_ID fetchAll The above example will output int 27054 array 1 0 array 2 CONNECTION_ID string 5 27054 0 string 5 27054 See Also mysqlnd_u...

Страница 2809: ...ion mysqli_connection Object of type mysqli If given the proxy will be set for this particular connection only Return Values Returns TRUE on success Otherwise returns FALSE Examples Example 20 389 mysqlnd_uh_set_connection_proxy example php mysqli new mysqli localhost root test mysqli query SELECT No proxy installed yet class proxy extends MysqlndUhConnection public function query res query printf...

Страница 2810: ...rror of the type E_WARNING may be emitted The error message may read like PHP Warning mysqlnd_uh_set_statement_proxy Mysqlnd User Handler The plugin has been disabled by setting the configuration parameter mysqlnd_uh enable false The proxy has not been installed Parameters statement_proxy The mysqlnd statement proxy object of type MysqlndUhStatement Return Values Returns TRUE on success Otherwise ...

Страница 2811: ...ver the MySQL Client Library libmysqlclient Mysqlnd plugins like mysqlnd_mux operate for the most part transparently from a user perspective The connection multiplexing plugin supports all PHP applications and all MySQL PHP extensions It does not change existing APIs Therefore it can easily be used with existing PHP applications Note This is a proof of concept All features are at an early stage No...

Страница 2812: ...of the consequences of connection sharing connections 20 7 9 3 About the name mysqlnd_mux Copyright 1997 2012 the PHP Documentation Group 2230 The shortcut mysqlnd_mux stands for mysqlnd connection multiplexing plugin 20 7 9 4 Concepts Copyright 1997 2012 the PHP Documentation Group 2230 This explains the architecture and related concepts for this plugin Reading and understanding these concepts is...

Страница 2813: ...er connection at a time The multiplexing plugin changes A MySQL connection is shared among multiple user handles There no one to one relation if using the plugin Sharing pooled connections has an impact on the connection state State changing operations from multiple user handles pointing to one MySQL connection are not isolated from each other If for example a session variable is set through one u...

Страница 2814: ...ugins version number can be obtained using MYSQLND_MUX_VERSION or MYSQLND_MUX_VERSION_ID MYSQLND_MUX_VERSION is the string representation of the numerical version number MYSQLND_MUX_VERSION_ID which is an integer such as 10000 Developers can calculate the version number as follows Version part Example Major 10000 1 10000 10000 Minor 100 0 100 0 Patch 0 0 MYSQLND_MUX_VERSION_ID 10000 MYSQLND_MUX_VE...

Страница 2815: ...ache requests Figure 20 70 mysqlnd_memcache data flow Note This plugin depends on the MySQL InnoDB Memcached Daemon Plugin It is not provided to be used with a stand alone Memcached For a generic query cache using Memcached look at the mysqlnd query cache plugin For direct Memcache access look at the memcache and memcached extensions The MySQL native driver for PHP is a C library that ships togeth...

Страница 2816: ...SQL Memcache plugins for InnoDB and NDB MySQL Cluster The plugin is not related to the Memcached cache server 20 7 10 4 Quickstart and Examples Copyright 1997 2012 the PHP Documentation Group 2230 The mysqlnd memcache plugin is easy to use This quickstart will demo typical use cases and provide practical advice on getting started It is strongly recommended to read the reference sections in additio...

Страница 2817: ... value_columns flags cas_column expire_time_column unique_idx_name_on_key VALUES plugin_test test test id f1 f2 f3 flags cas_column expire_time_column PRIMARY KEY 20 7 10 4 2 Usage Copyright 1997 2012 the PHP Documentation Group 2230 After associating a MySQL connection with a Memcache connection using mysqnd_memcache_set the plugin attempts to transparently replace SQL SELECT statements by a memc...

Страница 2818: ... 5 4 4 or never The required PHP extensions are PCRE enabled by default and the memcached extension version 2 0 x The mysqlnd_memcache Memcache plugin supports all PHP applications and all available PHP MySQL extensions mysqli mysql PDO_MYSQL The PHP MySQL extension must be configured with mysqlnd support For accessing InnoDB tables this PHP extension requires MySQL Server 5 6 6 or newer with the ...

Страница 2819: ...HP Documentation Group 2230 The constants below are defined by this extension and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime MySQL Memcache Plugin related MYSQLND_MEMCACHE_DEFAULT_REGEXP string Default regular expression PCRE style used for matching SELECT statements that will be mapped into a MySQL Memcache Plugin access point if p...

Страница 2820: ...ble 20 77 mysqlnd_memcache_get_config array structure Array Key Description memcached Instance of Memcached associated to this MySQL connection by mysqlnd_memcache_set You can use this to change settings of the memcache connection or directly by querying the server on this connection pattern The PCRE regular expression used to match the SQL query sent to the server Queries matching this pattern wi...

Страница 2821: ...Name of the database field column with the id used as key when accessing the table via memcache Often this is the database field having a primary key separator The separator used to split the different field values This is needed as memcache only provides access to a single value while MySQL can map multiple columns to this value Note The separator which can be set in the MySQL Server configuratio...

Страница 2822: ...nodb_memcache containers c See Also mysqlnd_memcache_set 20 7 10 7 2 mysqlnd_memcache_set Copyright 1997 2012 the PHP Documentation Group 2230 mysqlnd_memcache_set Associate a MySQL connection with a Memcache connection Description bool mysqlnd_memcache_set mixed mysql_connection Memcached memcache_connection string pattern callback callback Associate mysql_connection with memcache_connection usin...

Страница 2823: ...et to NULL then a default pattern will be used callback A callback which will be used whenever a query is being sent to MySQL The callback will receive a single boolean parameter telling if a query was sent via Memcache Return Values TRUE if the association or disassociation is successful otherwise FALSE if there is an error Examples Example 20 394 mysqlnd_memcache_set example with var_dump as a s...

Страница 2824: ...me Exceeded This is a PHP limit go into the php ini file and set the maximum execution time up from 30 seconds to something higher as needed It is also not a bad idea to double the RAM allowed per script to 16MB instead of 8MB Fatal error Call to unsupported or undefined function mysql_connect in This means that your PHP version isn t compiled with MySQL support You can either compile a dynamic My...

Страница 2825: ...commended Perl interface It replaces an older interface called mysqlperl which should be considered obsolete These sections contain information about using Perl with MySQL and writing MySQL applications in Perl For installation instructions for Perl DBI support see Section 2 22 Perl Installation Notes For an example of reading options from option files see Section 5 3 4 Using Client Programs in a ...

Страница 2826: ...Two APIs are available for Ruby programmers developing MySQL applications The MySQL Ruby API is based on the libmysqlclient API library For information on installing and using the MySQL Ruby API see Section 20 10 1 The MySQL Ruby API The Ruby MySQL API is written to use the native MySQL network protocol a native driver For information on installing and using the Ruby MySQL API see Section 20 10 2 ...

Страница 2827: ...manager thread handles TCP IP connection requests On Unix this manager thread also handles Unix socket file connection requests On Windows a manager thread handles shared memory connection requests and another handles named pipe connection requests The server does not create threads to handle interfaces that it does not listen to For example a Windows server that does not have support for named pi...

Страница 2828: ...L releases work well with your applications The test system consists of a test language interpreter mysqltest a Perl script to run all tests mysql test run pl the actual test cases written in a special test language and their expected results To run the test suite on your system after a build type make test from the source root directory or change location to the mysql test directory and type mysq...

Страница 2829: ...tions for writing UDFs discuss security precautions that MySQL takes to prevent UDF misuse and describe how to add native MySQL functions For example source code that illustrates how to write UDFs take a look at the sql udf_example c file that is provided in MySQL source distributions 21 2 1 Features of the User Defined Function Interface The MySQL interface for user defined functions provides the...

Страница 2830: ...unction names remain readable in the completed UDF The following list describes the C C functions that you write to implement the interface for a function named XXX The main function xxx is required In addition a UDF requires at least one of the other functions described here for reasons discussed in Section 21 2 2 6 User Defined Function Security Precautions xxx The main function This is where th...

Страница 2831: ... each row that belongs in the same group 5 Call xxx to get the result for the aggregate when the group changes or after the last row has been processed 6 Repeat steps 3 to 5 until all rows has been processed 7 Call xxx_deinit to let the UDF free any memory it has allocated All functions must be thread safe This includes not just the main function but the initialization and deinitialization functio...

Страница 2832: ... cases such as a FLOAT or DOUBLE column declared without an explicit number of decimals for example FLOAT rather than FLOAT 10 3 and for floating point constants such as 1345E 3 It is also used for string and other nonnumber arguments that might be converted within the function to numeric form The value to which the decimals member is initialized is only a default It can be changed within the func...

Страница 2833: ...group but can also be called to reset the values for a query where there were no matching rows Declare xxx_clear as follows void xxx_clear UDF_INIT initid char is_null char error is_null is set to point to CHAR 0 before calling xxx_clear If something went wrong you can store a value in the variable to which the error argument points error points to a single byte variable not to a string buffer xxx...

Страница 2834: ...eturn an error if they are not check the arg_type array in the initialization function For example if args arg_type 0 STRING_RESULT args arg_type 1 INT_RESULT strcpy message XXX requires a string and an integer return 1 Arguments of type DECIMAL_RESULT are passed as strings so you should handle them the same way as STRING_RESULT values As an alternative to requiring your function s arguments to be...

Страница 2835: ...SULT you must cast args args i to a double value double real_val real_val double args args i For an argument of type DECIMAL_RESULT the value is passed as a string and should be handled like a STRING_RESULT value ROW_RESULT arguments are not implemented unsigned long lengths For the initialization function the lengths array indicates the maximum string length for each argument You should not chang...

Страница 2836: ...buffer if it fits in which case the return value should be a pointer to the buffer If the function stores the result in a different buffer it should return a pointer to that buffer If your string function does not use the supplied buffer for example if it needs to return a string longer than 255 characters you must allocate the space for your own buffer with malloc in your xxx_init function or you...

Страница 2837: ...xample so Compiling the shared object using make produces a file named something like udf_example so 0 0 0 in the libs directory the exact name may vary from platform to platform As of MySQL 5 0 67 copy the shared object to server s plugin directory and name it udf_example so This directory is given by the value of the plugin_dir 481 system variable Prior to MySQL 5 0 67 or if the value of plugin_...

Страница 2838: ...e so mysql CREATE FUNCTION sequence RETURNS INTEGER SONAME udf_example so mysql CREATE FUNCTION lookup RETURNS STRING SONAME udf_example so mysql CREATE FUNCTION reverse_lookup RETURNS STRING SONAME udf_example so mysql CREATE AGGREGATE FUNCTION avgcost RETURNS REAL SONAME udf_example so To delete functions use DROP FUNCTION mysql DROP FUNCTION metaphon mysql DROP FUNCTION myfunc_double mysql DROP...

Страница 2839: ...ing this capability 21 2 3 Adding a New Native Function To add a new native MySQL function use the procedure described here which requires that you use a source distribution You cannot add native functions to a binary distribution because it is necessary to modify MySQL source code and compile MySQL from the modified source If you migrate to another version of MySQL for example when a new version ...

Страница 2840: ... must be thread safe In other words do not use any global or static variables in the functions without protecting them with mutexes If you want to return NULL from val val_int or str you should set null_value to 1 and return 0 For str object functions there are additional considerations to be aware of The String str argument provides a string buffer that may be used to hold the result For more inf...

Страница 2841: ...new in MySQL you can try to run mysqld with the skip new which disables all new potentially unsafe functionality See Section C 5 4 2 What to Do If MySQL Keeps Crashing If mysqld doesn t want to start you should verify that you don t have any my cnf files that interfere with your setup You can check your my cnf arguments with mysqld print defaults and avoid using them by starting with mysqld no def...

Страница 2842: ...gdb on the core file to find out what happened When you configure MySQL for debugging you automatically enable a lot of extra safety check functions that monitor the health of mysqld If they find something unexpected an entry is written to stderr which mysqld_safe directs to the error log This also means that if you are having some unexpected problems with MySQL and are using a source distribution...

Страница 2843: ...iles see Microsoft Knowledge Base Article 121366 For more information on the debugging options available see Debugging Tools for Windows Dr Watson is installed with all Windows distributions but if you have installed Windows development tools Dr Watson may have been replaced with WinDbg the debugger included with Visual Studio or the debugging tools provided with Borland or Delphi To generate a cr...

Страница 2844: ...le 404 option This core file can be used to make a backtrace that may help you find out why mysqld died shell gdb mysqld core gdb backtrace full gdb quit See Section C 5 4 2 What to Do If MySQL Keeps Crashing If you are using gdb 4 17 x or above on Linux you should install a gdb file with the following information in your current directory set print sevenbit off handle SIGUSR1 nostop noprint handl...

Страница 2845: ...80c1686 You can use the resolve_stack_dump utility to determine where mysqld died by using the following procedure 1 Copy the preceding numbers to a file for example mysqld stack 0x9da402 0x6648e9 0x7f1a5af000f0 0x7f1a5a10f0f2 0x7412cb 0x688354 0x688494 0x67a170 0x67f0ad 0x67fdf8 0x6811b6 0x66e05e 2 Make a symbol file for the mysqld server shell nm n libexec mysqld tmp mysqld sym If mysqld is not ...

Страница 2846: ...ction 5 2 4 The Slow Query Log If you find the text mysqld restarted in the error log file normally named hostname err you probably have found a query that causes mysqld to fail If this happens you should check all your tables with myisamchk see Chapter 5 MySQL Server Administration and test the queries in the MySQL log files to see whether one fails If you find such a query try first upgrading to...

Страница 2847: ...configure MySQL with with debug 122 or with debug full 122 See Section 2 17 3 MySQL Source Configuration Options Before running a client you should set the MYSQL_DEBUG environment variable shell MYSQL_DEBUG d t O tmp client trace shell export MYSQL_DEBUG This causes clients to generate a trace file in tmp client trace If you have problems with your own client code you should attempt to connect to ...

Страница 2848: ... file called dbugmon out containing information that can be used to profile the program May be followed by a list of keywords that select profiling only for the functions in that list A null list implies that all functions are considered L Identify the source file line number for each line of debug or trace output n Print the current function nesting depth for each line of debug or trace output N ...

Страница 2849: ...The DBUG Package 2829 d t i O mysqld trace In MySQL common tags to print with the d option are enter exit error warning info and loop ...

Страница 2850: ...2830 ...

Страница 2851: ... single MySQL server that is important to your business all the way up to a huge farm of MySQL servers powering a busy web site The following discussion briefly summarizes the basic components that make up the MySQL Enterprise Monitor product For more information see the MySQL Enterprise Monitor manual available at http dev mysql com doc mysql monitor en MySQL Enterprise Monitor components can be ...

Страница 2852: ...r server including the row counts and performance times for executing each query You can correlate the detailed query data with the graphical information to identify which queries were executing when you experienced a particularly high load index or other issue The query data is supported by a system called Query Analyzer and the data can be presented in different ways depending on your needs 22 2...

Страница 2853: ...prise Audit provides an out of box easy to use auditing and compliance solution for applications that are governed by both internal and external regulatory guidelines When installed the audit plugin enables MySQL Server to produce a log file containing an audit record of server activity The log contents include when clients connect and disconnect and what actions they perform while connected such ...

Страница 2854: ...2834 ...

Страница 2855: ...ncer Library License 2863 A 25 RFC 3174 US Secure Hash Algorithm 1 SHA1 License 2864 A 26 Richard A O Keefe String Library License 2864 A 27 SHA 1 in C License 2865 A 28 Simple Logging Facade for Java SLF4J License 2865 A 29 zlib License 2865 A 30 ZLIB NET License 2866 The following is a list of the libraries we have included with the MySQL Server source and components used to test MySQL We are th...

Страница 2856: ...ic License Version 2 0 June 1991 Section A 21 md5 Message Digest Algorithm 5 License Section A 24 RegEX Spencer Library License Section A 26 Richard A O Keefe String Library License Section A 27 SHA 1 in C License Section A 29 zlib License MySQL Connector C Section A 3 Boost Library License Section A 22 OpenSSL v1 0 License MySQL Connector J Section A 1 Ant Contrib License Section A 4 c3p0 JDBC Li...

Страница 2857: ...ithout modification are permitted provided that the following conditions are met 1 Redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer 2 Redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the dist...

Страница 2858: ...mote products derived from this software without specific prior written permission THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT IND...

Страница 2859: ... is licensed under Section A 10 GNU Lesser General Public License Version 2 1 February 1999 A 5 dtoa c License The following software may be included in this product dtoa c The author of this software is David M Gay Copyright c 1991 2000 2001 by Lucent Technologies Permission to use copy modify and distribute this software for any purpose without fee is hereby granted provided that this entire not...

Страница 2860: ...de is derived from software contributed to The NetBSD Foundation by Anthony Mallet Redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met 1 Redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer 2 Redistributions in binary form must reproduce the ...

Страница 2861: ...NG NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE Some files are Copyright c 1998 Todd C Miller Todd Miller courtesan com Permission to use copy modify and distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copie...

Страница 2862: ...all dir lib and proxy install dir licenses lgpl folders The terms of the Oracle license do NOT apply to the GLib library it is licensed under the following license separately from the Oracle programs you receive If you do not wish to install this library you may create an exclude file and run tar with the X option as in the following example but the Oracle program might not operate properly or at ...

Страница 2863: ... You can apply it to your programs too When we speak of free software we are referring to freedom not price Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software and charge for this service if you wish that you receive source code or can get it if you want it that you can change the software or use pieces of it in new free programs an...

Страница 2864: ...es of the Program or any portion of it thus forming a work based on the Program and copy and distribute such modifications or work under the terms of Section 1 above provided that you also meet all of these conditions a You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change b You must cause any work that you distribute or publish ...

Страница 2865: ...ted need not include anything that is normally distributed in either source or binary form with the major components compiler kernel and so on of the operating system on which the executable runs unless that component itself accompanies the executable If distribution of executable or object code is made by offering access to copy from a designated place then offering equivalent access to copy the ...

Страница 2866: ...ght holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries so that distribution is permitted only in or among countries not thus excluded In such case this License incorporates the limitation as if written in the body of this License 9 The Free Software Foundation may publish revised and or new versions of the General Pub...

Страница 2867: ... by the Free Software Foundation either version 2 of the License or at your option any later version This program is distributed in the hope that it will be useful but WITHOUT ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE See the GNU General Public License for more details You should have received a copy of the GNU General Public License alon...

Страница 2868: ...icenses are intended to guarantee your freedom to share and change free software to make sure the software is free for all its users This license the Lesser General Public License applies to some specially designated software packages typically libraries of the Free Software Foundation and other authors who decide to use it You can use it too but we suggest you first think carefully about whether ...

Страница 2869: ...t also provides other free software developers Less of an advantage over competing non free programs These disadvantages are the reason we use the ordinary General Public License for many libraries However the Lesser license provides advantages in certain special circumstances For example on rare occasions there may be a special need to encourage the widest possible use of a certain library so tha...

Страница 2870: ... notice and disclaimer of warranty keep intact all the notices that refer to this License and to the absence of any warranty and distribute a copy of this License along with the Library You may charge a fee for the physical act of transferring a copy and you may at your option offer warranty protection in exchange for a fee 2 You may modify your copy or copies of the Library or any portion of it t...

Страница 2871: ... code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine readable source code which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange If distribution of object code is made by offering access to copy from a designated place then offering equivalent acce...

Страница 2872: ...brary mechanism for linking with the Library A suitable mechanism is one that 1 uses at run time a copy of the library already present on the user s computer system rather than copying library functions into the executable and 2 will operate properly with a modified version of the library if the user installs one as long as the modified version is interface compatible with the version that the wor...

Страница 2873: ...parties with this License 11 If as a consequence of a court judgment or allegation of patent infringement or for any other reason not limited to patent issues conditions are imposed on you whether by court order agreement or otherwise that contradict the conditions of this License they do not excuse you from the conditions of this License If you cannot distribute so as to satisfy simultaneously yo...

Страница 2874: ...ER EXPRESSED OR IMPLIED INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU SHOULD THE LIBRARY PROVE DEFECTIVE YOU ASSUME THE COST OF ALL NECESSARY SERVICING REPAIR OR CORRECTION 16 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRI...

Страница 2875: ...rce code If you received the Oracle software under a license other than a commercial non GPL license then the terms of the Oracle license do NOT apply to these files from GNU Libtool they are licensed under the following licenses separately from the Oracle programs you receive Oracle elects to use GNU General Public License version 2 GPL for any software where a choice of GPL or GNU Lesser Library...

Страница 2876: ...version may be used or where a choice of which version of the GPL is applied is unspecified This component is licensed under Section A 9 GNU General Public License Version 2 0 June 1991 A 13 jboss common jdbc wrapper jar License You are receiving a copy of jboss common jdbc wrapper jar in both source and object code in the following src lib jboss common jdbc wrapper jar The terms of the Oracle lic...

Страница 2877: ...USE OF THIS SOFTWARE EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE Parts developed by Adam Langley log c Based on err c which was adapted from OpenBSD libc err warncode Copyright c 2005 Nick Mathewson Copyright c 2000 Dug Song Copyright c 1993 The Regents of the University of California All rights reserved Redistribution and use in source and binary forms with or without modification are permi...

Страница 2878: ... THE USE OF THIS SOFTWARE EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE win32 c Copyright 2000 2002 Niels Provos Copyright 2003 Michael A Davis All rights reserved Redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met 1 Redistributions of source code must retain the above copyright notice this list of conditi...

Страница 2879: ...ONINFRINGEMENT IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTION OF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE Except as contained in this notice the name of the X Consortium shall not be used in advertising or otherwise to promote the sale use or other deali...

Страница 2880: ... copyright notice and this permission notice shall be included in all copies or substantial portions of the Software THE SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIED INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OT...

Страница 2881: ...on and use in source and binary forms with or without modification are permitted provided that the following conditions are met 1 Redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer 2 Redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentatio...

Страница 2882: ... conditions and the following disclaimer in the documentation and or other materials provided with the distribution 3 All advertising materials mentioning features or use of this software must display the following acknowledgement This product includes cryptographic software written by Eric Young eay cryptsoft com The word cryptographic can be left out if the routines from the library being used a...

Страница 2883: ...omote products derived from this software without specific prior written permission THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT IN...

Страница 2884: ...nternet organizations except as needed for the purpose of developing Internet standards in which case the procedures for copyrights defined in the Internet Standards process must be followed or as required to translate it into languages other than English The limited permissions granted above are perpetual and will not be revoked by the Internet Society or its successors or assigns This document a...

Страница 2885: ...n including without limitation the rights to use copy modify merge publish distribute sublicense and or sell copies of the Software and to permit persons to whom the Software is furnished to do so subject to the following conditions The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software THE SOFTWARE IS PROVIDED AS IS WITHOUT WA...

Страница 2886: ...entAce http www componentace com All rights reserved Redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met Redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer Redistributions in binary form must reproduce the above copyright notice this list o...

Страница 2887: ...deletes B 1 5 2868 Does MySQL 5 0 have a Query Cache Does it work on Server Instance or Database B 1 6 2868 Does MySQL 5 0 have Sequences B 1 7 2868 Does MySQL 5 0 have a NOW 926 function with fractions of seconds B 1 8 2868 Does MySQL 5 0 work with multi core processors B 1 9 2868 Why do I see multiple processes for mysqld B 1 10 2869 Have there been there any improvements in error reporting when...

Страница 2888: ...he operates on the server level caching complete result sets matched with the original query string If an exactly identical query is made which often happens particularly in web applications no parsing or execution is necessary the result is sent directly from the cache Various tuning options are available See Section 8 6 3 The MySQL Query Cache B 1 6 Does MySQL 5 0 have Sequences No However MySQL...

Страница 2889: ...stions and Answers B 2 1 Where can I obtain complete documentation for MySQL storage engines See Chapter 14 Storage Engines That chapter contains information about all MySQL storage engines except for the NDB storage engine used for MySQL Cluster NDB is covered in Chapter 17 MySQL Cluster B 2 2 Are there any new storage engines in MySQL 5 0 Yes The FEDERATED storage engine new in MySQL 5 0 allows ...

Страница 2890: ...ithin a connection either locally to the connection or to take effect globally You can retrieve the current mode by issuing a SELECT sql_mode statement B 3 4 Is the mode dependent on the database or connection A mode is not linked to a particular database Modes can be set locally to the session connection or globally for the server you can change these settings using SET GLOBAL SESSION sql_mode mo...

Страница 2891: ...to using mod_plsql as a gateway on Apache to talk directly to a stored procedure in the database B 4 17 2873 Can I pass an array as input to a stored procedure B 4 18 2873 Can I pass a cursor as an IN parameter to a stored procedure B 4 19 2873 Can I return a cursor as an OUT parameter from a stored procedure B 4 20 2873 Can I print out a variable s value within a stored routine for debugging purp...

Страница 2892: ...use this query on the INFORMATION_SCHEMA ROUTINES table SELECT ROUTINE_TYPE ROUTINE_NAME FROM INFORMATION_SCHEMA ROUTINES WHERE ROUTINE_SCHEMA dbname For more information see Section 19 8 The INFORMATION_SCHEMA ROUTINES Table The body of a stored routine can be viewed using SHOW CREATE FUNCTION for a stored function or SHOW CREATE PROCEDURE for a stored procedure See Section 13 7 5 8 SHOW CREATE P...

Страница 2893: ...le inside stored procedures only However if you do not open a cursor on a SELECT the result will be sent directly to the client You can also SELECT INTO variables See Section 13 2 8 SELECT Syntax B 4 20 Can I print out a variable s value within a stored routine for debugging purposes Yes you can do this in a stored procedure but not in a stored function If you perform an ordinary SELECT inside a s...

Страница 2894: ...hat declaring stored functions to be DETERMINISTIC or setting the log_bin_trust_function_creators 463 system variable to 0 will not allow random valued operations to be invoked In addition time based actions cannot be reproduced on a slave because the timing of such actions in a stored procedure is not reproducible through the binary log used for replication It records only DML events and does not...

Страница 2895: ...fault triggers Not explicitly MySQL does have specific special behavior for some TIMESTAMP columns as well as for columns which are defined using AUTO_INCREMENT B 5 5 How are triggers managed in MySQL In MySQL 5 0 triggers can be created using the CREATE TRIGGER statement and dropped using DROP TRIGGER See Section 13 1 11 CREATE TRIGGER Syntax and Section 13 1 18 DROP TRIGGER Syntax for more about...

Страница 2896: ...vate on the slaves as well as the master For more information see Section 16 4 1 26 Replication and Triggers B 5 13 How are actions carried out through triggers on a master replicated to a slave First the triggers that exist on a master must be re created on the slave server Once this is done the replication flow works as any other standard DML statement that participates in replication For exampl...

Страница 2897: ...a view B 7 MySQL 5 0 FAQ INFORMATION_SCHEMA Questions B 7 1 2877 Where can I find documentation for the MySQL INFORMATION_SCHEMA database B 7 2 2877 Is there a discussion forum for INFORMATION_SCHEMA B 7 3 2877 Where can I find the ANSI SQL 2003 specification for INFORMATION_SCHEMA B 7 4 2878 What is the difference between the Oracle Data Dictionary and MySQL s INFORMATION_SCHEMA B 7 5 2878 Can I ...

Страница 2898: ... one major version to the next in each step This may seem more complicated but it will you save time and trouble if you encounter problems during the upgrade their origin will be easier to identify either by you or if you have a MySQL Enterprise subscription by MySQL support B 8 2 How has storage engine table type support changed in MySQL 5 0 from previous versions Storage engine support has chang...

Страница 2899: ...SL Concepts B 9 2 Does MySQL 5 0 have native support for SSL Most 5 0 binaries have support for SSL connections between the client and server See Section 6 3 6 Using SSL for Secure Connections You can also tunnel a connection using SSH if for example the client application does not support SSL connections For an example see Section 6 3 7 Connecting to MySQL Remotely from Windows with SSH B 9 3 Is ...

Страница 2900: ...y VMWare Parallels or Xen B 10 13 2885 I am trying to populate a MySQL Cluster database The loading process terminates prematurely and I get an error message like this one ERROR 1114 The table my_cluster_table is full Why is this happening B 10 14 2886 MySQL Cluster uses TCP IP Does this mean that I can run it over the Internet with one or more nodes in remote locations B 10 15 2886 Do I have to l...

Страница 2901: ...B RPM Downloads section of the MySQL 5 0 Downloads page for these Prior to 5 0 4 you had to use the max binaries supplied as tar gz archives This is still possible but is not required so you can use your Linux distribution s RPM manager if you prefer You can also obtain NDB support by compiling MySQL from source but it is not necessary to do so simply to use MySQL Cluster To download the latest bi...

Страница 2902: ...ormation about SCI B 10 5 How many computers do I need to run a MySQL Cluster and why A minimum of three computers is required to run a viable cluster However the minimum recommended number of computers in a MySQL Cluster is four one each to run the management and SQL nodes and two computers to serve as data nodes The purpose of the two data nodes is to provide redundancy the management node must ...

Страница 2903: ...art of MySQL Cluster s internal architecture When a node acts as a master for any of these mechanisms it is usually the point of coordination for the activity and the other nodes act as servants carrying out their parts of the activity as directed by the master If the node acting as master fails then the remaining nodes elect a new master Tasks in progress that were being coordinated by the old ma...

Страница 2904: ...limit set for DataMemory However this will at best result in severely degraded performance and may cause the node to be dropped due to slow response time missed heartbeats We do not recommend on relying on disk swapping in a production environment for this reason In any case once the DataMemory limit is reached any operations requiring additional memory such as inserts will fail We have implemente...

Страница 2905: ...mputers we do not recommend their use with MySQL Cluster MySQL Cluster is implemented as a shared nothing solution the idea behind this is that the failure of a single piece of hardware should not cause the failure of multiple cluster nodes or possibly even the failure of the cluster as a whole For this reason the use of network shares or network file systems is not supported for MySQL Cluster Thi...

Страница 2906: ...recautions as you would with any other instance of the MySQL server For more information see Section 17 5 10 MySQL Cluster Security Issues B 10 15 Do I have to learn a new programming or query language to use MySQL Cluster No Although some specialized commands are used to manage and configure the cluster itself only standard My SQL statements are required for the following operations Creating alte...

Страница 2907: ...feguard mission critical data It also worth noting that the requirements for a cluster host running a management node are minimal This task can be accomplished with a 300 MHz Pentium or equivalent CPU and sufficient RAM for the operating system plus a small amount of overhead for the ndb_mgmd and ndb_mgm processes It is acceptable to run multiple cluster data nodes on a single host for learning ab...

Страница 2908: ...AQ the only other special requirement is that any tables to be included in the cluster must use the NDB storage engine This means that the tables must be created with ENGINE NDB or ENGINE NDBCLUSTER It is also possible to convert existing tables that use other storage engines to NDBCLUSTER using one or more ALTER TABLE statement However the definition of the table must be compatible with the NDBCL...

Страница 2909: ...le each record containing a VARCHAR 255 column will require space for 255 characters as required for the character set and collation being used for the table regardless of the actual number of characters stored therein This issue is fixed in MySQL 5 1 and later however we do not plan to backport this functionality to MySQL 5 0 See Section 17 1 5 Known Limitations of MySQL Cluster for more informat...

Страница 2910: ...ster release It is also possible to use software from different MySQL Cluster releases on different nodes However we support this only as part of a rolling upgrade procedure see Section 17 5 5 Performing a Rolling Restart of a MySQL Cluster B 10 32 Can I run two data nodes on a single host Two SQL nodes Yes it is possible to do this In the case of multiple data nodes it is advisable but not requir...

Страница 2911: ...me 23002 0 0 0 0 123080 3356 Ssl 14 14 0 00 ndb_mgmd me 23096 0 0 0 0 35876 2036 Ss 14 14 0 00 ndbd c 127 0 0 1 initial me 23097 1 0 2 4 524116 91096 Sl 14 14 0 00 ndbd c 127 0 0 1 initial me 23168 0 0 0 0 5284 812 pts 2 R 14 15 0 00 grep ndb The ndbd process showing 0 memory and CPU usage is the angel process It actually does use a very small amount of each of course It simply checks to see if th...

Страница 2912: ...issues in MySQL Questions and Answers B 11 1 What CJK character sets are available in MySQL The list of CJK character sets may vary depending on your MySQL version For example the eucjpms character set was not supported prior to MySQL 5 0 3 However since the name of the applicable language appears in the DESCRIPTION column for every entry in the INFORMATION_SCHEMA CHARACTER_SETS table you can obta...

Страница 2913: ...base is actually using the desired character set People often think that the client character set is always the same as either the server character set or the character set used for display purposes However both of these are false assumptions You can make sure by checking the result of SHOW CREATE TABLE tablename or better yet by using this statement SELECT character_set_name collation_name FROM i...

Страница 2914: ... Windows users find that a Microsoft character set such as cp932 for Japanese Windows is suitable If you cannot control the server settings and you have no idea what your underlying computer is then try changing to a common character set for the country that you re in euckr Korea gb2312 or gbk People s Republic of China big5 Taiwan sjis ujis cp932 or eucjpms Japan ucs2 or utf8 anywhere Usually it ...

Страница 2915: ...at is the last 4 columns provide the hexadecimal result when we use CONVERT ucs2 948 or we assign a ucs2 column containing the value to an sjis cp932 ujis or eucjpms column Character Name ucs2 sjis cp932 ujis eucjpms BROKEN BAR 00A6 3F 3F 8FA2C3 3F FULLWIDTH BROKEN BAR FFE4 3F FA55 3F 8FA2 YEN SIGN 00A5 3F 3F 20 3F FULLWIDTH YEN SIGN FFE5 818F 818F A1EF 3F TILDE 007E 7E 7E 7E 7E OVERLINE 203E 3F 3...

Страница 2916: ...e Yen sign as at least one other major DBMS does This is one possible solution to the Yen sign issue however this will not happen in MySQL 5 1 or 6 0 B 11 8 Of what issues should I be aware when working with Korean character sets in MySQL In theory while there have been several versions of the euckr Extended Unix Code Korea character set only one problem has been noted We use the ASCII variant of ...

Страница 2917: ... then the trouble may be that your application interface requires initialization Use mysql to tell you what character set or sets it uses with the statement SHOW VARIABLES LIKE char If you are using Access then you are most likely connecting with Connector ODBC In this case you should check Section 20 1 4 Configuring Connector ODBC If for instance you use big5 you would enter SET NAMES big5 Note t...

Страница 2918: ...wants to use The server uses the name to set the character_set_client 441 character_set_results 443 and character_set_connection 442 system variables In effect the server performs a SET NAMES operation using the character set name The effect of this is that you cannot control the client character set by starting mysqld with character set server utf8 403 However some of our Asian customers have sai...

Страница 2919: ...s one byte but ペ requires three bytes as shown here OCTET_LENGTH _utf8 A OCTET_LENGTH _utf8 ペ 1 3 1 row in set 0 00 sec If we don t know where the first character ends then we don t know where the second character begins in which case even very simple searches such as LIKE _A 896 fail The solution is to use a regular CJK character set in the first place or to convert to a CJK character set before ...

Страница 2920: ...any single ucs2 character or it can be the code point value hexadecimal representation of that character For example from Unicode s list of ucs2 encodings and names http www unicode org Public UNIDATA UnicodeData txt we know that the Katakana character Pe appears in all CJK character sets and that its code point value is 0x30da If we use this value as the argument to p_convert the result is as sho...

Страница 2921: ...cial Unicode names following the mark tell us the Japanese syllabary Hiragana the informal classification letter digit or punctuation mark and the Western identifier KA or GA which happen to be voiced and unvoiced components of the same letter pair More importantly the primary weight the first hexadecimal number inside the square brackets is 1E57 on both lines For comparisons in both searching and...

Страница 2922: ... as not a bug With utf8 we must truncate an input string when we encounter bytes that we don t understand Otherwise we wouldn t know how long the bad multi byte character is One possible workaround is to use ucs2 instead of utf8 in which case the bad characters are changed to question marks however no truncation takes place You can also change the data type to BLOB or BINARY which perform no valid...

Страница 2923: ...following areas of the Manual Section 20 6 13 Common Questions and Problems When Using the C API Section 20 7 12 Common Problems with MySQL and PHP Section 20 1 7 Connector ODBC Notes and Tips Section 20 2 5 Connector Net Programming Section 20 3 MySQL Connector J B 13 MySQL 5 0 FAQ Replication In the following section we provide answers to questions that are most frequently asked about MySQL Repl...

Страница 2924: ...y master and slave to enable replication Yes networking must be enabled on the master and slave If networking is not enabled the slave cannot connect to the master and transfer the binary log Check that the skip networking 421 option has not been enabled in the configuration file for either server B 13 3 How do I know how late a slave is compared to the master In other words how do I know the date...

Страница 2925: ... difference is that there is a little less lock contention because the updates originating on another server are serialized in one slave thread Even this benefit might be offset by network delays B 13 6 How can I use replication to improve performance of my system Set up one server as the master and direct all writes to it Then configure as many slaves as you have the budget and rackspace for and ...

Страница 2926: ...etwork bandwidth and neglect several other factors that could be significant on your system In many cases you may not be able to perform a computation similar to the one just shown that accurately predicts what will happen on your system if you add N replication slaves However answering the following questions should help you decide whether and by how much replication will improve the performance ...

Страница 2927: ...ion Slaves automatically know which format to use B 13 12 How do I prevent GRANT and REVOKE statements from replicating to slave machines Start the server with the replicate wild ignore table mysql 1460 option to ignore replication for tables in the mysql database B 13 13 Does replication work on mixed operating systems for example the master runs on Linux while slaves run on Mac OS X and Windows ...

Страница 2928: ...2908 ...

Страница 2929: ...cribed in Section C 2 Types of Error Values These errors are returned from the server side see Section C 3 Server Error Codes and Messages Errors can occur on the client side usually involving problems communicating with the server see Section C 4 Client Error Codes and Messages SQL statement warning and error information is available through the SHOW WARNINGS and SHOW ERRORS statements The warnin...

Страница 2930: ... and Messages MySQL programs have access to several types of error information when the server returns an error For example the mysql client program displays errors using the following format shell SELECT FROM no_such_table ERROR 1146 42S02 Table test no_such_table doesn t exist The message displayed contains three types of information A numeric error code 1146 This number is MySQL specific and is...

Страница 2931: ...FILE 2911 Message Can t create file s errno d Error 1005 SQLSTATE HY000 ER_CANT_CREATE_TABLE 2911 Message Can t create table s errno d Error 1006 SQLSTATE HY000 ER_CANT_CREATE_DB 2911 Message Can t create database s errno d Error 1007 SQLSTATE HY000 ER_DB_CREATE_EXISTS 2911 Message Can t create database s database exists Error 1008 SQLSTATE HY000 ER_DB_DROP_EXISTS 2911 Message Can t drop database ...

Страница 2932: ... in table s Error 1021 SQLSTATE HY000 ER_DISK_FULL 2912 Message Disk full s waiting for someone to free some space Error 1022 SQLSTATE 23000 ER_DUP_KEY 2912 Message Can t write duplicate key in table s Error 1023 SQLSTATE HY000 ER_ERROR_ON_CLOSE 2912 Message Error on close of s errno d Error 1024 SQLSTATE HY000 ER_ERROR_ON_READ 2912 Message Error reading file s errno d Error 1025 SQLSTATE HY000 ER...

Страница 2933: ...SQLSTATE HY001 ER_OUT_OF_SORTMEMORY 2913 Message Out of sort memory increase server sort buffer size Error 1039 SQLSTATE HY000 ER_UNEXPECTED_EOF 2913 Message Unexpected EOF found when reading file s errno d Error 1040 SQLSTATE 08004 ER_CON_COUNT_ERROR 2913 Message Too many connections Error 1041 SQLSTATE HY000 ER_OUT_OF_RESOURCES 2913 Message Out of memory check if mysqld or some other process use...

Страница 2934: ... 2914 Message Server shutdown in progress Error 1054 SQLSTATE 42S22 ER_BAD_FIELD_ERROR 2914 Message Unknown column s in s Error 1055 SQLSTATE 42000 ER_WRONG_FIELD_WITH_GROUP 2914 Message s isn t in GROUP BY Error 1056 SQLSTATE 42000 ER_WRONG_GROUP_FIELD 2914 Message Can t group on s Error 1057 SQLSTATE 42000 ER_WRONG_SUM_SELECT 2914 Message Statement has sum functions and columns in same statement...

Страница 2935: ...essage Too many keys specified max d keys allowed Error 1070 SQLSTATE 42000 ER_TOO_MANY_KEY_PARTS 2915 Message Too many key parts specified max d parts allowed Error 1071 SQLSTATE 42000 ER_TOO_LONG_KEY 2915 Message Specified key was too long max key length is d bytes Error 1072 SQLSTATE 42000 ER_KEY_COLUMN_DOES_NOT_EXITS 2915 Message Key column s doesn t exist in table Error 1073 SQLSTATE 42000 ER...

Страница 2936: ...ed by Error 1085 SQLSTATE HY000 ER_TEXTFILE_NOT_READABLE 2916 Message The file s must be in the database directory or be readable by all Error 1086 SQLSTATE HY000 ER_FILE_EXISTS_ERROR 2916 Message File s already exists Error 1087 SQLSTATE HY000 ER_LOAD_INFO 2916 Message Records ld Deleted ld Skipped ld Warnings ld Error 1088 SQLSTATE HY000 ER_ALTER_INFO 2916 Message Records ld Duplicates ld Error ...

Страница 2937: ... s was not locked with LOCK TABLES Error 1101 SQLSTATE 42000 ER_BLOB_CANT_HAVE_DEFAULT 2917 Message BLOB TEXT column s can t have a default value Error 1102 SQLSTATE 42000 ER_WRONG_DB_NAME 2917 Message Incorrect database name s Error 1103 SQLSTATE 42000 ER_WRONG_TABLE_NAME 2917 Message Incorrect table name s Error 1104 SQLSTATE 42000 ER_TOO_BIG_SELECT 2917 Message The SELECT would examine more tha...

Страница 2938: ... a join Error 1117 SQLSTATE HY000 ER_TOO_MANY_FIELDS 2918 Message Too many columns Error 1118 SQLSTATE 42000 ER_TOO_BIG_ROWSIZE 2918 Message Row size too large The maximum row size for the used table type not counting BLOBs is ld You have to change some columns to TEXT or BLOBs Error 1119 SQLSTATE HY000 ER_STACK_OVERRUN 2918 Message Thread stack overrun Used ld of a ld stack Use mysqld O thread_st...

Страница 2939: ... change passwords Error 1132 SQLSTATE 42000 ER_PASSWORD_NOT_ALLOWED 2919 Message You must have privileges to update tables in the mysql database to be able to change passwords for others Error 1133 SQLSTATE 42000 ER_PASSWORD_NO_MATCH 2919 Message Can t find any matching row in the user table Error 1134 SQLSTATE HY000 ER_UPDATE_INFO 2919 Message Rows matched ld Changed ld Warnings ld Error 1135 SQL...

Страница 2940: ...SQLSTATE 42000 ER_NONEXISTING_TABLE_GRANT 2920 Message There is no such grant defined for user s on host s on table s Error 1148 SQLSTATE 42000 ER_NOT_ALLOWED_COMMAND 2920 Message The used command is not allowed with this MySQL version Error 1149 SQLSTATE 42000 ER_SYNTAX_ERROR 2920 Message You have an error in your SQL syntax check the manual that corresponds to your MySQL server version for the r...

Страница 2941: ...n t support BLOB TEXT columns Error 1164 SQLSTATE 42000 ER_TABLE_CANT_HANDLE_AUTO_INCREMENT 2921 Message The used table type doesn t support AUTO_INCREMENT columns Error 1165 SQLSTATE HY000 ER_DELAYED_INSERT_TABLE_LOCKED 2921 Message INSERT DELAYED can t be used with table s because it is locked with LOCK TABLES Error 1166 SQLSTATE 42000 ER_WRONG_COLUMN_NAME 2921 Message Incorrect column name s Er...

Страница 2942: ...he table doesn t support s Error 1179 SQLSTATE 25000 ER_CANT_DO_THIS_DURING_AN_TRANSACTION 2922 Message You are not allowed to execute this command in a transaction Error 1180 SQLSTATE HY000 ER_ERROR_DURING_COMMIT 2922 Message Got error d during COMMIT Error 1181 SQLSTATE HY000 ER_ERROR_DURING_ROLLBACK 2922 Message Got error d during ROLLBACK Error 1182 SQLSTATE HY000 ER_ERROR_DURING_FLUSH_LOGS 29...

Страница 2943: ...tomatic repair failed Error 1196 SQLSTATE HY000 ER_WARNING_NOT_COMPLETE_ROLLBACK 2923 Message Some non transactional changed tables couldn t be rolled back Error 1197 SQLSTATE HY000 ER_TRANS_CACHE_FULL 2923 Message Multi statement transaction required more than max_binlog_cache_size bytes of storage increase this mysqld variable and try again Error 1198 SQLSTATE HY000 ER_SLAVE_MUST_STOP 2923 Messa...

Страница 2944: ... 1210 SQLSTATE HY000 ER_WRONG_ARGUMENTS 2924 Message Incorrect arguments to s Error 1211 SQLSTATE 42000 ER_NO_PERMISSION_TO_CREATE_USER 2924 Message s s is not allowed to create new users Error 1212 SQLSTATE HY000 ER_UNION_TABLES_IN_DIFFERENT_DIR 2924 Message Incorrect table definition all MERGE tables must be in the same database Error 1213 SQLSTATE 40001 ER_LOCK_DEADLOCK 2924 Message Deadlock fo...

Страница 2945: ..._REACHED 2925 Message User s has exceeded the s resource current value ld Error 1227 SQLSTATE 42000 ER_SPECIFIC_ACCESS_DENIED_ERROR 2925 Message Access denied you need the s privilege for this operation Error 1228 SQLSTATE HY000 ER_LOCAL_VARIABLE 2925 Message Variable s is a SESSION variable and can t be used with SET GLOBAL Error 1229 SQLSTATE HY000 ER_GLOBAL_VARIABLE 2925 Message Variable s is a...

Страница 2946: ...mn s Error 1242 SQLSTATE 21000 ER_SUBQUERY_NO_1_ROW 2926 Message Subquery returns more than 1 row Error 1243 SQLSTATE HY000 ER_UNKNOWN_STMT_HANDLER 2926 Message Unknown prepared statement handler s given to s Error 1244 SQLSTATE HY000 ER_CORRUPT_HELP_DB 2926 Message Help database is corrupt or does not exist Error 1245 SQLSTATE HY000 ER_CYCLIC_REFERENCE 2926 Message Cyclic reference on subqueries ...

Страница 2947: ...rror 1258 SQLSTATE HY000 ER_ZLIB_Z_BUF_ERROR 2927 Message ZLIB Not enough room in the output buffer probably length of uncompressed data was corrupted Error 1259 SQLSTATE HY000 ER_ZLIB_Z_DATA_ERROR 2927 Message ZLIB Input data corrupted Error 1260 SQLSTATE HY000 ER_CUT_VALUE_GROUP_CONCAT 2927 Message d line s were cut by GROUP_CONCAT Error 1261 SQLSTATE 01000 ER_WARN_TOO_FEW_RECORDS 2927 Message R...

Страница 2948: ...928 Message SSL parameters in CHANGE MASTER are ignored because this MySQL slave was compiled without SSL support they can be used later if MySQL slave with SSL is started Error 1275 SQLSTATE HY000 ER_SERVER_IS_IN_SECURE_AUTH_MODE 2928 Message Server is running in secure auth mode but s s has a password in the old format please change the password to the new format Error 1276 SQLSTATE HY000 ER_WAR...

Страница 2949: ...le s of the s is not updatable Error 1289 SQLSTATE HY000 ER_FEATURE_DISABLED 2929 Message The s feature is disabled you need MySQL built with s to have it working Error 1290 SQLSTATE HY000 ER_OPTION_PREVENTS_STATEMENT 2929 Message The MySQL server is running with the s option so it cannot execute this statement Error 1291 SQLSTATE HY000 ER_DUPLICATED_VALUE_IN_TYPE 2929 Message Column s has duplica...

Страница 2950: ..._RECURSIVE_CREATE 2930 Message Can t create a s from within another stored routine Error 1304 SQLSTATE 42000 ER_SP_ALREADY_EXISTS 2930 Message s s already exists Error 1305 SQLSTATE 42000 ER_SP_DOES_NOT_EXIST 2930 Message s s does not exist Error 1306 SQLSTATE HY000 ER_SP_DROP_FAILED 2930 Message Failed to DROP s s Error 1307 SQLSTATE HY000 ER_SP_STORE_FAILED 2930 Message Failed to CREATE s s Erro...

Страница 2951: ...arguments for s s expected u got u Error 1319 SQLSTATE 42000 ER_SP_COND_MISMATCH 2931 Message Undefined CONDITION s Error 1320 SQLSTATE 42000 ER_SP_NORETURN 2931 Message No RETURN found in FUNCTION s Error 1321 SQLSTATE 2F005 ER_SP_NORETURNEND 2931 Message FUNCTION s ended without RETURN Error 1322 SQLSTATE 42000 ER_SP_BAD_CURSOR_QUERY 2931 Message Cursor statement must be a SELECT Error 1323 SQLS...

Страница 2952: ... 1337 SQLSTATE 42000 ER_SP_VARCOND_AFTER_CURSHNDLR 2932 Message Variable or condition declaration after cursor or handler declaration Error 1338 SQLSTATE 42000 ER_SP_CURSOR_AFTER_HANDLER 2932 Message Cursor declaration after handler declaration Error 1339 SQLSTATE 20000 ER_SP_CASE_NOT_FOUND 2932 Message Case not found for CASE statement Error 1340 SQLSTATE HY000 ER_FPARSER_TOO_BIG_FILE 2932 Messag...

Страница 2953: ...1353 SQLSTATE HY000 ER_VIEW_WRONG_LIST 2933 Message View s SELECT and view s field list have different column counts Error 1354 SQLSTATE HY000 ER_WARN_VIEW_MERGE 2933 Message View merge algorithm can t be used here for now assumed undefined algorithm Error 1355 SQLSTATE HY000 ER_WARN_VIEW_WITHOUT_KEY 2933 Message View being updated does not have complete key of underlying table in it Error 1356 SQ...

Страница 2954: ...00 ER_VIEW_NONUPD_CHECK 2934 Message CHECK OPTION on non updatable view s s Error 1369 SQLSTATE HY000 ER_VIEW_CHECK_FAILED 2934 Message CHECK OPTION failed s s Error 1370 SQLSTATE 42000 ER_PROCACCESS_DENIED_ERROR 2934 Message s command denied to user s s for routine s Error 1371 SQLSTATE HY000 ER_RELAY_LOG_FAIL 2934 Message Failed purging old relay logs s Error 1372 SQLSTATE HY000 ER_PASSWD_LENGTH...

Страница 2955: ...PS_PROC 2935 Message Can t handle procedures with different groups yet Error 1385 SQLSTATE HY000 ER_NO_GROUP_FOR_PROC 2935 Message Select must have a group with this procedure Error 1386 SQLSTATE HY000 ER_ORDER_WITH_PROC 2935 Message Can t use ORDER clause with this procedure Error 1387 SQLSTATE HY000 ER_LOGGING_PROHIBIT_CHANGING_OF 2935 Message Binary logging and replication forbid changing the g...

Страница 2956: ...AER_OUTSIDE 2936 Message XAER_OUTSIDE Some work is done outside global transaction Error 1401 SQLSTATE XAE03 ER_XAER_RMERR 2936 Message XAER_RMERR Fatal error occurred in the transaction branch check your data for consistency Error 1402 SQLSTATE XA100 ER_XA_RBROLLBACK 2936 Message XA_RBROLLBACK Transaction branch was rolled back Error 1403 SQLSTATE 42000 ER_NONEXISTING_PROC_GRANT 2936 Message Ther...

Страница 2957: ...ATE HY000 ER_FAILED_ROUTINE_BREAK_BINLOG 2937 Message A routine failed and has neither NO SQL nor READS SQL DATA in its declaration and binary logging is enabled if non transactional tables were updated the binary log will miss their changes Error 1418 SQLSTATE HY000 ER_BINLOG_UNSAFE_ROUTINE 2937 Message This function has none of DETERMINISTIC NO SQL or READS SQL DATA in its declaration and binary...

Страница 2958: ...ng the query on the foreign data source Data source error s Error 1431 SQLSTATE HY000 ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST 2938 Message The foreign data source you are trying to reference does not exist Data source error s Error 1432 SQLSTATE HY000 ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE 2938 Message Can t create federated table The data source connection string s is not in the correct format Er...

Страница 2959: ...5 SQLSTATE HY000 ER_SP_CANT_SET_AUTOCOMMIT 2939 Message Not allowed to set autocommit from a stored function or trigger Error 1446 SQLSTATE HY000 ER_MALFORMED_DEFINER 2939 Message Definer is not fully qualified Error 1447 SQLSTATE HY000 ER_VIEW_FRM_NO_USER 2939 Message View s s has no definer information old table format Current user is used as definer Please recreate the view Error 1448 SQLSTATE ...

Страница 2960: ...TABLE s to fix it Error 1460 SQLSTATE 42000 ER_SP_NO_AGGREGATE 2940 Message AGGREGATE is not supported for stored functions Error 1461 SQLSTATE 42000 ER_MAX_PREPARED_STMT_COUNT_REACHED 2940 Message Can t create more than max_prepared_stmt_count statements current value lu Error 1462 SQLSTATE HY000 ER_VIEW_RECURSIVE 2940 Message s s contains view recursion Error 1463 SQLSTATE 42000 ER_NON_GROUPING_...

Страница 2961: ...ror 1477 SQLSTATE HY000 ER_LOG_PURGE_NO_FILE 2941 Message Being purged log s was not found Error 1478 SQLSTATE XA106 ER_XA_RBTIMEOUT 2941 Message XA_RBTIMEOUT Transaction branch was rolled back took too long Error 1479 SQLSTATE XA102 ER_XA_RBDEADLOCK 2941 Message XA_RBDEADLOCK Transaction branch was rolled back deadlock was detected Error 1480 SQLSTATE HY000 ER_TOO_MANY_CONCURRENT_TRXS 2941 Messag...

Страница 2962: ...ion d client version d Error 2008 CR_OUT_OF_MEMORY 2942 Message MySQL client ran out of memory Error 2009 CR_WRONG_HOST_INFO 2942 Message Wrong host info Error 2010 CR_LOCALHOST_CONNECTION 2942 Message Localhost via UNIX socket Error 2011 CR_TCP_CONNECTION 2942 Message s via TCP IP Error 2012 CR_SERVER_HANDSHAKE_ERR 2942 Message Error in server handshake Error 2013 CR_SERVER_LOST 2942 Message Lost...

Страница 2963: ...rror on SHOW SLAVE HOSTS Error 2024 CR_PROBE_SLAVE_CONNECT 2943 Message Error connecting to slave Error 2025 CR_PROBE_MASTER_CONNECT 2943 Message Error connecting to master Error 2026 CR_SSL_CONNECTION_ERROR 2943 Message SSL connection error Error 2027 CR_MALFORMED_PACKET 2943 Message Malformed packet Error 2028 CR_WRONG_LICENSE 2943 Message This client library is licensed only for use with MySQL ...

Страница 2964: ... shared memory server could not allocate file mapping lu Error 2041 CR_SHARED_MEMORY_CONNECT_MAP_ERROR 2944 Message Can t open shared memory server could not get pointer to file mapping lu Error 2042 CR_SHARED_MEMORY_FILE_MAP_ERROR 2944 Message Can t open shared memory client could not allocate file mapping lu Error 2043 CR_SHARED_MEMORY_MAP_ERROR 2944 Message Can t open shared memory client could...

Страница 2965: ...m or piece of equipment is causing it If you have one of the following symptoms then it is probably a hardware problems such as memory motherboard CPU or hard disk or kernel problem The keyboard does not work This can normally be checked by pressing the Caps Lock key If the Caps Lock light does not change you have to replace your keyboard Before doing this you should try to restart your computer a...

Страница 2966: ...the problem If a program fails it is always useful to know the following information Has the program in question made a segmentation fault did it dump core Is the program taking up all available CPU time Check with top Let the program run for a while it may simply be evaluating something computationally intensive If the mysqld server is causing problems can you get any response from it with mysqla...

Страница 2967: ...ket tmp mysql sock version Note the use of backticks rather than forward quotation marks with the hostname command these cause the output of hostname that is the current host name to be substituted into the mysqladmin command If you have no hostname command or are running on Windows you can manually type the host name of your machine without backticks following the h option You can also try h 127 ...

Страница 2968: ... server is listening to a different port If there is a MySQL server running and listening to the port you should get a response that includes the server s version number If you get an error such as telnet Unable to connect to remote host Connection refused then there is no server running on the given port If the server is running on the local host try using mysqladmin h localhost variables to conn...

Страница 2969: ...TEM CurrentControlSet Services Tcpip Parameters 3 On the Edit menu click Add Value and then add the following registry value Value Name MaxUserPort Data Type REG_DWORD Value 65534 This sets the number of ephemeral ports available to any user The valid range is between 5000 and 65534 decimal The default value is 0x1388 5000 decimal 4 On the Edit menu click Add Value and then add the following regis...

Страница 2970: ...t library If that is not possible use one of the following approaches To connect to the server with a pre 4 1 client program use an account that still has a pre 4 1 style password Reset the password to pre 4 1 style for each user that needs to use a pre 4 1 client program This can be done using the SET PASSWORD statement and the OLD_PASSWORD 956 function mysql SET PASSWORD FOR some_user some_host ...

Страница 2971: ...nection errors Unblock with mysqladmin flush hosts The value of the max_connect_errors 467 system variable determines how many successive interrupted connection requests are permitted See Section 5 1 4 Server System Variables After max_connect_errors 467 failed requests without a successful connection mysqld assumes that something is wrong for example that someone is trying to break in and blocks ...

Страница 2972: ...return so many rows If not correct the query and try again Otherwise you can invoke mysql with the quick 268 option This causes it to use the mysql_use_result C API function to retrieve the result set which places less of a load on the client but more on the server C 5 2 9 MySQL server has gone away This section also covers the related Lost connection to server during query error The most common r...

Страница 2973: ... to increase the maximum packet size on the client end More information on setting the packet size is given in Section C 5 2 10 Packet Too Large An INSERT or REPLACE statement that inserts a great many rows can also cause these sorts of errors Either one of these statements sends a single request to the server irrespective of the number of rows to be inserted thus you can often avoid the error by ...

Страница 2974: ...L 5 0 server or client is 1GB When a MySQL client or the mysqld server receives a packet bigger than max_allowed_packet 466 bytes it issues an ER_NET_PACKET_TOO_LARGE 2920 error and closes the connection With some clients you may also get a Lost connection to MySQL server during query error if the communication packet is too large Both the client and the server have their own max_allowed_packet 46...

Страница 2975: ...ended abruptly in the middle of a data transfer If a client is unable even to connect the server increments the Aborted_connects 523 status variable Unsuccessful connection attempts can occur for the following reasons A client does not have privileges to connect to a database A client uses an incorrect password A connection packet does not contain the right information It takes more than connect_t...

Страница 2976: ...r C temp The C temp directory must exist and have sufficient space for the MySQL server to write to See Section 4 2 3 3 Using Option Files Another cause of this error can be permissions issues Make sure that the MySQL server can write to the tmpdir 502 directory Check also the error code that you get with perror One reason the server cannot write to a table is that the file system is full shell pe...

Страница 2977: ...are case sensitive if they are located on a file system that has case sensitive file names Even for file systems that are not case sensitive such as on Windows all references to a given table within a query must use the same lettercase You can check which tables are in the default database with SHOW TABLES See Section 13 7 5 SHOW Syntax C 5 2 17 Can t initialize character set You might see an erro...

Страница 2978: ...248 option to mysqld_safe or set the open_files_limit 480 system variable See Section 5 1 4 Server System Variables The easiest way to set these values is to add an option to your option file See Section 4 2 3 3 Using Option Files If you have an old version of mysqld that does not support setting the open files limit you can edit the mysqld_safe script There is a commented out line ulimit n 256 in...

Страница 2979: ...21 Environment Variables C 5 4 Administration Related Issues C 5 4 1 How to Reset the Root Password If you have never set a root password for MySQL the server does not require a password at all for connecting as root However this is insecure For instructions on assigning passwords see Section 2 18 2 Securing the Initial MySQL Accounts If you know the root password but want to change it see Section...

Страница 2980: ...e 240 setting 7 After the server has started successfully delete C mysql init txt You should now be able to connect to the MySQL server as root using the new password Stop the MySQL server then restart it in normal mode again If you run the server as a service start it from the Windows Services window If you start the server manually use whatever command you normally use C 5 4 1 2 Resetting the Ro...

Страница 2981: ...unt password 6 After the server has started successfully delete home me mysql init You should now be able to connect to the MySQL server as root using the new password Stop the server and restart it normally C 5 4 1 3 Resetting the Root Password Generic Instructions The preceding sections provide password resetting instructions for Windows and Unix systems Alternatively on any platform you can set...

Страница 2982: ...it to die in the middle of an update Some external program is manipulating data files or index files at the same time as mysqld without locking the table properly You are running many mysqld servers using the same data directory on a system that does not support good file system locks normally handled by the lockd lock manager or you are running multiple servers with external locking disabled You ...

Страница 2983: ...n u root processlist usually is able to make a connection even in these cases and can provide useful information about the current number of connections and their status Run the command mysqladmin i 5 status or mysqladmin i 5 r status in a separate window to produce statistics while you run your other queries Try the following 1 Start mysqld from gdb or another debugger See MySQL Internals Porting...

Страница 2984: ...ntinue Exceptions to the preceding behavior are when you use REPAIR TABLE or OPTIMIZE TABLE or when the indexes are created in a batch after LOAD DATA INFILE or after an ALTER TABLE statement All of these statements may create large temporary files that if left to themselves would cause big problems for the rest of the system If the disk becomes full while MySQL is doing any of these operations it...

Страница 2985: ...the form SQL_ ALTER TABLE creates a temporary table in the same directory as the original table C 5 4 5 How to Protect or Change the MySQL Unix Socket File The default location for the Unix socket file that the server uses for communication with local clients is tmp mysql sock For some distribution formats the directory might be different such as var lib mysql for RPMs On some versions of Unix any...

Страница 2986: ...c characters comparisons will be case sensitive A comparison between a nonbinary string and binary string is treated as a comparison of binary strings Simple comparison operations sorting and grouping are based on each character s sort value Characters with the same sort value are treated as the same character For example if e and é have the same sort value in a given collation they compare as equ...

Страница 2987: ...LATION ENCRYPT x COLLATION SHA1 x COLLATION ENCRYPT x COLLATION SHA1 x binary binary C 5 5 2 Problems Using DATE Columns The format of a DATE value is YYYY MM DD According to standard SQL no other format is permitted You should use this format in UPDATE expressions and in the WHERE clause of SELECT statements For example SELECT FROM t1 WHERE date 2003 05 05 As a convenience MySQL automatically con...

Страница 2988: ...ng comparison It does not convert 20030505 to the date 2003 05 05 and perform a date comparison If you enable the ALLOW_INVALID_DATES 535 SQL mode MySQL permits you to store dates that are given only limited checking MySQL requires only that the day is in the range from 1 to 31 and the month is in the range from 1 to 12 This makes MySQL very convenient for Web applications where you obtain year mo...

Страница 2989: ...L values if you are using the MyISAM InnoDB or BDB or MEMORY storage engine Otherwise you must declare an indexed column NOT NULL and you cannot insert NULL into the column When reading data with LOAD DATA INFILE empty or missing columns are updated with To load a NULL value into a column use N in the data file The literal word NULL may also be used under some circumstances See Section 13 2 6 LOAD...

Страница 2990: ...e or more of the tables you used in the transaction do not support transactions Warning Some non transactional changed tables couldn t be rolled back These nontransactional tables are not affected by the ROLLBACK statement If you were not deliberately mixing transactional and nontransactional tables within the transaction the most likely cause for this message is that a table you thought was trans...

Страница 2991: ... figure out what is wrong create a minimal test that can be run with mysql test query sql that shows your problems You can create a test file by dumping the tables with mysqldump quick db_name tbl_name_1 tbl_name_n query sql Open the file in an editor remove some insert lines if there are more than needed to demonstrate the problem and add your SELECT statement at the end of the file Verify that t...

Страница 2992: ...because the difference between the numbers shows up around the tenth decimal or so depending on factors such as computer architecture or the compiler version or optimization level For example different CPUs may evaluate floating point numbers differently As of MySQL 5 0 3 you will get only the last row in the above result The problem cannot be solved by using ROUND 913 or similar functions because...

Страница 2993: ... ABS a b 0 0001 i a b 6 51 40 0 00 1 row in set 0 00 sec Conversely to get rows where the numbers are the same the test should find differences within the tolerance value mysql SELECT i SUM d1 AS a SUM d2 AS b FROM t1 GROUP BY i HAVING ABS a b 0 0001 i a b 1 21 40 21 40 2 76 80 76 80 3 7 40 7 40 4 15 40 15 40 5 7 20 7 20 Floating point values are subject to platform or implementation dependencies ...

Страница 2994: ...et a duplicate key error when using ALTER TABLE to change the character set or collation of a character column the cause is either that the new column collation maps two keys to the same value or that the table is corrupted In the latter case you should run REPAIR TABLE on the table If ALTER TABLE dies with the following error the problem may be that MySQL crashed during an earlier ALTER TABLE ope...

Страница 2995: ...wing problems are known Subquery optimization for IN is not as effective as for Even if you use lower_case_table_names 2 which enables MySQL to remember the case used for databases and table names MySQL does not remember the case used for database names for the function DATABASE 960 or within the various logs on case insensitive systems Dropping a FOREIGN KEY constraint does not work in replicatio...

Страница 2996: ...INSERT IGNORE SELECT if you have duplicate key values in the inserted data If and only if the preceding queries have no ORDER BY clause guaranteeing a deterministic order For example for INSERT SELECT with no ORDER BY the SELECT may return rows in a different order which results in a row having different ranks hence getting a different number in the AUTO_INCREMENT column depending on the choices m...

Страница 2997: ...9223372036854775807 for anything other than bit fields You can have up to 255 ENUM and SET columns in one table In MIN 971 MAX 971 and other aggregate functions MySQL currently compares ENUM and SET columns by their string value rather than by the string s relative position in the set mysqld_safe redirects all messages from mysqld to the mysqld log One problem with this is that if you execute mysq...

Страница 2998: ...s in the result If you execute a PROCEDURE on a query that returns an empty set in some cases the PROCEDURE does not transform the columns Creation of a table of type MERGE does not check whether the underlying tables are compatible types If you use ALTER TABLE to add a UNIQUE index to a table used in a MERGE table and then add a normal index on the MERGE table the key order is different for the t...

Страница 2999: ...these release notes documents MySQL 5 0 Release Notes includes MySQL Cluster release notes for MySQL 5 0 8 and up MySQL Cluster 5 0 Release Notes for MySQL Cluster before MySQL 5 0 8 MySQL Connector ODBC Release Notes MySQL Connector Net Release Notes includes MySQL Visual Studio Plugin release notes MySQL Connector J Release Notes MySQL Proxy Release Notes ...

Страница 3000: ...2980 ...

Страница 3001: ...fted beginning with MySQL 5 0 17 The locking statements LOCK TABLES and UNLOCK TABLES ALTER VIEW Before MySQL 5 0 46 this restriction is enforced only for stored functions LOAD DATA and LOAD TABLE SQL prepared statements PREPARE EXECUTE DEALLOCATE PREPARE Implication You cannot use dynamic SQL within stored routines where you construct dynamically statements as strings and then execute them This r...

Страница 3002: ...multiple times in a stored function under different aliases a Can t reopen table tbl_name error occurs even if the references occur in different statements within the function A stored function acquires table locks before executing to avoid inconsistency in the binary log due to mismatch of the order in which statements execute and when they appear in the log Statements that invoke a function are ...

Страница 3003: ... additional restrictions apply Triggers currently are not activated by foreign key actions The RETURN statement is not permitted in triggers which cannot return a value To exit a trigger immediately use the LEAVE statement Triggers are not permitted on tables in the mysql database The trigger cache does not detect when metadata of the underlying objects has changed If a trigger uses a table and th...

Страница 3004: ...correlated subquery SELECT FROM t1 WHERE t1 a IN SELECT b FROM t2 The optimizer rewrites the statement to a correlated subquery SELECT FROM t1 WHERE EXISTS SELECT 1 FROM t2 WHERE t2 b t1 a If the inner and outer queries return M and N rows respectively the execution time becomes on the order of O M N rather than O M N as it would be for an uncorrelated subquery An implication is that an IN subquer...

Страница 3005: ...or certain subquery operators mysql SELECT FROM t1 WHERE s1 IN SELECT s2 FROM t2 ORDER BY s1 LIMIT 1 ERROR 1235 42000 This version of MySQL doesn t yet support LIMIT IN ALL ANY SOME subquery The optimizer is more mature for joins than for subqueries so in many cases a statement that uses a subquery can be executed more efficiently if you rewrite it as a join An exception occurs for the case where ...

Страница 3006: ... algorithm by specifying ALGORITHM TEMPTABLE in the view definition You can use DROP TABLE or ALTER TABLE to drop or alter a table that is used in a view definition No warning results from the DROP or ALTER operation even though this invalidates the view Instead an error occurs later when the view is used CHECK TABLE can be used to check for views that have been invalidated by DROP or ALTER operat...

Страница 3007: ... VIEW 577 since MySQL doesn t grant it implicitly when views are created Views do not have indexes so index hints do not apply Use of index hints when selecting from a view is not permitted SHOW CREATE VIEW displays view definitions using an AS alias_name clause for each column If a column is created from an expression the default alias is the expression text which can be quite long As of MySQL 5 ...

Страница 3008: ... connection to be terminated and then rolls back the PREPARED XA transaction associated with it It should be possible to commit or roll back a PREPARED XA transaction but this cannot be done without changes to the binary logging mechanism E 6 Restrictions on Character Sets Identifiers are stored in mysql database tables user db and so forth using utf8 but identifiers can contain only characters in...

Страница 3009: ... a look at Andreas Jaeger s Large File Support in Linux page at http www suse de aj linux_lfs html If you do encounter a full table error there are several reasons why it might have occurred The disk might be full The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files This enables a table to exceed the maximum individual file size The tablespac...

Страница 3010: ... and IndexMemory configuration parameters in your config ini file See Section 17 3 3 1 MySQL Cluster Data Node Configuration Parameters You are using the MEMORY HEAP storage engine in this case you need to increase the value of the max_heap_table_size 468 system variable See Section 5 1 4 Server System Variables E 7 4 Limits on Table Column Count and Row Size There is a hard limit of 4096 columns ...

Страница 3011: ...lumns to TEXT or BLOBs The following statement to create table t3 fails because although the column length is within the maximum length of 65 535 bytes two additional bytes are required to record the length which causes the row size to exceed 65 535 bytes mysql CREATE TABLE t3 c1 VARCHAR 65535 NOT NULL ENGINE MyISAM CHARACTER SET latin1 ERROR 1118 42000 Row size too large The maximum row size for ...

Страница 3012: ...r example if a table contains these two columns they count as one not two toward this limit because the definitions are identical e1 ENUM a b c e2 ENUM a b c The sum of the length of element names in the unique ENUM and SET definitions counts toward the 64KB limit so although the theoretical limit on number of elements in a given ENUM column is 65 535 the practical limit is less than 3000 E 7 6 Wi...

Страница 3013: ...file level interface with a virtual interface in the future so that we can use the readfile writefile interface to get more speed The current implementation limits the number of open files that MySQL 5 0 can use to 2 048 which means that you cannot run as many concurrent threads on Windows as on Unix This problem is fixed in MySQL 5 5 Blocking read MySQL uses a blocking read for each connection Th...

Страница 3014: ...ch as the data file path name in LOAD DATA INFILE The path name separator character Path name components in Windows are separated by the character which is also the escape character in MySQL If you are using LOAD DATA INFILE or SELECT INTO OUTFILE use Unix style file names with characters mysql LOAD DATA INFILE C tmp skr txt INTO TABLE skr mysql SELECT INTO OUTFILE C tmp skr txt FROM skr Alternati...

Страница 3015: ...2 assignment 761 equal 875 greater than 876 greater than or equal 876 right shift 951 api MySQL Cluster 1602 computer MySQL Cluster 1604 mgm MySQL Cluster 1600 mysqld MySQL Cluster 1602 ndbd default MySQL Cluster 1594 ndbd MySQL Cluster 1594 ndb_mgmd MySQL Cluster 1600 sci MySQL Cluster 1604 shm MySQL Cluster 1604 tcp MySQL Cluster 1604 double quote 746 single quote 746 mysql client command 215 27...

Страница 3016: ... ALTER PROCEDURE 1013 ALTER SCHEMA 1012 ALTER TABLE 1013 1017 2974 ALTER VIEW 1020 altering database 1012 schema 1012 ANALYSE PROCEDURE 715 analyze option myisamchk 325 mysqlcheck 290 ANALYZE TABLE 1162 Analyzing thread state 734 AND bitwise 951 logical 880 angel pid file option mysqlmanager 355 anonymous user 138 139 585 588 ANSI mode running 20 ansi option mysqld 401 ANSI SQL mode 535 540 ANSI_Q...

Страница 3017: ... system variable 437 BaseExceptionInterceptor class 1943 batch mode 214 batch option mysql 265 batch SQL files 262 BatchByteSize 1583 BatchSize 1584 BatchSizePerLocalScan 1565 Bazaar tree 113 BDB storage engine 1215 1307 BDB tables 24 bdb home option mysqld 1309 bdb lock detect option mysqld 1309 bdb logdir option mysqld 1309 bdb no recover option mysqld 1310 bdb no sync option mysqld 1310 bdb sha...

Страница 3018: ... data types 2130 example programs 2132 functions 2139 linking problems 2133 C prepared statement API functions 2196 2197 type codes 2195 C 1856 1942 C Builder 1809 C compiler gcc 121 C compiler cannot create executables 124 C my cnf file 557 CACHE INDEX 1205 caches clearing 1205 calculating dates 205 calendar 934 CALL 1059 calling sequences for aggregate functions UDF 2813 calling sequences for si...

Страница 3019: ...tem variable 443 charset command mysql 272 charset option comp_err 254 CHARSET 958 CHAR_LENGTH 887 check option myisamchk 322 mysqlcheck 291 check options myisamchk 322 CHECK TABLE 1163 check only changed option myisamchk 323 mysqlcheck 291 check upgrade option mysqlcheck 291 checking tables for errors 634 Checking master version thread state 741 checking permissions thread state 734 checking priv...

Страница 3020: ...d MySQL Cluster 1669 CMake 91 COALESCE 878 COERCIBILITY 958 col option mysql_tableinfo 369 ColdFusion 1809 collating strings 808 collation adding 808 modifying 809 collation names 780 COLLATION 959 collation server option mysqld 403 collations naming conventions 780 COLLATIONS INFORMATION_SCHEMA table 1717 COLLATION_CHARACTER_SET_APPLICABILITY INFORMATION_SCHEMA table 1718 collation_connection sys...

Страница 3021: ...ion 255 out_file option 255 statefile option 255 version option 255 CONCAT 887 concatenation string 745 887 CONCAT_WS 888 concurrent inserts 710 712 concurrent_insert system variable 445 Conditions 1146 conditions 1182 1203 config file option mysqld_multi 251 my_print_defaults 372 ndb_config 1628 config file option ndb_mgmd 1624 config cache 123 config cache file 123 config ini MySQL Cluster 1537 ...

Страница 3022: ...s 997 contributing companies list of 38 contributors list of 32 control flow functions 882 CONV 909 conventions syntax 3 typographical 3 CONVERT 948 CONVERT TO 1018 converting HEAP to MyISAM thread state 734 CONVERT_TZ 918 ConvexHull 996 copy option mysqlaccess 340 copy to tmp table thread state 734 copying databases 158 copying tables 1039 1039 Copying to group table thread state 734 Copying to t...

Страница 3023: ...DIRECTORY and replication 1499 data node MySQL Cluster defined 1516 data nodes MySQL Cluster 1618 Data truncation with CJK characters 2891 data type BIGINT 827 BINARY 833 850 BIT 826 BLOB 833 851 BOOL 826 862 BOOLEAN 826 862 CHAR 831 848 CHAR VARYING 832 CHARACTER 831 CHARACTER VARYING 832 DATE 829 839 DATETIME 829 839 DEC 828 DECIMAL 827 1001 DOUBLE 828 DOUBLE PRECISION 829 ENUM 834 852 FIXED 828...

Страница 3024: ... datetime_format system variable 446 DATE_ADD 919 date_format system variable 446 DATE_FORMAT 921 DATE_SUB 919 922 DAY 922 DAYNAME 923 DAYOFMONTH 923 DAYOFWEEK 923 DAYOFYEAR 923 db option mysqlaccess 341 db table sorting 588 DB2 SQL mode 540 DBI interface 2805 DBI quote 747 DBI trace 2824 DBI DBD interface 2805 DBI_TRACE environment variable 188 2824 DBI_USER environment variable 188 DBUG package ...

Страница 3025: ...dump 300 delayed_insert_limit 1071 delayed_insert_limit system variable 447 delayed_insert_timeout system variable 448 delayed_queue_size system variable 448 delay_key_write system variable 447 DELETE 1060 and MySQL Cluster 1524 delete option mysqlimport 310 delete master logs option mysqldump 300 deleting database 1054 foreign key 1018 1043 function 1170 index 1016 1055 primary key 1016 rows 2971...

Страница 3026: ...P IF EXISTS and replication 1499 DROP DATABASE 1054 Drop DB thread command 732 DROP FOREIGN KEY 1018 1043 DROP FUNCTION 1056 1170 DROP INDEX 1016 1055 DROP PREPARE 1136 DROP PRIMARY KEY 1016 DROP PROCEDURE 1056 DROP SCHEMA 1054 DROP TABLE 1056 and MySQL Cluster 1524 DROP TRIGGER 1056 DROP USER 1150 DROP VIEW 1057 dropping user 600 1150 dryrun option mysqlhotcopy 353 DUAL 1083 dump option myisam_ft...

Страница 3027: ... directory checksum 165 handling for UDFs 2816 in subqueries 1105 known 2975 linking 2133 list of 2946 lost connection 2949 reporting 14 14 sources of information 2909 error_count session variable 450 ERROR_FOR_DIVISION_BY_ZERO SQL mode 536 ER_ABORTING_CONNECTION 2083 ER_ACCESS_DENIED_ERROR 2083 ER_BAD_FIELD_ERROR 2083 ER_BAD_HOST_ERROR 2083 ER_BAD_TABLE_ERROR 2083 ER_BLOBS_AND_NO_TERMINATED 2083 ...

Страница 3028: ... 2083 ER_TOO_BIG_ROWSIZE 2083 ER_TOO_BIG_SELECT 2083 ER_TOO_LONG_IDENT 2083 ER_TOO_LONG_KEY 2083 ER_TOO_LONG_STRING 2083 ER_TOO_MANY_KEYS 2083 ER_TOO_MANY_KEY_PARTS 2083 ER_TOO_MANY_ROWS 2083 ER_TOO_MANY_USER_CONNECTIONS 2083 ER_UNKNOWN_CHARACTER_SET 2083 ER_UNKNOWN_COM_ERROR 2083 ER_UNKNOWN_PROCEDURE 2083 ER_UNKNOWN_STORAGE_ENGINE 2083 ER_UNKNOWN_TABLE 2083 ER_UNSUPPORTED_EXTENSION 2083 ER_USER_L...

Страница 3029: ... 1633 EXTRACT 923 extracting dates 205 F failover Java clients 2055 FALSE 748 750 testing for 876 876 FAQs Connector ODBC 1804 fast option myisamchk 323 mysqlcheck 291 fatal signal 11 124 features of MySQL 6 FEDERATED storage engine 1215 1313 Fetch thread command 733 FETCH 1145 field changing 1016 Field List thread command 733 FIELD 888 fields option ndb_config 1630 fields enclosed by option mysql...

Страница 3030: ...ly asked questions about MySQL Cluster 2879 FROM 1083 FROM_DAYS 923 FROM_UNIXTIME 923 ft_boolean_syntax system variable 451 ft_max_word_len myisamchk variable 321 ft_max_word_len system variable 452 ft_min_word_len myisamchk variable 321 ft_min_word_len system variable 452 ft_query_expansion_limit system variable 453 ft_stopword_file myisamchk variable 321 ft_stopword_file system variable 453 full...

Страница 3031: ... the slave I O thread to update it thread state 742 Has sent all binlog to slave waiting for binlog to be updated thread state 741 have_archive system variable 454 have_bdb system variable 454 have_blackhole_engine system variable 454 have_community_features system variable 454 have_compress system variable 454 have_crypt system variable 454 have_csv system variable 454 have_example_engine system ...

Страница 3032: ..._config 1629 host table 589 sorting 588 Host SciId parameters 1590 host frm problems finding 130 HostName 1553 1556 1583 HostName MySQL Cluster 1685 hostname system variable 455 HostName1 1585 1588 1591 HostName2 1586 1588 1591 HOUR 924 howto option mysqlaccess 341 html option mysql 267 I i am a dummy option mysql 269 i5 OS 101 IBM i5 OS 101 icc and MySQL Cluster support 2821 MySQL builds 59 Id 15...

Страница 3033: ...1297 next key lock 1245 1264 1269 1270 NFS 1227 1297 page size 1276 1298 record level locks 1245 1264 1269 1270 secondary index 1276 Solaris 10 x86_64 issues 165 transaction isolation levels 1264 InnoDB buffer pool 702 innodb option mysqld 1236 InnoDB storage engine 1215 1226 InnoDB tables 24 innodb safe binlog option mysqld 409 innodb status file option mysqld 1236 INSERT 685 1065 insert thread s...

Страница 3034: ... code examples 2053 compatibility 2073 configuration properties 2054 driver for MySQL 2047 SQLState codes 2083 troubleshooting 2051 2116 versions supported 2047 join nested loop algorithm 669 JOIN 1089 join algorithm Block Nested Loop 666 Nested Loop 666 join option myisampack 335 join type ALL 648 const 646 eq_ref 646 fulltext 647 index 648 index_merge 647 index_subquery 647 range 647 ref 646 ref...

Страница 3035: ...mp 317 LENGTH 890 less than 876 less than or equal 876 libmysqlclient library 1734 libmysqld 2129 libmysqld library 1734 libmysqld libs option mysql_config 371 library libmysqlclient 1734 libmysqld 1734 libs option mysql_config 371 libs_r option mysql_config 371 license system variable 462 LIKE 896 and indexes 695 and wildcards 695 LIMIT 684 960 1085 and replication 1501 limitations design 640 MyS...

Страница 3036: ... mysqld 411 log queries not using indexes option mysqld 412 log short format option mysqld 412 log slave updates option mysqld 1451 log slow admin statements option mysqld 412 log slow queries option mysqld 412 log tc option mysqld 413 log tc size option mysqld 413 log warnings option mysqld 414 1452 LOG10 911 LOG2 911 LogDestination 1553 logging passwords 563 logging commands MySQL Cluster 1664 l...

Страница 3037: ...also mgmd managing MySQL Cluster 1653 managing MySQL Cluster processes 1618 manual available formats 2 online location 2 syntax conventions 3 typographical conventions 3 master connect retry option mysqld 1453 master data option mysqldump 302 master host option mysqld 1453 master info file option mysqld 1453 master password option mysqld 1453 master port option mysqld 1453 master retry count optio...

Страница 3038: ...MAX_USER_CONNECTIONS 600 max_user_connections system variable 472 max_write_lock_count system variable 473 MBR 996 MBRContains 996 MBRDisjoint 996 MBREqual 997 MBRIntersects 997 MBROverlaps 997 MBRTouches 997 MBRWithin 997 MD5 955 medium trust 1932 medium check option myisamchk 323 mysqlcheck 291 MEDIUMBLOB data type 833 MEDIUMINT data type 827 MEDIUMTEXT data type 833 memlock option mysqld 415 ME...

Страница 3039: ...elp option 321 HELP option 321 information option 323 keys used option 324 max record length option 324 medium check option 323 no symlinks option 324 options 320 parallel recover option 324 quick option 324 read only option 323 recover option 324 safe recover option 324 set auto increment option 325 set character set option 325 set collation option 325 silent option 321 sort index option 326 sort...

Страница 3040: ... safe updates option 269 secure auth option 269 show warnings option 269 sigint ignore option 269 silent option 269 skip column names option 269 skip line numbers option 270 socket option 270 source command 274 SSL options 270 status command 274 system command 274 table option 270 tee command 274 tee option 270 unbuffered option 270 use command 275 user option 270 verbose option 270 version option...

Страница 3041: ...8 1671 ndb_mgm 1539 1626 ndb_mgmd process 1623 ndb_size pl utility 2879 network configuration and security 1685 network transporters 1616 1617 networking 1587 1587 1589 networking requirements 2879 2879 node failure single user mode 1683 node identifiers 1588 1590 node logs 1663 node types 2879 NODERESTART Events 1667 nodes and node groups 1518 nodes and types 1516 number of computers required 287...

Страница 3042: ...ySQL privileges and MySQL Cluster 1689 mysql prompt command 275 MySQL server mysqld 244 377 mysql source command for reading from text files 215 279 MySQL source distribution 46 MySQL storage engines 1215 MySQL system tables and MySQL Cluster 1689 and replication 1504 MySQL Thread Pool 2833 MySQL version 50 mysql command for reading from text files 215 279 MySql Data class 1942 MySql Data dll libr...

Страница 3043: ...on 291 force option 291 help option 290 host option 291 medium check option 291 optimize option 292 password option 292 pipe option 292 port option 292 protocol option 292 quick option 292 repair option 292 silent option 292 socket option 292 SSL options 292 tables option 292 use frm option 293 user option 293 verbose option 293 version option 293 MySqlClient namespace 1942 MySqlCommand class 1857...

Страница 3044: ...ption 416 open files limit option 417 pid file option 417 port option 417 port open timeout option 418 read only option 1455 relay log option 1455 relay log index option 1455 relay log info file option 1456 relay log purge option 1456 relay log space limit option 1456 remove option 418 replicate do db option 1457 replicate do table option 1458 replicate ignore db option 1457 replicate ignore table...

Страница 3045: ... 301 help option 298 hex blob option 301 host option 301 ignore table option 301 insert ignore option 301 lines terminated by option 301 311 lock all tables option 301 lock tables option 301 log error option 301 master data option 302 no autocommit option 303 no create db option 303 no create info option 303 no data option 303 no set names option 303 opt option 303 order by primary option 303 pass...

Страница 3046: ...n 311 ignore option 311 ignore lines option 311 local option 311 lock tables option 311 low priority option 311 password option 311 pipe option 311 port option 311 protocol option 311 replace option 312 silent option 312 socket option 312 SSL options 312 user option 312 verbose option 312 version option 312 mysqlmanager 227 354 angel pid file option 355 bind address option 355 default mysqld path ...

Страница 3047: ...sql_fix_extensions 227 366 mysql_fix_privilege_tables 225 257 mysql_free_result 2157 mysql_get_character_set_info 2157 mysql_get_client_info 2158 mysql_get_client_version 2158 mysql_get_host_info 2158 mysql_get_proto_info 2158 mysql_get_server_info 2159 mysql_get_server_version 2159 mysql_get_ssl_cipher 2159 MYSQL_GROUP_SUFFIX environment variable 188 mysql_hex_string 2160 MYSQL_HISTFILE environme...

Страница 3048: ...ar option 368 clear only option 369 col option 369 help option 368 host option 369 idx option 369 password option 369 port option 369 prefix option 369 quiet option 369 socket option 369 tbl status option 369 user option 369 MYSQL_TCP_PORT environment variable 188 228 556 557 mysql_thread_end 2222 mysql_thread_id 2189 mysql_thread_init 2222 mysql_thread_safe 2222 MYSQL_TIME C type 2194 mysql_tzinf...

Страница 3049: ... option 1629 1629 rows option 1630 type option 1630 usage option 1628 version option 1628 ndb_cpcd 1618 1631 ndb_delete_all 1618 1631 transactional option 1632 ndb_desc 1618 1632 extra partition info option 1633 ndb_drop_index 1618 1633 ndb_drop_table 1618 1634 ndb_error_reporter 1618 1635 ndb_mgm 1618 1626 see mgm ndb_mgm MySQL Cluster management node client 1540 ndb_mgmd 1618 see mgmd mycnf opti...

Страница 3050: ...n_dist 256 no defaults option 240 mysqld_multi 251 mysqld_safe 248 my_print_defaults 373 no embedded option make_win_bin_dist 256 no log option mysqld_multi 252 no named commands option mysql 267 no nodeid checks option ndb_mgmd 1624 no pager option mysql 267 no set names option mysqldump 303 no symlinks option myisamchk 324 no tee option mysql 267 nodaemon option ndbd 1621 nodaemon option ndb_mgm...

Страница 3051: ...BC compatibility 493 754 829 871 877 1032 1091 ODBC NET 1794 offset option mysqlbinlog 345 OLAP 972 old style user limits option mysqld 416 OLD_PASSWORD 956 old_passwords system variable 480 old_server option mysqlaccess 341 ON DUPLICATE KEY UPDATE 1065 one database option mysql 267 one thread option mysqld 416 one_shot system variable 480 online location of manual 2 online upgrades and downgrades...

Страница 3052: ...37 page size InnoDB 1276 1298 page level locking 709 pager command mysql 274 pager option mysql 268 PAM authentication with Connector J 2082 parallel recover option myisamchk 324 parallelism option ndb_restore 1640 parameters server 718 parentheses and 874 parsable option ndb_show_tables 1646 partial trust 1932 partial updates and replication 1505 partitions MySQL Cluster 1518 passwd option mysqlm...

Страница 3053: ... 987 PolygonFromText 985 PolygonFromWKB 986 port option 231 mysql 268 mysqladmin 286 mysqlbinlog 346 mysqlcheck 292 mysqld 417 mysqldump 303 mysqld_safe 248 mysqlhotcopy 354 mysqlimport 311 mysqlmanager 357 mysqlshow 315 mysql_config 371 mysql_convert_table_format 365 mysql_setpermission 367 mysql_tableinfo 369 port system variable 482 port open timeout option mysqld 418 portability 640 types 862 ...

Страница 3054: ...upport 45 processes display 1188 processing arguments 2814 Processing events thread state 743 Processing events from schema table thread state 743 Processlist thread command 733 PROCESSLIST 1188 PROFILING INFORMATION_SCHEMA table 1721 profiling session variable 483 profiling_history_size session variable 483 program options MySQL Cluster 1650 program variables setting 240 program development utili...

Страница 3055: ...rver option mysqlbinlog 346 read only option myisamchk 323 mysqld 1455 Reading event from the relay log thread state 742 Reading from net thread state 737 Reading master dump table data thread state 743 read_buffer_size myisamchk variable 321 read_buffer_size system variable 488 read_only system variable 488 read_rnd_buffer_size system variable 489 REAL data type 829 REAL_AS_FLOAT SQL mode 539 Reb...

Страница 3056: ...option mysqlcheck 292 repair options myisamchk 323 REPAIR TABLE 1166 and replication 1168 1502 Repair with keycache thread state 737 repairing tables 635 REPEAT 1143 labels 1137 REPEAT 892 REPEATABLE READ transaction isolation level 1120 repertoire character set 787 replace 228 REPLACE 1081 replace option mysqlimport 312 replace utility 374 REPLACE 892 replicas MySQL Cluster 1518 replicate do db o...

Страница 3057: ... command 733 resetmaster option mysqlhotcopy 354 resetslave option mysqlhotcopy 354 resolveip 228 375 help option 375 silent option 375 version option 375 resolve_stack_dump 228 373 help option 373 numeric dump file option 373 symbols file option 373 version option 373 resource limits user accounts 472 600 1157 RESTART command MySQL Cluster restarting the server 130 RestartOnErrorInsert 1571 RESTO...

Страница 3058: ...read state 737 scale arithmetic 1001 numeric 825 schema altering 1012 creating 1020 deleting 1054 SCHEMA 964 SCHEMATA INFORMATION_SCHEMA table 1723 SCHEMA_PRIVILEGES INFORMATION_SCHEMA table 1723 SCI Scalable Coherent Interface see MySQL Cluster script files 214 scripts 245 250 mysql_install_db 132 SQL 262 searching and case sensitivity 2966 full text 934 MySQL Web pages 14 two keys 220 Searching ...

Страница 3059: ... session variables and replication 1507 SESSION_USER 964 SET 1170 CHARACTER SET 776 1172 NAMES 776 778 1172 ONE_SHOT 1172 size 861 SET data type 834 854 SET GLOBAL sql_slave_skip_counter 1131 Set option thread command 733 SET OPTION 1170 SET PASSWORD 1161 SET PASSWORD statement 602 SET sql_log_bin 1127 SET statement assignment operator 882 SET TRANSACTION 1119 set auto increment option myisamchk 3...

Страница 3060: ...SHOW TRIGGERS 1173 1200 SHOW VARIABLES 1173 used with MySQL Cluster 1683 SHOW WARNINGS 1173 1203 and MySQL Cluster 2879 SHOW with WHERE 1715 1729 show slave auth info option mysqld 1461 show table type option mysqlshow 315 show temp status option ndb_show_tables 1646 show warnings option mysql 269 showing database information 312 Shutdown thread command 733 SHUTDOWN command MySQL Cluster shutdown_...

Страница 3061: ...nd replication 1502 slow_launch_time system variable 492 SMALLINT data type 827 socket location changing 121 socket option 232 mysql 270 mysqladmin 287 mysqlbinlog 346 mysqlcheck 292 mysqld 422 mysqldump 305 mysqld_safe 248 mysqlhotcopy 354 mysqlimport 312 mysqlmanager 357 mysqlshow 315 mysql_config 372 mysql_convert_table_format 365 mysql_explain_log 366 mysql_setpermission 367 mysql_tableinfo 36...

Страница 3062: ...3 SQL_BUFFER_RESULT 1087 sql_buffer_result session variable 494 SQL_CACHE 706 1087 SQL_CALC_FOUND_ROWS 1087 sql_log_bin session variable 494 sql_log_off session variable 494 sql_log_update session variable 494 sql_mode system variable 495 sql_notes session variable 495 SQL_NO_CACHE 706 1087 sql_quote_show_create session variable 495 sql_safe_updates session variable 495 sql_select_limit system var...

Страница 3063: ...myisamchk variable 321 status tables 1198 status command mysql 274 results 284 STATUS command MySQL Cluster status option mysqlshow 315 status variables 516 1197 STD 971 STDDEV 972 STDDEV_POP 972 STDDEV_SAMP 972 STOP command MySQL Cluster STOP SLAVE 1132 stop datetime option mysqlbinlog 347 stop position option mysqlbinlog 347 StopOnError 1570 stopping the server 134 stopword list user defined 945...

Страница 3064: ...able 1472 sync_frm system variable 497 syntax regular expression 899 syntax conventions 3 SYSDATE 928 sysdate is now option mysqld 423 system privilege 574 security 559 system command mysql 274 System lock thread state 738 system optimization 718 system table optimizer 646 1087 system variable automatic_sp_privileges 437 auto_increment_increment 1446 auto_increment_offset 1449 back_log 437 basedir...

Страница 3065: ...lowed_packet 466 max_binlog_cache_size 1471 max_binlog_size 1472 max_connections 467 max_connect_errors 467 max_delayed_threads 468 max_error_count 468 max_heap_table_size 468 max_insert_delayed_threads 469 max_join_size 469 max_length_for_sort_data 470 max_prepared_stmt_count 470 max_relay_log_size 470 max_seeks_for_key 471 max_sort_length 471 max_sp_recursion_depth 472 max_tmp_tables 472 max_use...

Страница 3066: ...n_compile_machine 506 version_compile_os 506 wait_timeout 506 system variables 425 507 1202 and replication 1507 system_time_zone system variable 498 SYSTEM_USER 964 T tab t 746 1077 tab option mysqldump 305 tab option ndb_restore 1640 table changing 1013 1017 2974 deleting 1056 rebuilding 156 repair 156 row size 858 table aliases 1084 table cache 716 1906 table description myisamchk 326 Table Des...

Страница 3067: ...e 499 TAN 914 tar problems on Solaris 100 165 tar option make_win_src_distribution 256 tbl status option mysql_tableinfo 369 tc heuristic recover option mysqld 423 Tcl API 2806 tcp ip option mysqld_multi 252 TCP IP 80 85 tee command mysql 274 tee option mysql 270 temp pool option mysqld 423 temporary file write access 133 temporary files 2964 temporary tables and replication 1503 internal 717 prob...

Страница 3068: ...ntries 740 Killed 736 Killing slave 743 Locked 736 logging slow query 736 login 736 Making temp file 742 NULL 736 Opening master dump table 743 Opening mysql ndb_apply_status 743 Opening table 736 Opening tables 736 optimizing 736 preparing 736 Processing events 743 Processing events from schema table 743 Purging old relay logs 736 query end 736 Queueing master event to the relay log 742 Reading e...

Страница 3069: ...ime literals 748 time types 859 time zone problems 2966 time zone tables 260 time zones and replication 1506 leap seconds 820 support 816 upgrading 819 TIME 929 TimeBetweenGlobalCheckpoints 1573 TimeBetweenInactiveTransactionAbortCheck 1574 TimeBetweenLocalCheckpoints 1573 TimeBetweenWatchDogCheck 1571 TIMEDIFF 929 timed_mutexes system variable 501 timeout 445 965 1071 connect_timeout variable 271...

Страница 3070: ...ster 1524 TRUNCATE 914 tupscan option ndb_select_all 1644 tutorial 193 tx_isolation system variable 504 type codes C prepared statement API 2195 type conversions 871 875 type option mysql_convert_table_format 365 ndb_config 1630 ndb_show_tables 1646 types columns 825 861 data 825 date 859 Date and Time 838 numeric 859 of tables 1215 portability 861 string 860 strings 848 time 859 Types namespace 2...

Страница 3071: ...connection properties 2072 useHexFormat option ndb_select_all 1643 user accounts creating 1149 renaming 1160 resource limits 472 600 1157 USER environment variable 188 232 User lock thread state 738 user names and passwords 595 user option 232 mysql 270 mysql server 250 mysqlaccess 342 mysqladmin 287 mysqlbinlog 347 mysqlcheck 293 mysqld 424 mysqldump 306 mysqld_multi 252 mysqld_safe 248 mysqlhotc...

Страница 3072: ...config 372 mysql_convert_table_format 365 mysql_waitpid 370 my_print_defaults 373 ndb_config 1628 perror 374 resolveip 375 resolve_stack_dump 373 version option MySQL Cluster 1653 version system variable 505 VERSION 964 version_bdb system variable 505 version_comment system variable 505 version_compile_machine system variable 506 version_compile_os system variable 506 vertical option mysql 270 mys...

Страница 3073: ...849 WEEK 932 WEEKDAY 933 WEEKOFYEAR 933 Well Known Binary format 984 Well Known Text format 983 WHERE 655 with SHOW 1715 1729 where option mysqldump 306 WHILE 1143 labels 1137 widths display 825 Wildcard character 746 Wildcard character _ 746 wildcards and LIKE 695 in account names 584 in mysql columns_priv table 588 in mysql db table 588 in mysql host table 588 in mysql procs_priv table 588 in my...

Страница 3074: ...n identifiers 1122 xid XA transaction identifier 1122 xml option mysql 270 mysqldump 306 XOR bitwise 951 logical 881 Y Y 992 yaSSL 604 YEAR data type 830 841 YEAR 933 YEARWEEK 934 Yen sign Japanese 2891 Z ZEROFILL 825 834 2228 ZFS 1334 ...

Страница 3075: ...ysql_thread_init Section 20 6 5 C API Function Overview Section 20 6 3 2 Writing C API Threaded Client Programs mysql_create_db Section 20 6 6 8 mysql_create_db Section 20 6 5 C API Function Overview mysql_data_seek Section 20 6 6 9 mysql_data_seek Section 20 6 6 58 mysql_row_seek Section 20 6 6 71 mysql_use_result Section 20 6 5 C API Function Overview mysql_debug Section 20 6 6 10 mysql_debug Se...

Страница 3076: ...mt_result_metadata Section 20 6 6 69 mysql_store_result Section 20 6 5 C API Function Overview Section 20 6 13 1 Why mysql_store_result Sometimes Returns NULL After mysql_query Returns Success mysql_field_seek Section 20 6 6 17 mysql_fetch_field Section 20 6 6 23 mysql_field_seek Section 20 6 6 24 mysql_field_tell Section 20 6 10 22 mysql_stmt_result_metadata Section 20 6 4 C API Data Structures S...

Страница 3077: ...Get the Unique ID for the Last Inserted Row Section 12 13 Information Functions Section 5 1 4 Server System Variables Section 1 8 5 3 Transactions and Atomic Operations Section 3 6 9 Using AUTO_INCREMENT Section 20 6 13 2 What Results You Can Get from a Query mysql_kill Section 20 6 6 38 mysql_kill Section 20 6 6 70 mysql_thread_id Section 20 6 5 C API Function Overview Section 20 6 14 Controlling...

Страница 3078: ...vior mysql_query Section 13 2 1 CALL Syntax Section 20 6 6 1 mysql_affected_rows Section 20 6 6 8 mysql_create_db Section 20 6 6 11 mysql_drop_db Section 20 6 6 17 mysql_fetch_field Section 20 6 6 38 mysql_kill Section 20 6 6 46 mysql_next_result Section 20 6 6 51 mysql_query Section 20 6 6 52 mysql_real_connect Section 20 6 6 54 mysql_real_query Section 20 6 6 56 mysql_reload Section 20 6 6 63 my...

Страница 3079: ...ction Overview mysql_server_end Section 20 6 6 39 mysql_library_end Section 20 6 12 2 mysql_server_end Section 20 6 12 C API Embedded Server Function Descriptions Section 20 6 5 C API Function Overview mysql_server_init Section 20 6 11 1 my_init Section 20 6 6 40 mysql_library_init Section 20 6 12 1 mysql_server_init Section 20 6 11 3 mysql_thread_init Section 20 6 12 C API Embedded Server Functio...

Страница 3080: ...on 20 6 10 15 mysql_stmt_init Section 20 6 8 C API Prepared Statement Data Structures Section 20 6 9 C API Prepared Statement Function Overview mysql_stmt_data_seek Section 20 6 10 7 mysql_stmt_data_seek Section 20 6 10 23 mysql_stmt_row_seek Section 20 6 10 27 mysql_stmt_store_result Section 20 6 9 C API Prepared Statement Function Overview mysql_stmt_errno Section 20 6 10 8 mysql_stmt_errno Sect...

Страница 3081: ...mysql_stmt_field_count Section 20 6 10 20 mysql_stmt_prepare Section 20 6 10 21 mysql_stmt_reset Section 20 6 10 22 mysql_stmt_result_metadata Section 20 6 8 C API Prepared Statement Data Structures Section 20 6 9 C API Prepared Statement Function Overview Section 20 6 17 C API Prepared Statement Handling of Date and Time Values Section 13 5 SQL Syntax for Prepared Statements mysql_stmt_reset Sect...

Страница 3082: ...6 5 C API Function Overview Section 20 5 libmysqld the Embedded MySQL Server Library Section 20 6 3 2 Writing C API Threaded Client Programs mysql_thread_id Section 20 6 6 50 mysql_ping Section 20 6 6 70 mysql_thread_id Section 20 6 5 C API Function Overview Section 20 6 14 Controlling Automatic Reconnection Behavior mysql_thread_init Section 20 6 11 1 my_init Section 20 6 11 2 mysql_thread_end Se...

Страница 3083: ...ection 2 17 2 Installing MySQL from a Development Source Tree autorun sh Section 2 17 2 Installing MySQL from a Development Source Tree B index top 3063 bash Section 2 20 4 4 BSD OS Version 2 x Notes Section 2 20 4 5 BSD OS Version 3 x Notes Section 6 1 2 1 End User Guidelines for Password Security Section 2 11 Installing MySQL on Mac OS X Section 4 2 1 Invoking MySQL Programs Section 16 1 2 3 Rep...

Страница 3084: ...7 5 Compiling and Linking an Optimized mysqld Server Section 21 3 1 1 Compiling MySQL for Debugging Section 6 3 6 2 Configuring MySQL for SSL Section 2 17 4 Dealing with Problems Compiling MySQL Section 21 3 Debugging and Porting MySQL Section 17 4 20 Options Common to MySQL Cluster Programs Options Common to MySQL Cluster Programs Section 2 21 Environment Variables Section C 5 4 5 How to Protect ...

Страница 3085: ...t connect to local MySQL server Section 13 7 2 3 CHECK TABLE Syntax Section 14 1 1 MyISAM Startup Options Section 5 2 5 Server Log Maintenance Section 7 6 5 Setting Up a MyISAM Table Maintenance Schedule Section 3 5 Using mysql in Batch Mode csh Section 2 20 4 4 BSD OS Version 2 x Notes Section 2 20 4 5 BSD OS Version 3 x Notes Section 4 2 1 Invoking MySQL Programs Section 4 2 4 Setting Environmen...

Страница 3086: ... Crashing gmake Section 2 20 4 1 FreeBSD Notes Section 2 20 5 3 IBM AIX notes Section 2 17 2 Installing MySQL from a Development Source Tree Section 2 17 Installing MySQL from Source Section 2 20 5 9 SCO OpenServer 6 0 x Notes Section 2 20 5 10 SCO UnixWare 7 1 x and OpenUNIX 8 0 0 Notes GnuPG Section 2 6 2 Signature Checking Using GnuPG gnutar Section 2 16 Installing MySQL from Generic Binaries o...

Страница 3087: ...ter Data Node Daemon Section 17 5 5 Performing a Rolling Restart of a MySQL Cluster Section E 5 Restrictions on XA Transactions L index top 3063 ld Section 2 20 5 6 Alpha DEC OSF 1 Notes ld elf so 1 Section 21 2 2 5 Compiling and Installing User Defined Functions ld so Section 21 2 2 5 Compiling and Installing User Defined Functions ldconfig Section 21 2 2 5 Compiling and Installing User Defined F...

Страница 3088: ...ection 21 1 2 The MySQL Test Suite make_binary_distribution Section 4 1 Overview of MySQL Programs make_win_bin_dist Section 4 4 2 make_win_bin_dist Package MySQL Distribution as Zip Archive Section 2 10 8 3 Installing MySQL from a Source Build on Windows Section 4 1 Overview of MySQL Programs make_win_src_distribution Section 4 4 3 make_win_src_distribution Create Source Distribution for Windows ...

Страница 3089: ...stalling MySQL on NetWare Section E 7 3 Limits on Table Size Section 21 3 1 7 Making a Test Case If You Experience Table Corruption Section 4 6 3 5 Obtaining Table Information with myisamchk Section 4 6 3 4 Other myisamchk Options Section 8 3 3 Other Optimization Tips Section 4 1 Overview of MySQL Programs Section 14 1 4 2 Problems from Tables Not Being Closed Properly Section 5 1 3 Server Command...

Страница 3090: ...ction 18 1 Defining Stored Programs Section 17 4 3 ndb_mgm The MySQL Cluster Management Client Section 4 6 6 mysqlaccess Client for Checking Access Privileges Section 4 6 7 mysqlbinlog Utility for Processing Binary Log Files Section 4 5 4 mysqldump A Database Backup Program Section 4 5 6 mysqlshow Display Database Table and Column Information Section 4 4 2 make_win_bin_dist Package MySQL Distribut...

Страница 3091: ...gram Variables Section 21 3 1 6 Using Server Logs to Find Causes of Errors in mysqld Section 6 3 6 3 Using SSL Connections Section 4 5 1 6 3 Using the safe updates Option Section 2 10 7 Windows Postinstallation Procedures mysql Section 21 3 1 1 Compiling MySQL for Debugging mysql mysql mysql dump Section 2 19 2 1 Downgrading to MySQL 4 1 mysql stop Section 4 6 10 3 Starting the MySQL Server with M...

Страница 3092: ...etting Up Multiple Data Directories Section 2 18 1 Unix Postinstallation Procedures mysql_secure_installation Section 4 4 7 mysql_secure_installation Improve MySQL Installation Security Section 4 1 Overview of MySQL Programs Section 2 18 2 Securing the Initial MySQL Accounts mysql_setpermission Section 4 6 15 mysql_setpermission Interactively Set Permissions in Grant Tables Section 2 17 1 Installi...

Страница 3093: ...talling MySQL on NetWare Section 5 2 MySQL Server Logs Section 4 1 Overview of MySQL Programs Section 6 2 1 Privileges Provided by MySQL Section 5 3 3 Running Multiple MySQL Instances on Unix Section 2 18 2 Securing the Initial MySQL Accounts Section 2 10 4 7 Starting MySQL as a Windows Service Section 2 10 4 5 Starting MySQL from the Windows Command Line Section 5 1 10 The Shutdown Process Sectio...

Страница 3094: ...Client for Checking Access Privileges Section 1 7 How to Report Bugs or Problems Section 6 2 2 Privilege System Grant Tables Section 2 18 1 1 Problems Running mysql_install_db Section 5 1 3 Server Command Options Section 6 3 4 Setting Account Resource Limits Section 6 2 6 When Privilege Changes Take Effect mysqladmin reload version Section 1 7 How to Report Bugs or Problems mysqladmin shutdown Sec...

Страница 3095: ...s Section 4 4 9 mysql_upgrade Check Tables for MySQL Upgrade Section 4 1 Overview of MySQL Programs Section 2 19 4 Rebuilding or Repairing Tables or Indexes Section 5 1 4 Server System Variables Section 14 1 The MyISAM Storage Engine mysqld Section 4 6 3 2 myisamchk Check Options Section 4 6 3 1 myisamchk General Options Section 4 3 1 mysqld The MySQL Server Section 17 3 4 2 mysqld Command Options...

Страница 3096: ...or Message File Section 4 4 6 mysql_install_db Initialize MySQL Data Directory Section 4 3 3 mysql server MySQL Server Startup Script Section 4 3 4 mysqld_multi Manage Multiple MySQL Servers Section 4 3 2 mysqld_safe MySQL Server Startup Script Section 2 3 1 Enterprise Server Distribution Types Section 2 21 Environment Variables Section 14 5 6 Errors That May Occur When Using BDB Tables Section 8 ...

Страница 3097: ...ySQL Instances on One Machine Section 1 8 3 Running MySQL in ANSI Mode Section 2 20 5 8 SCO UNIX and OpenServer 5 0 x Notes Section 6 1 6 Security Issues with LOAD DATA LOCAL Section 6 1 4 Security Related mysqld Options and Variables Section 2 10 4 3 Selecting a MySQL Server Type Section 1 8 2 Selecting SQL Modes Section 10 1 3 1 Server Character Set and Collation Section 5 1 3 Server Command Opt...

Страница 3098: ...ction 4 3 4 mysqld_multi Manage Multiple MySQL Servers Section 4 6 10 mysqlmanager The MySQL Instance Manager Section 4 1 Overview of MySQL Programs Section 5 3 3 Running Multiple MySQL Instances on Unix mysqld_safe Section 4 3 2 mysqld_safe MySQL Server Startup Script Section C 5 2 18 File Not Found and Similar Errors Section 14 2 12 3 InnoDB General Troubleshooting Section 2 20 5 5 Alpha DEC UNI...

Страница 3099: ...kup Methods Section 14 2 10 3 Defragmenting a Table Section 17 4 14 ndb_restore Restore a MySQL Cluster Backup Section 4 6 1 innochecksum Offline InnoDB File Checksum Utility Section 2 19 2 Downgrading MySQL Section 2 19 2 1 Downgrading to MySQL 4 1 Section 7 4 3 Dumping Data in Delimited Text Format with mysqldump Section 7 4 1 Dumping Data in SQL Format with mysqldump Section 7 4 5 3 Dumping Sto...

Страница 3100: ...other Machine Section 7 2 Database Backup Methods Section 2 19 2 Downgrading MySQL Section 4 1 Overview of MySQL Programs Section 7 4 4 Reloading Delimited Text Format Backups Section 6 1 6 Security Issues with LOAD DATA LOCAL Section 2 19 1 2 Upgrading from MySQL 4 1 to 5 0 mysqlmanager Section 4 6 10 mysqlmanager The MySQL Instance Manager Section 4 6 10 4 Instance Manager User and Password Mana...

Страница 3101: ...e MySQL Cluster Management Client Section 17 3 2 5 Defining MySQL Cluster Data Nodes Section 17 4 2 ndb_mgmd The MySQL Cluster Management Server Daemon Section 17 4 14 ndb_restore Restore a MySQL Cluster Backup Section 17 5 6 Event Reports Generated in MySQL Cluster Section 17 2 3 Initial Startup of MySQL Cluster Section 17 2 1 1 Installing a MySQL Cluster Binary Release on Linux Section 17 2 1 2 ...

Страница 3102: ...mmon to MySQL Cluster Programs Options Common to MySQL Cluster Programs Section 17 4 11 ndb_print_backup_file Print NDB Backup File Contents Section 17 4 13 ndb_print_sys_file Print NDB System File Contents ndb_print_schema_file file_name Section 17 4 12 ndb_print_schema_file Print NDB Schema File Contents ndb_print_sys_file Section 17 4 13 ndb_print_sys_file Print NDB System File Contents Section...

Страница 3103: ...ent of MySQL Cluster Section 17 3 2 1 MySQL Cluster Configuration Basic Example Section 17 1 1 MySQL Cluster Core Concepts Section 17 2 MySQL Cluster Installation and Upgrades Section 17 3 5 2 MySQL Cluster Interconnects and Performance Section 17 1 2 MySQL Cluster Nodes Node Groups Replicas and Partitions Section 17 4 MySQL Cluster Programs Section 17 3 3 Overview of MySQL Cluster Configuration P...

Страница 3104: ...ecting to the MySQL Server ps xa grep mysqld Section C 5 2 2 Can t connect to local MySQL server R index top 3063 rename Section 5 2 5 Server Log Maintenance replace Section 1 8 5 5 as the Start of a Comment Section 4 8 2 replace A String Replacement Utility Section 4 7 1 msql2mysql Convert mSQL Programs for Use with MySQL Section 4 1 Overview of MySQL Programs Section 16 3 3 Using Replication for...

Страница 3105: ... MySQL Cluster Binary Release on Linux Section 2 16 Installing MySQL from Generic Binaries on Other Unix Like Systems sysctl Section 2 20 4 1 FreeBSD Notes T index top 3063 tar Section 16 3 1 2 Backing Up Raw Data from a Slave Section 7 1 Backup and Recovery Types Section 2 4 3 2 Choosing a Distribution Format Section 16 1 1 6 Creating a Data Snapshot Using Raw Data Files Section 3 3 Creating and ...

Страница 3106: ...a Standard Source Distribution Section 2 16 Installing MySQL from Generic Binaries on Other Unix Like Systems Section 2 12 Installing MySQL from RPM Packages on Linux usermod Section 2 12 Installing MySQL from RPM Packages on Linux V index top 3063 vi Section 4 5 1 2 mysql Commands Section 17 2 2 Initial Configuration of MySQL Cluster Section 3 3 4 7 Pattern Matching W index top 3063 WinDbg Sectio...

Страница 3107: ...ial Data Section 12 16 5 1 Geometry Format Conversion Functions ASCII Section 13 8 3 HELP Syntax Section 12 5 String Functions ASIN Section 12 6 2 Mathematical Functions AsText Section 12 16 4 5 Fetching Spatial Data Section 12 16 5 1 Geometry Format Conversion Functions AsWKB Section 12 16 5 1 Geometry Format Conversion Functions AsWKT Section 12 16 5 1 Geometry Format Conversion Functions ATAN S...

Страница 3108: ...4 1 to 5 0 Section 9 4 User Defined Variables CEIL Section 12 6 2 Mathematical Functions CEILING Section 12 6 2 Mathematical Functions Centroid Section 12 16 5 2 6 MultiPolygon Functions CHAR Section 12 10 Cast Functions and Operators Section 12 12 Encryption and Compression Functions Section 1 8 4 MySQL Extensions to Standard SQL Section 10 1 9 1 Result Strings Section 12 5 String Functions Secti...

Страница 3109: ...o Standard SQL Section C 5 5 3 Problems with NULL Values Section 5 1 7 Server SQL Modes Section 18 4 3 Updatable and Insertable Views Section 18 4 2 View Processing Algorithms CRC32 Section 12 6 2 Mathematical Functions Crosses Section 12 16 5 4 2 Functions That Test Spatial Relationships Between Geometries crypt Section 12 12 Encryption and Compression Functions Section 5 1 4 Server System Variab...

Страница 3110: ..._FORMAT Section 20 6 16 C API Prepared Statement Problems Section 12 7 Date and Time Functions Section 10 7 MySQL Server Locale Support Section 5 1 4 Server System Variables Section 2 19 1 2 Upgrading from MySQL 4 1 to 5 0 DATE_SUB Section 12 7 Date and Time Functions Section 11 1 5 Date and Time Types DATEDIFF Section 12 7 Date and Time Functions DAY Section 12 7 Date and Time Functions DAYNAME S...

Страница 3111: ...2 Comparison Functions and Operators ExteriorRing Section 12 16 5 2 5 Polygon Functions Section 12 16 5 3 1 Geometry Functions That Produce New Geometries EXTRACT Section 12 10 Cast Functions and Operators Section 12 7 Date and Time Functions F index top 3087 FIELD Section 12 5 String Functions FIND_IN_SET Section 12 5 String Functions Section 11 1 6 5 The SET Type FLOOR Section 12 6 1 Arithmetic ...

Страница 3112: ...vior Section 8 10 2 General Thread States Section 8 6 3 1 How the Query Cache Operates Section 8 7 1 Internal Locking Methods Section 12 14 Miscellaneous Functions Section 16 4 1 8 Replication and System Functions Section 13 3 5 3 Table Locking Restrictions and Conditions gethostbyaddr Section 8 9 8 DNS Lookup Optimization and the Host Cache gethostbyaddr_r Section 8 9 8 DNS Lookup Optimization an...

Страница 3113: ...Functions IsClosed Section 12 16 5 2 4 MultiLineString Functions IsEmpty Section 12 16 5 2 1 General Geometry Functions ISNULL Section 12 3 2 Comparison Functions and Operators IsRing Section 12 16 5 2 3 LineString Functions IsSimple Section 12 16 5 2 1 General Geometry Functions L index top 3087 LAST_DAY Section 12 7 Date and Time Functions LAST_INSERT_ID Section 13 1 10 CREATE TABLE Syntax Secti...

Страница 3114: ... How the Query Cache Operates Section 6 2 1 Privileges Provided by MySQL Section 16 4 1 8 Replication and System Functions Section 5 1 3 Server Command Options Section 5 1 4 Server System Variables Section 12 5 String Functions LOCALTIME Section 11 1 5 5 Automatic Initialization and Updating for TIMESTAMP Section 12 7 Date and Time Functions LOCALTIME Section 11 1 5 5 Automatic Initialization and ...

Страница 3115: ...Rectangles MBRs MBROverlaps Section 12 16 5 4 1 Relations on Geometry Minimal Bounding Rectangles MBRs MBRTouches Section 12 16 5 4 1 Relations on Geometry Minimal Bounding Rectangles MBRs MBRWithin Section 12 16 5 4 1 Relations on Geometry Minimal Bounding Rectangles MBRs Section 12 16 6 2 Using a Spatial Index MD5 Section 12 12 Encryption and Compression Functions Section 6 1 2 5 Implications of...

Страница 3116: ...ometry Values Using WKB Functions MultiPolygon Section 12 16 4 2 3 Creating Geometry Values Using MySQL Specific Functions MultiPolygonFromText Section 12 16 4 2 1 Creating Geometry Values Using WKT Functions MultiPolygonFromWKB Section 12 16 4 2 2 Creating Geometry Values Using WKB Functions N index top 3087 NAME_CONST Section 18 6 Binary Logging of Stored Programs Section 12 14 Miscellaneous Fun...

Страница 3117: ...er Names and Passwords PERIOD_ADD Section 12 7 Date and Time Functions Section 1 8 4 MySQL Extensions to Standard SQL PERIOD_DIFF Section 12 7 Date and Time Functions Section 1 8 4 MySQL Extensions to Standard SQL PI Section 9 2 3 Function Name Parsing and Resolution Section 12 6 2 Mathematical Functions POINT Section 12 16 3 1 Well Known Text WKT Format Point Section 12 16 4 2 3 Creating Geometry...

Страница 3118: ... 10 1 9 1 Result Strings Section 12 5 String Functions ROUND Section 12 6 2 Mathematical Functions Section 12 17 Precision Math Section 12 17 5 Precision Math Examples Section C 5 5 8 Problems with Floating Point Values Section 12 17 4 Rounding Behavior ROW_COUNT Section 13 2 1 CALL Syntax Section 13 2 2 DELETE Syntax Section 13 2 5 INSERT Syntax Section 20 6 6 1 mysql_affected_rows Section 12 13 ...

Страница 3119: ...ection 12 7 Date and Time Functions SUBSTR Section 12 5 String Functions SUBSTRING Section 10 1 9 1 Result Strings Section 6 3 8 SQL Based MySQL Account Activity Auditing Section 12 5 String Functions SUBSTRING_INDEX Section 12 5 String Functions SUBTIME Section 12 7 Date and Time Functions SUM Section 12 15 1 GROUP BY Aggregate Functions Section 21 2 2 Adding a New User Defined Function Section 1...

Страница 3120: ... Operators UNIX_TIMESTAMP Section 12 7 Date and Time Functions Section 8 6 3 1 How the Query Cache Operates Section C 5 4 6 Time Zone Problems UPPER Chapter 19 INFORMATION_SCHEMA Tables Section 12 10 Cast Functions and Operators Section 10 1 9 1 Result Strings Section 12 5 String Functions Section 10 1 8 String Repertoire USER Section 10 1 7 5 Collation of Expressions Section 8 6 3 1 How the Query...

Страница 3121: ...ation and System Functions Section 10 1 11 UTF 8 for Metadata W index top 3087 WEEK Section 12 7 Date and Time Functions Section 5 1 4 Server System Variables WEEKDAY Section 12 7 Date and Time Functions Section 1 8 4 MySQL Extensions to Standard SQL WEEKOFYEAR Section 12 7 Date and Time Functions Within Section 12 16 5 4 2 Functions That Test Spatial Relationships Between Geometries X index top 3...

Страница 3122: ...3102 ...

Страница 3123: ...g FOREIGN KEY Constraints INFORMATION_SCHEMA ROUTINES Chapter 19 INFORMATION_SCHEMA Tables Section 20 2 6 Connector Net Connection String Options Reference Section 19 8 The INFORMATION_SCHEMA ROUTINES Table INFORMATION_SCHEMA TABLES Chapter 19 INFORMATION_SCHEMA Tables INFORMATION_SCHEMA TRIGGERS Section 13 7 5 35 SHOW TRIGGERS Syntax Section 2 19 1 2 Upgrading from MySQL 4 1 to 5 0 INFORMATION_SC...

Страница 3124: ...PRIVILEGES Section 19 14 The INFORMATION_SCHEMA TABLE_PRIVILEGES Table TABLES Chapter 19 INFORMATION_SCHEMA Tables Section 4 6 16 mysql_tableinfo Generate Database Metadata Section 14 7 2 How to Use FEDERATED Tables Section 19 12 The INFORMATION_SCHEMA TABLES Table TRIGGERS Section 19 15 The INFORMATION_SCHEMA TRIGGERS Table Section 18 3 2 Trigger Metadata U index top 3103 USER_PRIVILEGES Section ...

Страница 3125: ... Subqueries with EXISTS Strategy R index top 3105 range Section 8 2 2 EXPLAIN Output Format Section 8 3 1 4 Index Merge Optimization Section 8 3 1 12 1 Loose Index Scan Section 8 3 1 8 Nested Loop Join Algorithms Section 8 3 1 3 Range Optimization Section 8 3 1 3 1 The Range Access Method for Single Part Indexes ref Section 8 2 2 EXPLAIN Output Format Section 14 3 1 MERGE Table Advantages and Disa...

Страница 3126: ...3106 ...

Страница 3127: ... Indexes Section 8 3 1 3 1 The Range Access Method for Single Part Indexes Section 8 2 2 EXPLAIN Output Format Section 12 3 2 Comparison Functions and Operators Section 8 5 3 How MySQL Uses Indexes Section 1 8 4 MySQL Extensions to Standard SQL Section 12 3 1 Operator Precedence Section 8 3 1 3 2 The Range Access Method for Multiple Part Indexes Section 8 3 1 3 1 The Range Access Method for Single...

Страница 3128: ...op 3107 AND Section 8 5 3 How MySQL Uses Indexes Section 8 3 1 4 Index Merge Optimization Section 12 3 3 Logical Operators Section 1 8 4 MySQL Extensions to Standard SQL Section 8 3 1 14 Optimizing Subqueries with EXISTS Strategy Section E 3 Restrictions on Subqueries Section 3 6 7 Searching on Two Keys Section 3 3 4 2 Selecting Particular Rows Section 12 5 1 String Comparison Functions Section 8 ...

Страница 3129: ... 1 14 Optimizing Subqueries with EXISTS Strategy Section C 5 5 3 Problems with NULL Values Section 5 1 4 Server System Variables Section 8 3 1 3 2 The Range Access Method for Multiple Part Indexes Section 8 3 1 3 1 The Range Access Method for Single Part Indexes Section 3 3 4 6 Working with NULL Values L index top 3107 LIKE Section 4 5 1 4 mysql Server Side Help Section 13 8 3 HELP Syntax Section ...

Страница 3130: ...13 7 1 3 GRANT Syntax Section 9 5 Expression Syntax Section 8 3 1 4 Index Merge Optimization Section 12 3 3 Logical Operators Section 1 8 4 MySQL Extensions to Standard SQL Section 12 3 1 Operator Precedence Section 8 3 1 14 Optimizing Subqueries with EXISTS Strategy Section 3 6 7 Searching on Two Keys Section 3 3 4 2 Selecting Particular Rows Section 5 1 7 Server SQL Modes Section 12 5 1 String C...

Страница 3131: ...pack Generate Compressed Read Only MyISAM Tables Section 4 6 12 mysql_explain_log Use EXPLAIN on Statements in Query Log Section 4 6 17 mysql_waitpid Kill Process and Wait for Its Termination Section 4 6 18 mysql_zap Kill Processes That Match a Pattern Section 4 6 6 mysqlaccess Client for Checking Access Privileges Section 4 6 7 mysqlbinlog Utility for Processing Binary Log Files Section 4 6 9 mys...

Страница 3132: ...urity Precautions allowold Section 4 6 9 mysqlhotcopy A Database Backup Program analyze Section 4 6 3 1 myisamchk General Options Section 7 6 4 MyISAM Table Optimization Section 4 5 3 mysqlcheck A Table Maintenance Program Section 4 6 3 4 Other myisamchk Options angel pid file Section 4 6 10 1 MySQL Instance Manager Command Options ansi Section 1 8 3 Running MySQL in ANSI Mode Section 5 1 3 Server...

Страница 3133: ... Options bdb lock detect Section 14 5 3 BDB Startup Options bdb logdir Section 14 5 3 BDB Startup Options Section 14 5 4 Characteristics of BDB Tables Section 5 3 Running Multiple MySQL Instances on One Machine Section 5 1 4 Server System Variables bdb no recover Section 14 5 3 BDB Startup Options Section 2 18 1 3 Starting and Troubleshooting the MySQL Server bdb no sync Section 14 5 3 BDB Startup...

Страница 3134: ...ksum Offline InnoDB File Checksum Utility Section 4 6 2 myisam_ftdump Display Full Text Index information Section 4 6 4 myisamlog Display MyISAM Log File Contents Section 4 5 2 mysqladmin Client for Administering a MySQL Server Section 4 5 3 mysqlcheck A Table Maintenance Program Section 4 5 4 mysqldump A Database Backup Program Section 4 5 5 mysqlimport A Data Import Program Section 4 7 3 my_prin...

Страница 3135: ...acter Set and Collation for Applications Section 16 4 1 2 Replication and Character Sets Section 10 1 3 1 Server Character Set and Collation Section 5 1 3 Server Command Options column names Section 4 5 1 1 mysql Options Section 4 2 3 2 Program Option Modifiers columns Section 4 5 5 mysqlimport A Data Import Program comments Section 4 5 1 1 mysql Options Section 4 5 4 mysqldump A Database Backup P...

Страница 3136: ... Display Full Text Index information Section 4 5 2 mysqladmin Client for Administering a MySQL Server Section 4 5 6 mysqlshow Display Database Table and Column Information create options Section 4 5 4 mysqldump A Database Backup Program D index top 3111 D Section 4 6 3 3 myisamchk Repair Options Section 4 5 1 1 mysql Options Section 20 6 3 1 Building C API Client Programs Section 17 4 15 ndb_selec...

Страница 3137: ...adir Section 2 10 4 2 Creating an Option File Section 2 18 1 2 Starting and Stopping MySQL Automatically Section 4 6 10 3 Starting the MySQL Server with MySQL Instance Manager Section 2 10 5 Troubleshooting a MySQL Installation Under Windows Section E 7 6 Windows Platform Limitations date Section 4 6 12 mysql_explain_log Use EXPLAIN on Statements in Query Log db Section 4 6 6 mysqlaccess Client fo...

Страница 3138: ...pport Section 16 4 1 24 Replication and Time Zones Section 5 1 3 Server Command Options Section 5 1 4 Server System Variables default key_buffer_size Section 5 1 5 1 Structured System Variables defaults extra file Section 4 2 3 4 Command Line Options that Affect Option File Handling Section 4 7 3 my_print_defaults Display Options from Option Files Section 4 3 4 mysqld_multi Manage Multiple MySQL S...

Страница 3139: ...or Windows disable Section 4 2 3 2 Program Option Modifiers disable auto rehash Section 4 5 1 1 mysql Options disable grant options Section 4 4 6 mysql_install_db Initialize MySQL Data Directory Section 2 17 3 MySQL Source Configuration Options Section 5 1 3 Server Command Options Section 5 1 4 Server System Variables disable keys Section 4 5 4 mysqldump A Database Backup Program disable log bin S...

Страница 3140: ...r Type Section 5 1 3 Server Command Options enable profiling Section 2 17 3 MySQL Source Configuration Options enable pstack Section 5 1 3 Server Command Options enable thread safe client Section 2 17 3 MySQL Source Configuration Options engine condition pushdown Section 17 1 4 1 MySQL Cluster Developement in MySQL 5 0 events Section 2 19 1 2 Upgrading from MySQL 4 1 to 5 0 example Section 4 3 4 m...

Страница 3141: ...5 Using a Stack Trace fast Section 4 6 3 2 myisamchk Check Options Section 4 5 3 mysqlcheck A Table Maintenance Program federated Section 14 7 The FEDERATED Storage Engine fields Section 17 4 4 ndb_config Extract MySQL Cluster Configuration Information fields enclosed by Section 17 4 14 ndb_restore Restore a MySQL Cluster Backup Section 4 5 4 mysqldump A Database Backup Program Section 4 5 5 mysql...

Страница 3142: ...b_error_reporter NDB Error Reporting Utility G index top 3111 G Section 4 5 1 1 mysql Options g Section 4 5 1 1 mysql Options Section 21 3 1 1 Compiling MySQL for Debugging Section 4 6 8 mysqldumpslow Summarize Slow Query Log Files Section 4 5 3 mysqlcheck A Table Maintenance Program Section 4 7 3 my_print_defaults Display Options from Option Files gci Section 17 4 15 ndb_select_all Print Rows fro...

Страница 3143: ...rivileges Section 4 6 7 mysqlbinlog Utility for Processing Binary Log Files Section 4 6 8 mysqldumpslow Summarize Slow Query Log Files Section 4 6 9 mysqlhotcopy A Database Backup Program Section 4 5 2 mysqladmin Client for Administering a MySQL Server Section 4 5 3 mysqlcheck A Table Maintenance Program Section 4 5 4 mysqldump A Database Backup Program Section 4 5 5 mysqlimport A Data Import Prog...

Страница 3144: ...3 1 Building C API Client Programs Section 4 6 4 myisamlog Display MyISAM Log File Contents Section 4 6 17 mysql_waitpid Kill Process and Wait for Its Termination Section 4 6 18 mysql_zap Kill Processes That Match a Pattern Section 4 8 1 perror Explain Error Codes Section 4 8 2 replace A String Replacement Utility Section 4 8 3 resolveip Resolve Host name to IP Address or Vice Versa i Section 4 6 ...

Страница 3145: ...uster Configuration Parameters Section 17 3 3 Overview of MySQL Cluster Configuration Parameters Section 17 5 5 Performing a Rolling Restart of a MySQL Cluster Section 17 5 1 Summary of MySQL Cluster Start Phases initial start Section 17 4 1 ndbd The MySQL Cluster Data Node Daemon innodb Section 14 2 2 InnoDB Startup Options and System Variables innodb safe binlog Section 16 4 1 13 Replication and...

Страница 3146: ...Client Programs Section 4 5 5 mysqlimport A Data Import Program Section 2 20 1 3 Linux Source Distribution Notes Section 2 22 3 Problems Using the Perl DBI DBD Interface Section 6 1 6 Security Issues with LOAD DATA LOCAL Section 10 2 Setting the Error Message Language Section 2 20 3 Solaris Notes l Section 4 6 3 3 myisamchk Repair Options Section 20 6 6 39 mysql_library_end Section 2 20 5 5 Alpha ...

Страница 3147: ...Table lock all tables Section 4 5 4 mysqldump A Database Backup Program lock tables Section 4 5 4 mysqldump A Database Backup Program Section 4 5 5 mysqlimport A Data Import Program log Section 4 3 4 mysqld_multi Manage Multiple MySQL Servers Section 4 6 10 1 MySQL Instance Manager Command Options Section 5 3 Running Multiple MySQL Instances on One Machine Section 5 1 3 Server Command Options Sect...

Страница 3148: ...ilover Section 5 2 3 The Binary Log log slow admin statements Section 5 1 3 Server Command Options Section 5 2 4 The Slow Query Log log slow queries Section 5 1 3 Server Command Options Section 5 2 5 Server Log Maintenance Section 5 1 4 Server System Variables Section 5 2 4 The Slow Query Log log tc Section 5 1 3 Server Command Options log tc size Section 5 1 3 Server Command Options Section 5 1 6...

Страница 3149: ...h Section 16 1 2 3 Replication Slave Options and Variables master ssl cert Section 16 1 2 3 Replication Slave Options and Variables master ssl cipher Section 16 1 2 3 Replication Slave Options and Variables master ssl key Section 16 1 2 3 Replication Slave Options and Variables master user Section 16 1 2 3 Replication Slave Options and Variables max Section 4 2 3 5 Using Options to Set Program Var...

Страница 3150: ...ger Command Options Section 4 6 10 3 Starting the MySQL Server with MySQL Instance Manager mysqld version Section 4 3 2 mysqld_safe MySQL Server Startup Script Section 2 19 1 2 Upgrading from MySQL 4 1 to 5 0 N index top 3111 N Section 4 5 1 1 mysql Options Section 4 5 4 mysqldump A Database Backup Program Section 4 4 1 comp_err Compile MySQL Error Message File n Section 4 6 3 3 myisamchk Repair O...

Страница 3151: ...new Section 4 2 3 3 Using Option Files nice Section 4 3 2 mysqld_safe MySQL Server Startup Script no auto rehash Section 4 5 1 1 mysql Options no autocommit Section 4 5 4 mysqldump A Database Backup Program no beep Section 4 5 1 1 mysql Options no contact Section 17 4 19 ndb_waiter Wait for MySQL Cluster to Reach a Given Status no create db Section 4 5 4 mysqldump A Database Backup Program no crea...

Страница 3152: ... Dump to Symbols O index top 3111 O Section 4 6 3 1 myisamchk General Options Section 2 20 5 6 Alpha DEC OSF 1 Notes Section 2 17 4 Dealing with Problems Compiling MySQL Section 4 6 7 mysqlbinlog Utility for Processing Binary Log Files Section 4 4 1 comp_err Compile MySQL Error Message File Section 2 20 5 1 HP UX Version 10 20 Notes Section 2 20 5 3 IBM AIX notes Section 5 1 3 Server Command Optio...

Страница 3153: ...g Binary Log Files Section 4 6 9 mysqlhotcopy A Database Backup Program Section 4 5 2 mysqladmin Client for Administering a MySQL Server Section 4 5 3 mysqlcheck A Table Maintenance Program Section 4 5 4 mysqldump A Database Backup Program Section 4 5 5 mysqlimport A Data Import Program Section 4 5 6 mysqlshow Display Database Table and Column Information Section 4 2 1 Invoking MySQL Programs Sect...

Страница 3154: ...Section 4 6 12 mysql_explain_log Use EXPLAIN on Statements in Query Log Section 4 6 15 mysql_setpermission Interactively Set Permissions in Grant Tables Section 4 6 16 mysql_tableinfo Generate Database Metadata Section 4 6 6 mysqlaccess Client for Checking Access Privileges Section 4 6 7 mysqlbinlog Utility for Processing Binary Log Files Section 4 6 9 mysqlhotcopy A Database Backup Program Sectio...

Страница 3155: ...nformation Section 4 7 2 mysql_config Display Options for Compiling Clients Section 4 3 2 mysqld_safe MySQL Server Startup Script Section 4 2 1 Invoking MySQL Programs Section 4 6 10 1 MySQL Instance Manager Command Options Section 2 17 3 MySQL Source Configuration Options Section 5 3 Running Multiple MySQL Instances on One Machine Section 5 3 3 Running Multiple MySQL Instances on Unix Section 5 1...

Страница 3156: ...tion Section 4 6 16 mysql_tableinfo Generate Database Metadata Section 4 6 9 mysqlhotcopy A Database Backup Program Section 4 5 3 mysqlcheck A Table Maintenance Program Section 4 5 4 mysqldump A Database Backup Program Section 2 20 5 3 IBM AIX notes query Section 17 4 4 ndb_config Extract MySQL Cluster Configuration Information query cache size Section 8 7 4 External Locking quick Section 4 6 3 6 ...

Страница 3157: ...rom Files Section 4 6 9 mysqlhotcopy A Database Backup Program relative Section 4 5 2 mysqladmin Client for Administering a MySQL Server relay log Section 13 4 2 1 CHANGE MASTER TO Syntax Section 16 3 5 Improving Replication Performance Section 16 1 1 9 Introducing Additional Slaves to an Existing Replication Environment Section 16 1 2 3 Replication Slave Options and Variables Section 16 2 2 1 The...

Страница 3158: ...ection 16 2 3 How Servers Evaluate Replication Filtering Rules Section 16 4 1 19 Replication and Reserved Words Section 16 2 3 3 Replication Rule Application Section 16 1 2 3 Replication Slave Options and Variables Section 5 2 3 The Binary Log replicate ignore table Section 13 7 5 31 SHOW SLAVE STATUS Syntax Section 16 2 3 2 Evaluation of Table Level Replication Options Section 16 4 1 19 Replicati...

Страница 3159: ...rows Extract SQL Statements from Files rpm Section 4 4 6 mysql_install_db Initialize MySQL Data Directory run as service Section 4 6 10 1 MySQL Instance Manager Command Options S index top 3111 S Section 4 5 1 2 mysql Commands Section 4 5 1 1 mysql Options Section 7 6 4 MyISAM Table Optimization Section 4 2 2 Connecting to the MySQL Server Section 4 6 12 mysql_explain_log Use EXPLAIN on Statements...

Страница 3160: ... file priv Section 2 17 1 Installing MySQL from a Standard Source Distribution Section 6 1 3 Making MySQL Secure Against Attackers Section 5 1 3 Server Command Options Section 5 1 4 Server System Variables Section 2 18 1 Unix Postinstallation Procedures select_limit Section 4 5 1 6 3 Using the safe updates Option server id Section 13 7 5 30 SHOW SLAVE HOSTS Syntax Section 16 1 2 Replication and Bi...

Страница 3161: ...Section 4 6 5 myisampack Generate Compressed Read Only MyISAM Tables Section 4 5 2 mysqladmin Client for Administering a MySQL Server Section 4 5 3 mysqlcheck A Table Maintenance Program Section 4 5 5 mysqlimport A Data Import Program Section 4 4 3 make_win_src_distribution Create Source Distribution for Windows Section 4 8 1 perror Explain Error Codes Section 4 8 3 resolveip Resolve Host name to ...

Страница 3162: ...SQL 4 1 Section 2 17 3 MySQL Source Configuration Options Section 2 18 1 1 Problems Running mysql_install_db Section C 5 4 1 3 Resetting the Root Password Generic Instructions Section 5 1 3 Server Command Options Section 4 2 3 1 Using Options on the Command Line Section 6 2 6 When Privilege Changes Take Effect skip host cache Section 6 2 7 Causes of Access Denied Errors Section 8 9 8 DNS Lookup Op...

Страница 3163: ...skip quote names Section 4 5 4 mysqldump A Database Backup Program skip reconnect Section 4 5 1 1 mysql Options Section 20 6 14 Controlling Automatic Reconnection Behavior Section 4 5 1 6 4 Disabling mysql Auto Reconnect skip routines Section 2 19 2 1 Downgrading to MySQL 4 1 Section 7 4 5 3 Dumping Stored Programs skip safemalloc Section 2 17 5 Compiling and Linking an Optimized mysqld Server Sec...

Страница 3164: ...Given Storage Engine Section 4 6 12 mysql_explain_log Use EXPLAIN on Statements in Query Log Section 4 6 15 mysql_setpermission Interactively Set Permissions in Grant Tables Section 4 6 16 mysql_tableinfo Generate Database Metadata Section 4 6 7 mysqlbinlog Utility for Processing Binary Log Files Section 4 6 9 mysqlhotcopy A Database Backup Program Section 4 5 2 mysqladmin Client for Administering...

Страница 3165: ...p A Database Backup Program Section 4 5 5 mysqlimport A Data Import Program Section 4 5 6 mysqlshow Display Database Table and Column Information Section 5 1 3 Server Command Options ssl ca Section 13 7 1 3 GRANT Syntax Section 16 1 2 3 Replication Slave Options and Variables Section 6 3 6 5 Setting Up SSL Certificates and Keys for MySQL Section 6 3 6 4 SSL Command Options Section 6 3 6 3 Using SS...

Страница 3166: ... Server Command Options symbols file Section 4 7 4 resolve_stack_dump Resolve Numeric Stack Trace Dump to Symbols sync bdb logs Section 14 5 3 BDB Startup Options sysconfdir Section 4 2 3 3 Using Option Files sysdate is now Section 12 7 Date and Time Functions Section 16 4 1 8 Replication and System Functions Section 5 1 3 Server Command Options Section 5 1 4 Server System Variables Section 2 19 1...

Страница 3167: ...4 5 1 1 mysql Options temp pool Section 5 1 3 Server Command Options test Section 4 6 5 myisampack Generate Compressed Read Only MyISAM Tables Text Section 1 2 Typographical and Syntax Conventions thread stack Section 2 20 1 5 Linux x86 Notes thread_cache_size Section 21 3 1 4 Debugging mysqld under gdb thread_stack Section 8 9 3 How MySQL Uses Threads for Client Connections timeout Section 17 4 1...

Страница 3168: ...y Log Section 4 6 16 mysql_tableinfo Generate Database Metadata Section 4 6 6 mysqlaccess Client for Checking Access Privileges Section 4 6 7 mysqlbinlog Utility for Processing Binary Log Files Section 4 6 9 mysqlhotcopy A Database Backup Program Section 4 5 2 mysqladmin Client for Administering a MySQL Server Section 4 5 3 mysqlcheck A Table Maintenance Program Section 4 5 4 mysqldump A Database ...

Страница 3169: ...ction 4 2 1 Invoking MySQL Programs Section 2 20 1 2 Linux Binary Distribution Notes Section 6 1 3 Making MySQL Secure Against Attackers Section 17 5 10 3 MySQL Cluster and MySQL Security Procedures Section 4 6 10 1 MySQL Instance Manager Command Options Section 4 2 3 6 Option Defaults Options Expecting Values and the Sign Section C 5 4 1 2 Resetting the Root Password Unix Systems Section 5 1 3 Se...

Страница 3170: ...on 4 5 1 1 mysql Options Section 17 4 14 ndb_restore Restore a MySQL Cluster Backup Section 4 6 2 myisam_ftdump Display Full Text Index information Section 4 6 5 myisampack Generate Compressed Read Only MyISAM Tables Section 4 6 11 mysql_convert_table_format Convert Tables to Use a Given Storage Engine Section 4 6 17 mysql_waitpid Kill Process and Wait for Its Termination Section 4 6 8 mysqldumpsl...

Страница 3171: ...atabase Backup Program Section 4 5 5 mysqlimport A Data Import Program Section 4 5 6 mysqlshow Display Database Table and Column Information Section 2 20 5 3 IBM AIX notes Section 2 20 1 3 Linux Source Distribution Notes Section 5 1 3 Server Command Options Section 2 20 3 Solaris Notes w Section 4 6 3 1 myisamchk General Options Section 4 5 1 1 mysql Options Section 4 6 4 myisamlog Display MyISAM ...

Страница 3172: ...ge engine Section 14 6 The EXAMPLE Storage Engine with extra charsets Section C 5 2 17 Can t initialize character set Section 2 17 3 MySQL Source Configuration Options with federated storage engine Section 14 7 The FEDERATED Storage Engine with libwrap Section 2 4 3 2 Choosing a Distribution Format with low memory Section 2 20 4 4 BSD OS Version 2 x Notes Section 2 17 4 Dealing with Problems Compi...

Страница 3173: ...Configuration Options without query cache Section 8 6 3 The MySQL Query Cache without server Section 2 17 3 MySQL Source Configuration Options X index top 3111 X Section 4 5 1 2 mysql Commands Section 4 5 1 1 mysql Options Section 4 5 4 mysqldump A Database Backup Program Section 2 20 3 Solaris Notes x Section 17 4 15 ndb_select_all Print Rows from an NDB Table Section 4 5 4 mysqldump A Database B...

Страница 3174: ...3154 ...

Страница 3175: ...on 5 1 4 Server System Variables Section 18 2 2 Stored Routines and MySQL Privileges CREATE TEMPORARY TABLES Section 13 1 10 CREATE TABLE Syntax Section 13 7 1 3 GRANT Syntax Section 6 2 1 Privileges Provided by MySQL CREATE USER Section 13 7 1 1 CREATE USER Syntax Section 13 7 1 2 DROP USER Syntax Section 13 7 1 3 GRANT Syntax Section 13 7 1 4 RENAME USER Syntax Section 13 7 1 5 REVOKE Syntax Sec...

Страница 3176: ..._SCHEMA COLUMN_PRIVILEGES Table I index top 3155 INDEX Section 13 1 4 ALTER TABLE Syntax Section 13 7 1 3 GRANT Syntax Section 6 2 1 Privileges Provided by MySQL Section 19 14 The INFORMATION_SCHEMA TABLE_PRIVILEGES Table INSERT Section 13 1 4 ALTER TABLE Syntax Section 13 7 2 1 ANALYZE TABLE Syntax Section 13 7 3 1 CREATE FUNCTION Syntax for User defined Functions Section 13 7 1 1 CREATE USER Syn...

Страница 3177: ...ave Options and Variables Section 16 3 7 Setting Up Replication Using SSL S index top 3155 SELECT Section 13 7 2 1 ANALYZE TABLE Syntax Section 13 1 9 CREATE PROCEDURE and CREATE FUNCTION Syntax Section 13 1 10 CREATE TABLE Syntax Section 13 1 11 CREATE TRIGGER Syntax Section 13 1 12 CREATE VIEW Syntax Section 13 2 2 DELETE Syntax Section 13 7 1 3 GRANT Syntax Section 13 2 5 INSERT Syntax Section ...

Страница 3178: ...ed Programs and Views Section 18 6 Binary Logging of Stored Programs Section 10 1 5 Configuring the Character Set and Collation for Applications Section 4 6 7 mysqlbinlog Utility for Processing Binary Log Files Section 12 12 Encryption and Compression Functions Section 12 9 6 Fine Tuning MySQL Full Text Search Section 16 1 1 How to Set Up Replication Section 6 1 3 Making MySQL Secure Against Attac...

Страница 3179: ...L Modes H index top 3159 HIGH_NOT_PRECEDENCE Section 9 5 Expression Syntax Section 12 3 1 Operator Precedence Section 5 1 7 Server SQL Modes I index top 3159 IGNORE_SPACE Section 4 5 1 1 mysql Options Section 13 1 9 CREATE PROCEDURE and CREATE FUNCTION Syntax Section 9 2 3 Function Name Parsing and Resolution Section 5 1 7 Server SQL Modes M index top 3159 MAXDB Section 11 1 2 Date and Time Type O...

Страница 3180: ...0 CREATE TABLE Syntax Section 11 1 5 Date and Time Types Section C 5 5 2 Problems Using DATE Columns Section 5 1 7 Server SQL Modes O index top 3159 ONLY_FULL_GROUP_BY Section 3 3 4 8 Counting Rows Section 12 15 3 MySQL Extensions to GROUP BY Section 5 1 7 Server SQL Modes ORACLE Section 5 1 7 Server SQL Modes P index top 3159 PIPES_AS_CONCAT Section 9 5 Expression Syntax Section 12 3 1 Operator P...

Страница 3181: ...age Formats Section 20 6 6 35 mysql_info Section 13 7 2 5 OPTIMIZE TABLE Syntax Section 13 1 20 RENAME TABLE Syntax Section 13 7 5 12 SHOW ENGINE Syntax Section 13 7 5 37 SHOW WARNINGS Syntax Section C 5 7 2 TEMPORARY Table Problems Section 11 1 5 4 YEAR 2 Limitations and Migrating to YEAR 4 Section 10 1 3 4 Column Character Set and Collation Section 10 1 12 Column Character Set Conversion Section...

Страница 3182: ...ms Section 18 4 1 View Syntax ANALYZE TABLE Section 4 6 3 1 myisamchk General Options Section 13 1 4 ALTER TABLE Syntax Section 13 7 2 1 ANALYZE TABLE Syntax Section 8 2 2 EXPLAIN Output Format Section 14 2 2 InnoDB Startup Options and System Variables Section 14 3 2 MERGE Table Problems Section 8 5 4 MyISAM Index Statistics Collection Section 7 6 MyISAM Table Maintenance and Crash Recovery Sectio...

Страница 3183: ...ews Section 18 2 1 Stored Routine Syntax Section 18 3 1 Trigger Syntax CASE Section 13 6 5 1 CASE Syntax Section 12 4 Control Flow Functions Section 13 6 5 Flow Control Statements CHANGE MASTER TO Section 13 4 2 1 CHANGE MASTER TO Syntax Section 13 7 1 3 GRANT Syntax Section 13 7 1 6 SET PASSWORD Syntax Section 13 7 5 31 SHOW SLAVE STATUS Syntax Section 16 3 1 2 Backing Up Raw Data from a Slave Se...

Страница 3184: ...MySQL Section 14 2 13 Limits on InnoDB Tables Section 13 3 MySQL Transactional and Locking Statements Section 16 1 1 4 Obtaining the Replication Master Binary Log Coordinates Section 16 4 1 25 Replication and Transactions Section 16 1 2 3 Replication Slave Options and Variables Section 5 1 6 Server Status Variables Section 5 1 4 Server System Variables Section 8 3 2 1 Speed of INSERT Statements Se...

Страница 3185: ...5 8 Issues Exclusive to MySQL Cluster CREATE TABLE Section 4 5 1 1 mysql Options Section 13 1 4 ALTER TABLE Syntax Section 14 2 3 3 AUTO_INCREMENT Handling in InnoDB Section 13 1 8 CREATE INDEX Syntax Section 13 1 10 1 CREATE TABLE SELECT Syntax Section 13 1 10 CREATE TABLE Syntax Section 13 8 2 EXPLAIN Syntax Section 1 8 6 2 FOREIGN KEY Constraints Section 13 8 3 HELP Syntax Section 14 2 3 4 Inno...

Страница 3186: ...tion E 7 6 Windows Platform Limitations CREATE TABLE LIKE Section 13 1 10 CREATE TABLE Syntax CREATE TABLE SELECT Section 13 1 10 1 CREATE TABLE SELECT Syntax Section 1 8 5 1 SELECT INTO TABLE Section 18 6 Binary Logging of Stored Programs Section 12 10 Cast Functions and Operators Section 14 2 7 2 Consistent Nonlocking Reads Section C 5 8 Known Issues in MySQL Section 16 4 1 3 Replication of CREA...

Страница 3187: ...20 6 6 1 mysql_affected_rows Section 20 6 6 48 mysql_num_rows Section 20 6 10 10 mysql_stmt_execute Section 20 6 10 13 mysql_stmt_field_count Section 20 6 10 17 mysql_stmt_num_rows Section 13 7 1 5 REVOKE Syntax Section 13 3 6 SET TRANSACTION Syntax Section 13 1 21 TRUNCATE TABLE Syntax Section 8 3 1 2 WHERE Clause Optimization Section 6 3 2 Adding User Accounts Section 16 1 2 4 Binary Log Options...

Страница 3188: ...ection 13 1 10 3 Silent Column Specification Changes Section 3 6 6 Using Foreign Keys Section 10 1 11 UTF 8 for Metadata DO Section 13 2 3 DO Syntax Section 18 6 Binary Logging of Stored Programs Section 12 14 Miscellaneous Functions Section 1 8 4 MySQL Extensions to Standard SQL Section 13 2 9 Subquery Syntax DROP DATABASE Section 13 1 13 DROP DATABASE Syntax Section 20 6 6 11 mysql_drop_db Secti...

Страница 3189: ...MySQL Limits Section 1 8 4 MySQL Extensions to Standard SQL Section E 4 Restrictions on Views Section 5 1 4 Server System Variables Section 13 3 3 Statements That Cause an Implicit Commit Section 14 4 The MEMORY HEAP Storage Engine Section 14 3 The MERGE Storage Engine Section 14 2 12 4 Troubleshooting InnoDB Data Dictionary Operations Section 13 1 10 2 Using FOREIGN KEY Constraints Section E 7 6 ...

Страница 3190: ...hod for Multiple Part Indexes Section 12 16 6 2 Using a Spatial Index Section 21 3 1 6 Using Server Logs to Find Causes of Errors in mysqld EXPLAIN EXTENDED Section 8 2 3 EXPLAIN EXTENDED Output Format Section 13 8 2 EXPLAIN Syntax Section 13 7 5 37 SHOW WARNINGS Syntax Section 8 3 1 5 Engine Condition Pushdown Optimization Section 8 2 1 Optimizing Queries with EXPLAIN Section 8 3 1 14 Optimizing ...

Страница 3191: ...Section 13 7 6 2 FLUSH Syntax Section 8 3 2 1 Speed of INSERT Statements FLUSH TABLES Section 13 7 6 2 FLUSH Syntax Section 13 2 4 HANDLER Syntax Section 13 2 5 2 INSERT DELAYED Syntax Section 14 3 2 MERGE Table Problems Section 20 6 6 55 mysql_refresh Section 7 2 Database Backup Methods Section 4 6 3 myisamchk MyISAM Table Maintenance Utility Section 4 6 9 mysqlhotcopy A Database Backup Program S...

Страница 3192: ...MySQL Access Privilege System Section 6 3 1 User Names and Passwords Section 6 3 6 3 Using SSL Connections Section 6 3 6 Using SSL for Secure Connections Section 6 2 6 When Privilege Changes Take Effect GRANT ALL Section 13 7 1 3 GRANT Syntax GRANT USAGE Section 13 7 1 3 GRANT Syntax Section 6 3 5 Assigning Account Passwords Section 6 3 4 Setting Account Resource Limits H index top 3161 HANDLER Se...

Страница 3193: ...2 13 Information Functions Section 8 7 1 Internal Locking Methods Section 14 7 3 Limitations of the FEDERATED Storage Engine Section 3 3 3 Loading Data into a Table Section 14 2 7 6 Locks Set by Different SQL Statements in InnoDB Section 12 14 Miscellaneous Functions Section 17 2 4 MySQL Cluster Example with Tables and Data Section 8 1 1 MySQL Design Limitations and Tradeoffs Section 1 8 4 MySQL E...

Страница 3194: ...ns Section E 1 Restrictions on Stored Programs Section 5 1 6 Server Status Variables Section 5 1 4 Server System Variables Section 8 3 2 1 Speed of INSERT Statements Section 8 7 2 Table Locking Issues Section 13 3 5 3 Table Locking Restrictions and Conditions Section 14 8 The ARCHIVE Storage Engine Section 14 4 The MEMORY HEAP Storage Engine Section 1 8 5 3 Transactions and Atomic Operations Secti...

Страница 3195: ... from a Slave Section 7 1 Backup and Recovery Types Section 6 2 7 Causes of Access Denied Errors Section 8 7 3 Concurrent Inserts Section 7 2 Database Backup Methods Section 10 1 3 2 Database Character Set and Collation Section 17 4 17 ndb_show_tables Display List of NDB Tables Section 4 6 7 mysqlbinlog Utility for Processing Binary Log Files Section 4 5 4 mysqldump A Database Backup Program Secti...

Страница 3196: ...ion 4 6 9 mysqlhotcopy A Database Backup Program Section 4 5 4 mysqldump A Database Backup Program Section 14 2 7 9 How to Cope with Deadlocks Section 13 3 5 1 Interaction of Table Locking and Transactions Section 8 7 1 Internal Locking Methods Section 17 1 5 9 Limitations Relating to Multiple MySQL Cluster Nodes Section 14 2 13 Limits on InnoDB Tables Section 14 2 7 6 Locks Set by Different SQL S...

Страница 3197: ...ENAME TABLE Syntax Section 4 5 4 mysqldump A Database Backup Program Section 8 10 2 General Thread States Section 9 2 2 Identifier Case Sensitivity Section 1 8 4 MySQL Extensions to Standard SQL Section 13 3 3 Statements That Cause an Implicit Commit Section 14 2 1 1 Using Per Table Tablespaces Section 8 9 6 2 Using Symbolic Links for MyISAM Tables on Unix RENAME USER Section 13 7 1 3 GRANT Syntax...

Страница 3198: ...R Syntax Section 16 3 6 Switching Masters During Failover Section 5 2 3 The Binary Log RESET SLAVE Section 13 7 6 2 FLUSH Syntax Section 20 6 6 55 mysql_refresh Section 13 4 1 2 RESET MASTER Syntax Section 13 4 2 5 RESET SLAVE Syntax Section 16 1 2 3 Replication Slave Options and Variables RESTORE TABLE Section 13 7 2 2 BACKUP TABLE Syntax Section 13 7 2 7 RESTORE TABLE Syntax Section 8 9 6 2 Usin...

Страница 3199: ...Options and System Variables Section 13 2 5 1 INSERT SELECT Syntax Section 13 2 5 2 INSERT DELAYED Syntax Section 13 2 5 INSERT Syntax Section 13 2 8 2 JOIN Syntax Section 13 7 6 3 KILL Syntax Section 13 4 2 2 LOAD DATA FROM MASTER Syntax Section 13 4 2 3 LOAD TABLE tbl_name FROM MASTER Syntax Section 13 3 5 LOCK TABLES and UNLOCK TABLES Syntax Section 14 3 2 MERGE Table Problems Section 7 6 4 MyI...

Страница 3200: ...dard SQL Section 12 9 1 Natural Language Full Text Searches Section C 5 6 Optimizer Related Issues Section 8 3 1 Optimizing SELECT Statements Section 8 3 2 Optimizing Non SELECT Statements Section 8 2 1 Optimizing Queries with EXPLAIN Section 8 3 1 14 Optimizing Subqueries with EXISTS Strategy Section 4 6 3 4 Other myisamchk Options Section 8 3 3 Other Optimization Tips Section 6 2 1 Privileges Pr...

Страница 3201: ...1 Unix Postinstallation Procedures SELECT INTO OUTFILE Section 13 2 6 LOAD DATA INFILE Syntax Section 9 1 7 NULL Values Section 13 2 8 1 SELECT INTO Syntax Section 1 8 5 1 SELECT INTO TABLE Section 7 1 Backup and Recovery Types Section 6 2 7 Causes of Access Denied Errors Section 7 4 3 Dumping Data in Delimited Text Format with mysqldump Section 14 2 5 2 Forcing InnoDB Recovery Section 6 1 3 Makin...

Страница 3202: ...se Section 2 18 2 Securing the Initial MySQL Accounts Section 5 1 4 Server System Variables Section 6 2 3 Specifying Account Names Section 6 2 6 When Privilege Changes Take Effect SET SESSION Section 13 7 4 SET Syntax Section 5 1 5 2 Dynamic System Variables Section 5 1 5 Using System Variables SET sql_mode mode_value Section 1 8 2 Selecting SQL Modes SET TIMESTAMP value Section 8 10 Examining Thr...

Страница 3203: ...Sets and Collations That MySQL Supports Section 19 18 Extensions to SHOW Statements SHOW COLLATION Section 13 1 1 ALTER DATABASE Syntax Section 13 7 5 4 SHOW COLLATION Syntax Section 10 1 9 3 SHOW Statements and INFORMATION_SCHEMA Section 20 6 4 C API Data Structures Section 10 5 Character Set Configuration Section 10 1 2 Character Sets and Collations in MySQL Section 10 1 3 5 Character String Lit...

Страница 3204: ... 7 1 3 GRANT Syntax Chapter 19 INFORMATION_SCHEMA Tables Section 13 4 2 2 LOAD DATA FROM MASTER Syntax Section 13 7 5 11 SHOW DATABASES Syntax Section 3 3 Creating and Using a Database Section 4 6 16 mysql_tableinfo Generate Database Metadata Section 19 18 Extensions to SHOW Statements Section 3 4 Getting Information About Databases and Tables Section 9 2 2 Identifier Case Sensitivity Section 2 20...

Страница 3205: ... System Grant Tables Section 6 1 1 Security Guidelines Section 6 2 The MySQL Access Privilege System SHOW INDEX Section 13 7 2 1 ANALYZE TABLE Syntax Section 8 2 2 EXPLAIN Output Format Section 13 8 2 EXPLAIN Syntax Section 8 5 4 MyISAM Index Statistics Collection Section 13 7 5 5 SHOW COLUMNS Syntax Section 13 7 5 18 SHOW INDEX Syntax Section 4 6 16 mysql_tableinfo Generate Database Metadata Sect...

Страница 3206: ... 7 5 31 SHOW SLAVE STATUS Syntax Section 13 4 2 7 START SLAVE Syntax Section 16 1 3 1 Checking Replication Status Section 4 5 4 mysqldump A Database Backup Program Section 16 4 5 How to Report Replication Bugs or Problems Section 6 2 1 Privileges Provided by MySQL Section 16 2 1 Replication Implementation Details Section 8 10 6 Replication Slave I O Thread States Section 16 1 2 3 Replication Slave...

Страница 3207: ...g Replication START TRANSACTION Section 13 6 1 BEGIN END Compound Statement Syntax Section 14 2 11 InnoDB Error Handling Section 13 3 5 LOCK TABLES and UNLOCK TABLES Syntax Section 14 2 7 3 SELECT FOR UPDATE and SELECT LOCK IN SHARE MODE Locking Reads Section 13 3 1 START TRANSACTION COMMIT and ROLLBACK Syntax Section 14 5 4 Characteristics of BDB Tables Section 4 5 4 mysqldump A Database Backup P...

Страница 3208: ...T and ROLLBACK Syntax Section 7 2 Database Backup Methods Section 4 5 4 mysqldump A Database Backup Program Section 14 2 7 9 How to Cope with Deadlocks Section 13 3 5 1 Interaction of Table Locking and Transactions Section 14 2 13 Limits on InnoDB Tables Section E 1 Restrictions on Stored Programs Section 8 3 2 1 Speed of INSERT Statements Section 13 3 3 Statements That Cause an Implicit Commit Se...

Страница 3209: ...5 1 6 Server Status Variables Section 5 1 4 Server System Variables Section 16 4 1 20 Slave Errors During Replication Section 8 3 2 1 Speed of INSERT Statements Section 8 3 2 2 Speed of UPDATE Statements Section 13 2 9 9 Subquery Errors Section 13 2 9 Subquery Syntax Section 8 7 2 Table Locking Issues Section 13 3 5 3 Table Locking Restrictions and Conditions Section 10 1 7 6 The _bin and binary C...

Страница 3210: ... top 3161 XA COMMIT Section 5 1 4 Server System Variables Section 13 3 7 2 XA Transaction States XA END Section E 5 Restrictions on XA Transactions Section 13 3 7 1 XA Transaction SQL Syntax Section 13 3 7 2 XA Transaction States XA PREPARE Section 13 3 7 2 XA Transaction States XA RECOVER Section 13 3 7 1 XA Transaction SQL Syntax Section 13 3 7 2 XA Transaction States XA ROLLBACK Section 5 1 4 S...

Страница 3211: ...1 9 CREATE PROCEDURE and CREATE FUNCTION Syntax Section 5 1 4 Server System Variables Section 18 2 2 Stored Routines and MySQL Privileges B index top 3191 back_log Section 5 1 4 Server System Variables basedir Section 5 1 4 Server System Variables bdb_cache_size Section 5 1 4 Server System Variables bdb_home Section 5 1 4 Server System Variables bdb_log_buffer_size Section 5 1 4 Server System Vari...

Страница 3212: ...les character_set_system Section 10 5 Character Set Configuration Section 5 1 4 Server System Variables Section 10 1 11 UTF 8 for Metadata character_sets_dir Section 10 4 3 Adding a Simple Collation to an 8 Bit Character Set Section 10 4 4 1 Defining a UCA Collation using LDML Syntax Section 5 1 4 Server System Variables collation_connection Section 10 1 9 2 CONVERT and CAST Section 13 7 4 SET Syn...

Страница 3213: ...ns Section 5 1 4 Server System Variables error_count Section 13 7 5 14 SHOW ERRORS Syntax Section 5 1 4 Server System Variables Section C 1 Sources of Error Information expire_logs_days Section 13 4 1 1 PURGE BINARY LOGS Syntax Section 5 2 5 Server Log Maintenance Section 5 1 4 Server System Variables F index top 3191 flush Section 5 1 4 Server System Variables flush_time Section 5 1 4 Server Syst...

Страница 3214: ...iables have_ndbcluster Section 17 3 4 3 MySQL Cluster System Variables have_openssl Section 6 3 6 2 Configuring MySQL for SSL Section 5 1 4 Server System Variables have_profiling Section 5 1 4 Server System Variables have_query_cache Section 8 6 3 3 Query Cache Configuration Section 5 1 4 Server System Variables have_raid Section 5 1 4 Server System Variables have_rtree_keys Section 5 1 4 Server S...

Страница 3215: ... 3 5 InnoDB and MySQL Replication Section 14 2 2 InnoDB Startup Options and System Variables Section 14 2 12 2 2 InnoDB Tablespace Monitor Output Section 14 2 1 3 Creating the InnoDB Tablespace Section 16 3 4 Replicating Different Databases to Different Slaves Section 14 2 12 4 Troubleshooting InnoDB Data Dictionary Operations Section 14 2 1 1 Using Per Table Tablespaces innodb_flush_log_at_trx_co...

Страница 3216: ...LETE Statements Section 8 3 2 1 Speed of INSERT Statements Section 8 3 2 4 Speed of REPAIR TABLE Statements Section 5 1 5 1 Structured System Variables Section 8 6 1 The MyISAM Key Cache Section 8 9 2 Tuning Server Parameters Section 4 2 3 3 Using Option Files key_cache_age_threshold Section 8 6 1 3 Midpoint Insertion Strategy Section 5 1 4 Server System Variables Section 5 1 5 1 Structured System...

Страница 3217: ... 10 2 Using FOREIGN KEY Constraints M index top 3191 max_allowed_packet Section 12 15 1 GROUP BY Aggregate Functions Section C 5 2 3 Lost connection to MySQL server Section C 5 2 9 MySQL server has gone away Section 20 6 6 71 mysql_use_result Section C 5 2 11 Communication Errors and Aborted Connections Section 12 3 2 Comparison Functions and Operators Section C 5 5 6 Deleting Rows from Related Ta...

Страница 3218: ...ts on InnoDB Tables Section 5 1 4 Server System Variables max_sort_length Section 13 1 10 CREATE TABLE Syntax Section C 5 8 Known Issues in MySQL Section 5 1 4 Server System Variables Section 11 1 6 3 The BLOB and TEXT Types max_sp_recursion_depth Section 5 1 4 Server System Variables Section 18 2 1 Stored Routine Syntax max_tmp_tables Section 5 1 4 Server System Variables max_user_connections Sec...

Страница 3219: ...OM MASTER Syntax Section C 5 2 3 Lost connection to MySQL server Section 2 20 4 1 FreeBSD Notes Section 2 20 2 1 Mac OS X 10 x Darwin Section 5 1 4 Server System Variables net_retry_count Section 20 6 6 49 mysql_options Section 5 1 4 Server System Variables net_write_timeout Section 13 4 2 2 LOAD DATA FROM MASTER Syntax Section 5 1 4 Server System Variables new Section 5 1 4 Server System Variable...

Страница 3220: ...ery Cache Configuration Section 5 1 4 Server System Variables Section 8 6 3 The MySQL Query Cache Section 5 1 5 Using System Variables query_cache_type Section 13 2 8 SELECT Syntax Section 8 6 3 2 Query Cache SELECT Options Section 8 6 3 3 Query Cache Configuration Section 5 1 6 Server Status Variables Section 5 1 4 Server System Variables query_cache_wlock_invalidate Section 5 1 4 Server System V...

Страница 3221: ..._load_tmpdir Section 13 2 6 LOAD DATA INFILE Syntax Section 16 1 2 3 Replication Slave Options and Variables Section 5 1 4 Server System Variables slave_net_timeout Section 16 1 3 1 Checking Replication Status Section 16 4 1 13 Replication and Master or Slave Shutdowns Section 8 10 6 Replication Slave I O Thread States Section 16 1 2 3 Replication Slave Options and Variables Section 5 1 4 Server S...

Страница 3222: ...tion 13 7 5 31 SHOW SLAVE STATUS Syntax Section 16 1 2 3 Replication Slave Options and Variables sql_warnings Section 5 1 4 Server System Variables ssl_ca Section 5 1 4 Server System Variables ssl_capath Section 5 1 4 Server System Variables ssl_cert Section 5 1 4 Server System Variables ssl_cipher Section 5 1 4 Server System Variables ssl_key Section 5 1 4 Server System Variables storage_engine S...

Страница 3223: ...Section 8 3 1 11 ORDER BY Optimization Section 16 3 1 2 Backing Up Raw Data from a Slave Section 7 2 Database Backup Methods Section 16 1 2 3 Replication Slave Options and Variables Section 5 1 4 Server System Variables transaction_alloc_block_size Section 5 1 4 Server System Variables transaction_prealloc_size Section 5 1 4 Server System Variables tx_isolation Section 13 3 6 SET TRANSACTION Synta...

Страница 3224: ...3204 warning_count Section 13 7 5 14 SHOW ERRORS Syntax Section 13 7 5 37 SHOW WARNINGS Syntax Section 5 1 4 Server System Variables Section C 1 Sources of Error Information ...

Страница 3225: ...er System Variables Created_tmp_disk_tables Section 8 8 5 How MySQL Uses Internal Temporary Tables Section 5 1 6 Server Status Variables Section 5 1 4 Server System Variables Created_tmp_files Section 5 1 6 Server Status Variables Created_tmp_tables Section 8 8 5 How MySQL Uses Internal Temporary Tables Section 5 1 6 Server Status Variables Section 5 1 4 Server System Variables D index top 3205 De...

Страница 3226: ...s Variables Innodb_buffer_pool_read_ahead_rnd Section 5 1 6 Server Status Variables Innodb_buffer_pool_read_ahead_seq Section 5 1 6 Server Status Variables Innodb_buffer_pool_read_requests Section 5 1 6 Server Status Variables Innodb_buffer_pool_reads Section 5 1 6 Server Status Variables Innodb_buffer_pool_wait_free Section 5 1 6 Server Status Variables Innodb_buffer_pool_write_requests Section 5...

Страница 3227: ...ariables Innodb_rows_read Section 5 1 6 Server Status Variables Innodb_rows_updated Section 5 1 6 Server Status Variables K index top 3205 Key_blocks_not_flushed Section 5 1 6 Server Status Variables Key_blocks_unused Section 5 1 6 Server Status Variables Section 5 1 4 Server System Variables Key_blocks_used Section 5 1 6 Server Status Variables Key_read_requests Section 5 1 6 Server Status Variab...

Страница 3228: ...ts Section 5 1 6 Server Status Variables Qcache_lowmem_prunes Section 8 6 3 3 Query Cache Configuration Section 8 6 3 4 Query Cache Status and Maintenance Section 5 1 6 Server Status Variables Qcache_not_cached Section 5 1 6 Server Status Variables Qcache_queries_in_cache Section 8 6 3 3 Query Cache Configuration Section 5 1 6 Server Status Variables Qcache_total_blocks Section 8 6 3 3 Query Cache...

Страница 3229: ...on 5 1 6 Server Status Variables Ssl_ctx_verify_depth Section 5 1 6 Server Status Variables Ssl_ctx_verify_mode Section 5 1 6 Server Status Variables Ssl_default_timeout Section 5 1 6 Server Status Variables Ssl_finished_accepts Section 5 1 6 Server Status Variables Ssl_finished_connects Section 5 1 6 Server Status Variables Ssl_session_cache_hits Section 5 1 6 Server Status Variables Ssl_session_...

Страница 3230: ...r Status Variables Threads_connected Section 5 1 6 Server Status Variables Threads_created Section 8 9 3 How MySQL Uses Threads for Client Connections Section 5 1 6 Server Status Variables Section 5 1 4 Server System Variables Threads_running Section 5 1 6 Server Status Variables U index top 3205 Uptime Section 4 5 2 mysqladmin Client for Administering a MySQL Server Section 5 1 6 Server Status Va...

Страница 3231: ...ommand Options REPEATABLE READ Section 14 2 7 4 InnoDB Record Gap and Next Key Locks Section 13 3 6 SET TRANSACTION Syntax Section 13 3 1 START TRANSACTION COMMIT and ROLLBACK Syntax Section 14 2 7 2 Consistent Nonlocking Reads Section 17 1 5 3 Limits Relating to Transaction Handling in MySQL Cluster Section 14 2 7 The InnoDB Transaction Model and Locking Section 13 3 7 XA Transactions REPEATABLE ...

Страница 3232: ...3212 ...

Отзывы: