Vous êtes sur la page 1sur 36

Java MySQL Transaction Commit & Rollback?

MySQL Transaction transaction MySQL Database MySQL Google

Problem with Transaction rollback with JDBC (mysql)

http://forum.java.sun.com/thread.jspa?threadID=600053&messageID=3951042

1(417)

....... I have written an example program to see if the transaction rollback is properly working or not. I am using mysql database. I turned autocommit mode to false and then explicitly rollbacked transaction :- problem i faced is Create stament gets executed but insert statement is rollbacked only. But, I think that both should be rollbacked,can someone help me as I am not able to figure out the problem. Here is the complete code :

import java.sql.*;

public class CreateCoffees {

public static void main(String args[]) {

String url = "jdbc:mysql://localhost/test"; Connection con = null; String createString; createString = "create table COFFEES " + "(COF_NAME varchar(32), " + "SUP_ID int, " + "PRICE float, " + "SALES int, " + "TOTAL int)"; Statement stmt = null;

try { Class.forName("com.mysql.jdbc.Driver");

} catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); }

try {

con = DriverManager.getConnection(url, "root", "root"); // Set Autocommit false con.setAutoCommit(false);

stmt = con.createStatement();

// execute create table statement stmt.executeUpdate(createString);

System.out.println("Auto commit mode is " + con.getAutoCommit());

// enter an item into the database stmt.executeUpdate("insert into COFFEES " + "values('Colombian', 00101, 7.99, 0, 0)");

// rollback complete transaction con.rollback();

} catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if(con != null) { con.close(); } if(stmt != null) { stmt.close(); } }catch(SQLException ex) { ex.printStackTrace(); } } }

Problem : Coffees table is created but the entry is not inserted into the coffees. But I think both should not be executed as autocommit mode is off. (using mysql 4.1.27)

__________________________________________________________________ ____________________________________________ skywalker

Thai Developer Network Free online shopping cheap toy for sale cheap dirt bike for sale skate board on sale

2(418) ....... MySQL Control Transaction Version

With MySQL, you have a choice of different storage engines (aka table types), some of which support transactionality and some of which do not. For backwards

compatability, the default storage engine is MyISAM, which does not support transactions. Only the INNODB and BDB engines will support rollback.

See the documentation: http://dev.mysql.com/doc/refman/5.0/en/storage-engines.html

This is true with older versions of MySQL as well; however, really old versions don't support transactions at all.

You can specify a table type (storage engine) in the CREATE TABLE ... statement, but the posted code did not; unless you modify the SQL or change the default storage engine of your MySQL database, you won't get transactionality/rollback.

See also: http://dev.mysql.com/doc/refman/5.0/en/create-table.html storage engine MySQL MyISAM Rollback, Commit, Version Version 5 MySQL INNODB Config INNODB BDB engines

...

__________________________________________________________________ ____________________________________________ skywalker

Thai Developer Network Free online shopping cheap toy for sale cheap dirt bike for sale skate board on sale

3(421) ....... Commit, Rollback PHP http://www.devarticles.com/c/a/MySQL/Using-Transactions-with-MySQL-4.0and-PHP/

This is a well-written article by Joel about MySQL transactions. If you are new to MySQL 4.0, then you must read this so you can ensure data integrity.

With the arrival of MySQL 4.0, you finally have full support of Transactions. This course will help you get started using this great new feature using PHP.

Requirements for this Article

MySQL and PHP installed on a local or remote server. Knowledge of using the MySQL Monitor program. MySQL connectivity using PHP. MySQL Version 4.0.12 using InnoDB type tables. You have heard of Transacations but you are not sure on how they are used. They are simple to utilize after you learn the basics.

Lets start with defining Transactions. A good definition would be the following:

"Transaction Processing is used to maintain database integrity by ensuring that SQL operations execute completely or not at all."

Thats fine for a definition but a visual example would be better.

If you go to the store and take 3 of the 10 items on the shelf, that leaves 7 left for others to purchase. You decide to checkout and make your way to the purchase your items. If you agree to buy the items then you give the merchant your money and COMMIT to the Transaction. After you receive your receipt the Transaction is completed.

You have learned all there is to know about Transactions.

Not really, but its a start.

Here are the steps for using Transactions in MySQL:

