#链接mysql
#插入数据
Import MySQLdb
conn = MySQLdb.connect (host = ' 127.0.0.1 ', user = ' root ', passwd = ' ', db = ' mytest ')
cur = conn.cursor ()
Reconn = Cur.execute ("INSERT into UserInfo (id,name) value (3, ' Tony ')")
Conn.commit ()
Cur.close ()
Conn.close ()
Print Reconn
#查询数据
Import MySQLdb
conn = MySQLdb.connect (host = ' 127.0.0.1 ', user = ' root ', passwd = ' ', db = ' mytest ')
cur = conn.cursor (cursorclass=mysqldb.cursors.dictcursor) #以字典形式获取数据
cur = conn.cursor () #以元组形式获取数据
#reConn = Cur.execute ("SELECT * from UserInfo")
sql = "SELECT name from userinfo where id =%s"
#sql = "SELECT ID from userinfo where id =%s"
params = 1
#params = ' Dendi '
#reConn = Cur.execute (sql,params)
Reconn = Cur.execute ("SELECT * from UserInfo")
#fetchall把查找到的数据一下拿出来
#fetchone逐个取数据
# data = Cur.fetchall ()
data = Cur.fetchone ()
Print data
data = Cur.fetchone ()
Print data
Cur.close ()
Conn.close ()
# Print Data
Print Reconn
#更新数据
Import MySQLdb
conn = MySQLdb.connect (host = ' 127.0.0.1 ', user = ' root ', passwd = ' ', db = ' mytest ')
cur = conn.cursor ()
sql = "Update userinfo set name = ' AAA ' WHERE id = '%s '"
params = 1
Reconn = Cur.execute (sql,params)
Conn.commit ()
#conn. Rollback ()
Cur.close ()
Conn.close ()
Print Reconn
#删除数据
Import MySQLdb
conn = MySQLdb.connect (host = ' 127.0.0.1 ', user = ' root ', passwd = ' ', db = ' mytest ')
cur = conn.cursor ()
sql = "Delete from userinfo where id = '%s '"
params = 1
Reconn = Cur.execute (sql,params)
Conn.commit ()
#conn. Rollback ()
Cur.close ()
Conn.close ()
Print Reconn
Reference Blog: http://www.cnblogs.com/wupeiqi/articles/4198124.html
Python MySQL basic operation