Module installation
| 12345 |
linux: yum install MySQL-python windows:(如果报错需要执行license.py) Http://files.cnblogs.com/files/daliangtou/py-mysql-win.zip |
API Action 1, insert data 1.1 insert a piece of data
| 12345678910111213141516 |
import MySQLdb conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘123‘,db=‘mydb‘)cur = conn.cursor() #打开游标reCount = cur.execute( ‘insert into UserInfo(Name,Address) values(%s,%s)‘, (‘test‘,‘beijing‘)) #与字符串格式化不一样,mysql只有%s,没有别的,数字什么的也都用%s# reCount = cur.execute(‘insert into UserInfo(id,Name) values(%(id)s, %(name)s)‘,{‘id‘:12345,‘name‘:‘test1‘})cur.lastrowid() #获取新插入的数据的自增IDconn.commit()cur.close()conn.close()print reCount #在数据库中影响的行数 |
1.2 Inserting more than one data
| 1234567891011121314151617 |
import MySQLdbconn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘123‘,db=‘mydb‘)cur = conn.cursor()li =[ (‘test1‘,‘usa‘), (‘test2‘,‘china‘),]reCount = cur.executemany(‘insert into UserInfo(Name,Address) values(%s,%s)‘,li)conn.commit()cur.close()conn.close()print reCount |
2. Delete data
| 1234567891011121314 |
import MySQLdb conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘mydb‘) cur = conn.cursor() reCount = cur.execute(‘delete from UserInfo‘) conn.commit() cur.close()conn.close() print reCount |
3. Modify the data
| 12345678910111213 |
import MySQLdb conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘mydb‘) cur = conn.cursor() reCount = cur.execute(‘update UserInfo set Name = %s‘,(‘alin‘,)) conn.commit()cur.close()conn.close() print reCount |
4. Check the data
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
# ############################## fetchone/fetchmany(num) ############################## import MySQLdb conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘mydb‘)cur = conn.cursor() reCount = cur.execute(‘select * from UserInfo‘) print cur.fetchone()print cur.fetchone()cur.scroll(-1,mode=‘relative‘) #‘-’号代表当前行位置往回移动,正值是向下移动。print cur.fetchone()print cur.fetchone()cur.scroll(0,mode=‘absolute‘) #absolute是绝对位置,这行代码的意思是,指向获取结构所有开头的0行位置。print cur.fetchone() #获取的还是第一行的数据print cur.fetchone() cur.close()conn.close() print reCount # ############################## fetchall ############################## import MySQLdb conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘mydb‘)#cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) #结果是列表包含字典cur = conn.cursor() reCount = cur.execute(‘select Name,Address from UserInfo‘) nRet = cur.fetchall() #获取值是序列包含序列,如默认是列表包含元组,列表包含字典 cur.close()conn.close() print reCountprint nRetfor i in nRet: print i[0],i[1] |
From for notes (Wiz)
Mysql-python Module