BEGIN the Transaction. Update, insert or delete entries in the database. If you like the changes to the database, then you COMMIT to the Transaction. If you do not like the changes then you ROLLBACK the changes to the original condition of the database. Note: You must use InnoDB type tables or Transactions, will not work.

Lets create a basic table in your database called "trans", and make the table type "innodb".

CREATE TABLE trans ( id int not null auto_increment, item varchar(30) not null, quantity varchar(10) not null, primary key(id) )type=innodb;

Heres the contruction of the table:

mysql> DESC trans;

Field Type Null Key Default id int(11) PRI

Extra auto_increment

NULL

item varchar(30) quantity varchar(10)

3 rows in set (0.00 sec)

Insert some data into the table:

mysql> INSERT INTO trans (id,item,quantity) VALUES (NULL,'Computer','5');

Query OK, 1 row affected (0.00 sec)

Begin the Transaction by using the BEGIN command and update the entry:

mysql> BEGIN;

Query OK, 0 rows affected (0.00 sec)

mysql> UPDATE trans SET quantity ='4' WHERE id=1;

Query OK, 1 row affected (0.01 sec)

Rows matched: 1 Changed: 1 Warnings: 0

View the results of the update:

mysql> SELECT * FROM trans;

id 1

item quantity Computer 4

1 row in set (0.00 sec)

If you do not like the changes, then use the ROLLBACK command to revert back to the original version of the table.

mysql> ROLLBACK;

Query OK, 0 rows affected (0.00 sec)

Notice the table has reverted back to the original insertion:

mysql> SELECT * FROM trans;

id 1

item quantity Computer 5

1 row in set (0.01 sec)

Lets update the table using another Transaction and commit to the changes:

mysql> BEGIN;

Query OK, 0 rows affected (0.00 sec)

mysql> UPDATE trans SET quantity ='2' WHERE id=1;

Query OK, 1 row affected (0.00 sec)

Rows matched: 1 Changed: 1 Warnings: 0

mysql> SELECT * FROM trans;

id 1

item quantity Computer 2

1 row in set (0.00 sec)

mysql> COMMIT;

Query OK, 0 rows affected (0.00 sec)

After you use the COMMIT command, the table will take on the changes and remain that way until they are modified.

mysql> SELECT * FROM trans;

id 1

item quantity Computer 2

1 row in set (0.00 sec)

Now that you understand the basics of Transactions lets create a PHP script that will insert new data into the table.

Here is the code for the transaction script:

<?php // trans.php function begin() { @mysql_query("BEGIN"); } function commit() { @mysql_query("COMMIT"); } function rollback() { @mysql_query("ROLLBACK"); } @mysql_connect("localhost","username", "password") or die(mysql_error()); @mysql_select_db("test") or die(mysql_error()); $query = "INSERT INTO trans (id,item,quantity) values (null,'Baseball',4)"; begin(); // transaction begins $result = @mysql_query($query);

