Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

database - Transactions not working for my MySQL DB

I'm using a MySQL DB for my site, which is hosted on a Linux shared server.

I wrote a test script which I run using 'mysql' to test if transactions are working ok. Running the script, I do not get any error, but the result of executing the scripts is as if transaction is not enabled.

I also made sure to grant ALL privileges to the admin MySQL user which runs the script.

In order to double check, I tried the same test script on PostgreSQL, and there - the result of the script indicated that transaction does work. So it's definitely something which is specific to MySQL.

The script runs on a simple table which I created as follows:

create table a ( id serial primary key);

Following is the test script:

delete from a;
set autocommit = 0;
start transaction;
insert into a(id) values(1);
rollback work;
select count(*) from a;

So the script makes sure the table is empty, Then it starts a transaction, insert a row and rollback the insert. As the "insert" is rolled back, the "select" should indicate that table contains 0 rows.

Running this on PostgreSQL:

$ psql db admin < test1
DELETE 0
START TRANSACTION
INSERT 0 1
ROLLBACK
count
-------
     0

This is the expected behavior, 0 rows in the table as the insert was rolled back.

Running the same on my MySQL DB:

$ mysql db -u admin < test1
count(*)
1

Having 1 row following the rollback indicate that the "insert" was not rolled back, just as in non-transaction mode.

As mentioned, admin is granted with ALL privileges to the DB.

Anything I've missed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Probably the table is created with the MyISAM storage engine as default. MyISAM storage engine doesnt support transactions.

Create table

CREATE TABLE a ( id SERIAL PRIMARY KEY) ENGINE = MYISAM;

Query

DELETE FROM a;
SET autocommit = 0;
START TRANSACTION;
INSERT INTO a(id) VALUES(1);
ROLLBACK WORK;
SELECT COUNT(*) FROM a;

Result

count(*)

     1

Making the table InnoDB

Query

ALTER TABLE a ENGINE=INNODB; 

Query

DELETE FROM a;
SET autocommit = 0;
START TRANSACTION;
INSERT INTO a(id) VALUES(1);
ROLLBACK WORK;
SELECT COUNT(*) FROM a;

Result

count(*)  
----------
         0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...