跟老齐学Python之使用Python操作数据库(1)(3)
mysql> select * from users;
+----+----------+----------+------------------+
| id | username | password | email |
+----+----------+----------+------------------+
| 1 | qiwsir | 123123 | qiwsir@gmail.com |
+----+----------+----------+------------------+
1 row in set (0.00 sec)
咦,奇怪呀。怎么没有看到增加的那一条呢?哪里错了?可是上面也没有报错呀。
在这里,特别请列位看官注意,通过"cur.execute()"对数据库进行操作之后,没有报错,完全正确,但是不等于数据就已经提交到数据库中了,还必须要用到"MySQLdb.connect"的一个属性:commit(),将数据提交上去,也就是进行了"cur.execute()"操作,要将数据提交,必须执行:
>>> conn.commit()
在到"mysql>"中运行"select * from users"试一试:
mysql> select * from users;
+----+----------+----------+------------------+
| id | username | password | email |
+----+----------+----------+------------------+
| 1 | qiwsir | 123123 | qiwsir@gmail.com |
| 2 | python | 123456 | python@gmail.com |
+----+----------+----------+------------------+
2 rows in set (0.00 sec)
good,very good。果然如此。这就如同编写一个文本一样,将文字写到文本上,并不等于文字已经保留在文本文件中了,必须执行"CTRL-S"才能保存。也就是在通过python操作数据库的时候,以"execute()"执行各种sql语句之后,要让已经执行的效果保存,必须运行"commit()",还要提醒,这个属性是"MySQLdb.connect()"实例的。
再尝试一下插入多条的那个命令"executemany(query,args)".
>>> cur.executemany("insert into users (username,password,email) values (%s,%s,%s)",(("google","111222","g@gmail.com"),("facebook","222333","f@face.book"),("github","333444","git@hub.com"),("docker","444555","doc@ker.com")))
4L
>>> conn.commit()
到"mysql>"里面看结果:
mysql> select * from users;
+----+----------+----------+------------------+
| id | username | password | email |
+----+----------+----------+------------------+
| 1 | qiwsir | 123123 | qiwsir@gmail.com |
| 2 | python | 123456 | python@gmail.com |
| 3 | google | 111222 | g@gmail.com |
| 4 | facebook | 222333 | f@face.book |
| 5 | github | 333444 | git@hub.com |
| 6 | docker | 444555 | doc@ker.com |
+----+----------+----------+------------------+
6 rows in set (0.00 sec)