if(!$result) { rollback(); // transaction rolls back echo "you rolled back"; exit; } else { commit(); // transaction is committed echo "your insertion was successful"; } ?>

Explanation of the script

Functions are created for the BEGIN, COMMIT and ROLLBACK commands. The script connects to the server and runs the query of inserting data into the table. If the query is successful then it COMMITS the Transaction. If the query is unsuccessful then the Transaction will ROLLBACK. Here is the table after the script executes:

mysql> SELECT * FROM trans;

id 1 2

item quantity Computer Baseball 2 4

2 rows in set (0.00 sec)

I hope that this gets you started using Transactions in MySQL 4.0 using PHP. Its a great feature and will open up new ideas when building web applications.

__________________________________________________________________ ____________________________________________ skywalker

Thai Developer Network Free online shopping cheap toy for sale cheap dirt bike for sale skate board on sale

4(422) ....... ...

13.4.1. START TRANSACTION, COMMIT, and ROLLBACK Syntax http://dev.mysql.com/doc/refman/4.1/en/commit.html

START TRANSACTION | BEGIN [WORK] COMMIT ROLLBACK SET AUTOCOMMIT = {0 | 1} The START TRANSACTION and BEGIN statement begin a new transaction. COMMIT commits the current transaction, making its changes permanent. ROLLBACK rolls back the current transaction, canceling its changes. The SET AUTOCOMMIT statement disables or enables the default autocommit mode for the current connection.

By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk.

If you are using a transaction-safe storage engine (such as InnoDB, BDB, or NDB Cluster), you can disable autocommit mode with the following statement:

SET AUTOCOMMIT=0; After disabling autocommit mode by setting the AUTOCOMMIT variable to zero, you must use COMMIT to store your changes to disk or ROLLBACK if you want to ignore the changes you have made since the beginning of your transaction.

To disable autocommit mode for a single series of statements, use the START TRANSACTION statement:

START TRANSACTION; SELECT @A:=SUM(salary) FROM table1 WHERE type=1; UPDATE table2 SET summary=@A WHERE type=1; COMMIT; With START TRANSACTION, autocommit remains disabled until you end the transaction with COMMIT or ROLLBACK. The autocommit mode then reverts to its previous state.

BEGIN and BEGIN WORK are supported as aliases of START TRANSACTION for initiating a transaction. START TRANSACTION was added in MySQL 4.0.11. This is standard SQL syntax and is the recommended way to start an ad-hoc transaction. BEGIN and BEGIN WORK are available from MySQL 3.23.17 and 3.23.19, respectively.

As of MySQL 4.1.8, you can begin a transaction like this:

START TRANSACTION WITH CONSISTENT SNAPSHOT; The WITH CONSISTENT SNAPSHOT clause starts a consistent read for storage engines that are capable of it. Currently, this applies only to InnoDB. The effect is the same as issuing a START TRANSACTION followed by a SELECT from any InnoDB table. See Section 14.2.11.4, Consistent Non-Locking Read.

The WITH CONSISTENT SNAPSHOT clause does not change the current transaction isolation level, so it provides a consistent snapshot only if the current

isolation level is one that allows consistent read (REPEATABLE READ or SERIALIZABLE).

Beginning a transaction causes an implicit UNLOCK TABLES to be performed.

For best results, transactions should be performed using only tables managed by a single transactional storage engine. Otherwise, the following problems can occur:

If you use tables from more than one transaction-safe storage engine (such as InnoDB and BDB), and the transaction isolation level is not SERIALIZABLE, 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 the isolation level to SERIALIZABLE on a per-transaction basis as necessary.)

If you use non-transaction-safe tables within a transaction, any changes to those tables are stored at once, regardless of the status of autocommit mode.

If you issue a ROLLBACK statement after updating a non-transactional table within a transaction, an ER_WARNING_NOT_COMPLETE_ROLLBACK warning occurs. Changes to transaction-safe tables are rolled back, but not changes to non-transaction-safe tables.

If you are using START TRANSACTION or SET AUTOCOMMIT=0, you should use the MySQL binary log for backups instead of the older update log. Transactions are stored in the binary log in one chunk, upon COMMIT.

Transactions that are rolled back are not logged. (Exception: Modifications to nontransactional tables cannot be rolled back. If a transaction that is rolled back includes modifications to non-transactional tables, the entire transaction is logged with a ROLLBACK statement at the end to ensure that the modifications to those tables are replicated. This is true as of MySQL 4.0.15.) See Section 5.11.4, The Binary Log.

You can change the isolation level for transactions with SET TRANSACTION ISOLATION LEVEL. See Section 13.4.6, SET TRANSACTION Syntax.

Rolling back can be a slow operation that may occur without the user having explicitly asked for it (for example, when an error occurs). Because of this, SHOW PROCESSLIST displays Rolling back in the State column for the connection during implicit and explicit (ROLLBACK SQL statement) rollbacks, starting from MySQL 4.1.8.

Previous / Next / Up / Table of Contents

User Comments

Posted by Phil Haigh on October 20 2005 7:54am [Delete] [Edit] If you want to use transactions within Java code, you will need to issue a START TRANSACTION statement after you've acquired your connection. There is no method in the JDBC interface to do this, so you'll need to do the following instead:

// get connection Connection connection = dataSource.getConnection();

// Start the transaction Statement statement = connection.createStatement(); statement.execute("START TRANSACTION");

Now when your code issues a commit or rollback, all the statements executed will be committed or rolled back as a unit.

Posted by Rodrigo Elias on November 6 2005 5:21pm In fact, Java 5 supports Transactions.

[Delete] [Edit]

All you need to do is set connection.autoCommit(false) ( in Java, every transaction is "commited" by default, so, we have to 'disable' it, to commit our transaction when ever we want to), and then use connection.commit() or connection.rollback() when you need.

