MySQL-python模块
模块安装
1 2 3 4 5 | linux: yum install MySQL-python windows:(如果报错需要执行license.py) https://files.cnblogs.com/files/daliangtou/py-mysql-win.zip
|
API操作
1、插入数据
1.1 插入一条数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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() #获取新插入的数据的自增ID conn.commit() cur.close() conn.close() print reCount #在数据库中影响的行数 |
1.2 插入多条数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import MySQLdb conn = 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、删除数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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、修改数据
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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、查数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | # ############################## 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 reCount print nRet for i in nRet: print i[ 0 ],i[ 1 ] |