#!/usr/bin/python
#Program:
# insert data into mysql and the display them
import MySQLdb as mdb
conn = mdb.connect(host = 'localhost', user = 'root', passwd = '8023xue0526', db ='contact')
cur = conn.cursor()
cur.execute("insert into contact values('123221', 'ni')")
cur.execute("select * from contact")
row_num = int(cur.rowcount)
for i in range(row_num):
row = cur.fetchone()
print row
我使用这些代码将数据插入到 mysql 中,程序工作正常。但在那之后,我在mysqlclient中检查它,数据不存在。但是当我在 'cur = conn.cursor() 之前添加一个语句 'with conn:' 时,数据确实插入到了 mysql 中。像这样的代码
#!/usr/bin/python
#Program:
# to get some information from mysql
import MySQLdb as mdb
import sys
conn = mdb.connect(host = 'localhost', user = 'root', passwd = '8023xue0526', db = 'contact')
with conn:
cur = conn.cursor()
cur.execute("insert into contact values('122221', 'ni')")
cur.execute("select * from contact")
row_num = int(cur.rowcount)
for i in range(row_num):
row = cur.fetchone()
print row