Posted by Jez on November 15 2005 2:50pm [Delete] [Edit] Warning...

"START TRANSACTION" also does a COMMIT.

It's best to maintain some kind of context within your program if you think it's possible to end up with one routine calling another that may also have a START TRANSACTION. Otherwise you'll COMMIT TRANSACTIONs before you wanted too.

__________________________________________________________________ ____________________________________________ skywalker

Thai Developer Network Free online shopping cheap toy for sale cheap dirt bike for sale skate board on sale

5(423) ....... 14.2.7.4. FOREIGN KEY Constraints

Starting from MySQL 3.23.44, InnoDB features foreign key constraints.

The syntax of a foreign key constraint definition in InnoDB looks like this:

[CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...) REFERENCES tbl_name (index_col_name, ...) [ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION}]

[ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION}] Foreign keys definitions are subject to the following conditions:

Both tables must be InnoDB tables and they must not be TEMPORARY tables.

In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Starting with MySQL 4.1.2, such an index is created on the referencing table automatically if it does not exist.

In the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

Index prefixes on foreign key columns are not supported. One consequence of this is that BLOB and TEXT columns cannot be included in a foreign key, because indexes on those columns must always include a prefix length.

If the CONSTRAINT symbol clause is given, the symbol value must be unique in the database. If the clause is not given, InnoDB creates the name automatically.

InnoDB rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table. The action InnoDB takes for any UPDATE or DELETE operation that attempts to update or delete a candidate key value in the parent table that has some matching rows in the child table is dependent on the referential action specified using ON UPDATE and ON DELETE subclauses of the FOREIGN KEY clause. When the user attempts to delete or update a row from a parent table, and there are one or more matching rows in the child table, InnoDB supports five options regarding the action to be taken:

CASCADE: Delete or update the row from the parent table and automatically delete or update the matching rows in the child table. ON DELETE CASCADE is supported starting from MySQL 3.23.50 and ON UPDATE CASCADE is supported starting from 4.0.8. Between two tables, you should not define several ON UPDATE CASCADE clauses that act on the same column in the parent table or in the child table.

SET NULL: Delete or update the row from the parent table and set the foreign key column or columns in the child table to NULL. This is valid only if the foreign key columns do not have the NOT NULL qualifier specified. ON DELETE SET NULL is available starting from MySQL 3.23.50 and ON UPDATE SET NULL is available starting from 4.0.8.

NO ACTION: In standard sQL, NO ACTION means no action in the sense that an attempt to delete or update a primary key value will not be allowed to proceed if there is a related foreign key value in the referenced table. Starting from 4.0.18 InnoDB rejects the delete or update operation for the parent table.

RESTRICT: Rejects the delete or update operation for the parent table. NO ACTION and RESTRICT are the same as omitting the ON DELETE or ON UPDATE clause. (Some database systems have deferred checks, and NO ACTION is a deferred check. In MySQL, foreign key constraints are checked immediately, so NO ACTION and RESTRICT are the same.)

SET DEFAULT: This action is recognized by the parser, but InnoDB rejects table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses.

Note that InnoDB supports foreign key references within a table. In these cases, child table records really refers to dependent records within the same table.

InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. Starting with MySQL 4.1.2, the index on the foreign key is created automatically. In older versions, the indexes must be created explicitly or the creation of foreign key constraints fails.

Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL.

If MySQL reports an error number 1005 from a CREATE TABLE statement, and the error message refers to errno 150, table creation failed because a foreign key constraint was not correctly formed. Similarly, if an ALTER TABLE fails and it refers to errno 150, that means a foreign key definition would be incorrectly formed for the altered table. Starting from MySQL 4.0.13, you can use SHOW INNODB STATUS to display a detailed explanation of the latest InnoDB foreign key error in the server.

Starting from MySQL 3.23.50, InnoDB does not check foreign key constraints on those foreign key or referenced key values that contain a NULL column.

Note: Currently, triggers are not activated by cascaded foreign key actions.

You cannot create a table with a column name that matches the name of an internal InnoDB column (including DB_ROW_ID, DB_TRX_ID, DB_ROLL_PTR and DB_MIX_ID). In versions of MySQL before 4.1.19 this would cause a crash, since 4.1.19 the server will report error 1005 and refers to errno -1 in the error message.

Deviation from SQL standards: If there are several rows in the parent table that have the same referenced key value, InnoDB acts in foreign key checks as if the other parent rows with the same key value do not exist. For example, if you have defined a RESTRICT type constraint, and there is a child row with several parent rows, InnoDB does not allow the deletion of any of those parent rows.

InnoDB performs cascading operations through a depth-first algorithm, based on records in the indexes corresponding to the foreign key constraints.

Deviation from SQL standards: A FOREIGN KEY constraint that references a non-UNIQUE key is not standard SQL. It is an InnoDB extension to standard SQL.

Deviation from SQL standards: If ON UPDATE CASCADE or ON UPDATE SET NULL recurses to update the same table it has previously updated during the cascade, it acts like RESTRICT. This means that you cannot use self-referential ON UPDATE CASCADE or ON UPDATE SET NULL operations. This is to prevent infinite loops resulting from cascaded updates. A self-referential ON DELETE SET NULL, on the other hand, is possible from 4.0.13. A self-referential ON DELETE CASCADE has been possible since ON DELETE was implemented. Since 4.0.21, cascading operations may not be nested more than 15 levels.

Deviation from SQL standards: 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. According to the SQL standard, the default behavior

should be deferred checking. That is, constraints are only checked after the whole SQL statement has been processed. Until InnoDB implements deferred constraint checking, some things will be impossible, such as deleting a record that refers to itself via a foreign key.

Here is a simple example that relates parent and child tables through a singlecolumn foreign key:

CREATE TABLE parent (id INT NOT NULL, PRIMARY KEY (id) ) TYPE=INNODB; CREATE TABLE child (id INT, parent_id INT, INDEX par_ind (parent_id), FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE ) TYPE=INNODB; A more complex example in which a product_order table has foreign keys for two other tables. One foreign key references a two-column index in the product table. The other references a single-column index in the customer table:

CREATE TABLE product (category INT NOT NULL, id INT NOT NULL, price DECIMAL, PRIMARY KEY(category, id)) TYPE=INNODB; CREATE TABLE customer (id INT NOT NULL, PRIMARY KEY (id)) TYPE=INNODB;

CREATE TABLE product_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), FOREIGN KEY (product_category, product_id) REFERENCES product(category, id) ON UPDATE CASCADE ON DELETE RESTRICT, INDEX (customer_id), FOREIGN KEY (customer_id) REFERENCES customer(id)) TYPE=INNODB; Starting from MySQL 3.23.50, InnoDB allows you to add a new foreign key constraint to a table by using ALTER TABLE:

ALTER TABLE tbl_name ADD [CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...) REFERENCES tbl_name (index_col_name, ...) [ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION}] [ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION}] Remember to create the required indexes first. You can also add a self-referential foreign key constraint to a table using ALTER TABLE.

Starting from MySQL 4.0.13, InnoDB supports the use of ALTER TABLE to drop foreign keys:

ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol; If the FOREIGN KEY clause included a CONSTRAINT name when you created the foreign key, you can refer to that name to drop the foreign key. (A constraint name can be given as of MySQL 4.0.18.) Otherwise, the fk_symbol value is internally generated by InnoDB when the foreign key is created. To find out the symbol when you want to drop a foreign key, use the SHOW CREATE TABLE statement. For example:

mysql> SHOW CREATE TABLE ibtest11c\G *************************** 1. row *************************** Table: ibtest11c Create Table: CREATE TABLE `ibtest11c` ( `A` int(11) NOT NULL auto_increment, `D` int(11) NOT NULL default '0', `B` varchar(200) NOT NULL default '', `C` varchar(175) default NULL, PRIMARY KEY (`A`,`D`,`B`), KEY `B` (`B`,`C`), KEY `C` (`C`), CONSTRAINT `0_38775` FOREIGN KEY (`A`, `D`) REFERENCES `ibtest11a` (`A`, `D`) ON DELETE CASCADE ON UPDATE CASCADE,

CONSTRAINT `0_38776` FOREIGN KEY (`B`, `C`) REFERENCES `ibtest11a` (`B`, `C`) ON DELETE CASCADE ON UPDATE CASCADE ) TYPE=InnoDB CHARSET=latin1 1 row in set (0.01 sec)

mysql> ALTER TABLE ibtest11c DROP FOREIGN KEY `0_38775`; You cannot add a foreign key and drop a foreign key in separate clauses of a single ALTER TABLE statement. Separate statements are required.

Starting from MySQL 3.23.50, the InnoDB parser allows table and column identifiers in a FOREIGN KEY ... REFERENCES ... clause to be quoted within backticks. (Alternatively, double quotes can be used if the ANSI_QUOTES SQL mode is enabled.) The InnoDB parser also takes into account the setting of the lower_case_table_names system variable.

Before MySQL 3.23.50, ALTER TABLE or CREATE INDEX should not be used in connection with tables that have foreign key constraints or that are referenced in foreign key constraints: Any ALTER TABLE removes all foreign key constraints defined for the table. You should not use ALTER TABLE with the referenced table, either. Instead, use DROP TABLE and CREATE TABLE to modify the schema. When MySQL does an ALTER TABLE it may internally use RENAME TABLE, and that confuses the foreign key constraints that refer to the table. In MySQL, a CREATE INDEX statement is processed as an ALTER TABLE, so the same considerations apply.

Starting from MySQL 3.23.50, InnoDB returns the foreign key definitions of a table as part of the output of the SHOW CREATE TABLE statement:

SHOW CREATE TABLE tbl_name; mysqldump also produces correct definitions of tables to the dump file, and does not forget about the foreign keys.

You can also display the foreign key constraints for a table like this:

SHOW TABLE STATUS FROM db_name LIKE 'tbl_name'; The foreign key constraints are listed in the Comment column of the output.

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; the check is not deferred to transaction commit.

To make it easier to reload dump files for tables that have foreign key relationships, mysqldump automatically includes a statement in the dump output to set FOREIGN_KEY_CHECKS to 0 as of MySQL 4.1.1. This avoids problems with tables having to be reloaded in a particular order when the dump is reloaded. For earlier versions, you can disable the variable manually within mysql when loading the dump file like this:

mysql> SET FOREIGN_KEY_CHECKS = 0; mysql> SOURCE dump_file_name; mysql> SET FOREIGN_KEY_CHECKS = 1; This allows you to import the tables in any order if the dump file contains tables that are not correctly ordered for foreign keys. It also speeds up the import

operation. Setting FOREIGN_KEY_CHECKS to 0 can also be useful for ignoring foreign key constraints during LOAD DATA or ALTER TABLE operations. However, even if FOREIGN_KEY_CHECKS=0, InnoDB does not allow the creation of a foreign key constraint where a column references a non-matching column type. FOREIGN_KEY_CHECKS is available starting from MySQL 3.23.52 and 4.0.3.

InnoDB does not allow you to drop a table that is referenced by a FOREIGN KEY constraint, unless you do SET FOREIGN_KEY_CHECKS=0. When you drop a table, the constraints that were defined in its create statement are also dropped.

If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the right column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns error number 1005 and refers to errno 150 in the error message.

__________________________________________________________________ ____________________________________________ skywalker

Thai Developer Network Free online shopping cheap toy for sale cheap dirt bike for sale skate board on sale

6(424) ....... MySQL

http://www.thaiwbi.com/course/mysql/index2.html

__________________________________________________________________ ____________________________________________ skywalker

Thai Developer Network Free online shopping cheap toy for sale cheap dirt bike for sale skate board on sale

7(425) ....... SHOW INNODB STATUS

13.1.6. CREATE INDEX Syntax

CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name [index_type] ON tbl_name (index_col_name,...) [index_option ...]

index_col_name: col_name [(length)] [ASC | DESC]

index_type: USING {BTREE | HASH}

index_option: KEY_BLOCK_SIZE value | index_type | WITH PARSER parser_name Foreign keys definitions are subject to the following conditions:

Both tables must be InnoDB tables and they must not be TEMPORARY tables.

In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist.

In the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

Index prefixes on foreign key columns are not supported. One consequence of this is that BLOB and TEXT columns cannot be included in a foreign key, because indexes on those columns must always include a prefix length.

If the CONSTRAINT symbol clause is given, the symbol value must be unique in the database. If the clause is not given, InnoDB creates the name automatically.

__________________________________________________________________ ____________________________________________ skywalker

Thai Developer Network Free online shopping cheap toy for sale cheap dirt bike for sale skate board on sale

Vous aimerez peut-être aussi