首页 > 代码库 > python连接mysql之pymysql模块
python连接mysql之pymysql模块
以下demo均以python2中的mysqldb模块
一、插入数据
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import MySQLdb conn = MySQLdb.connect(host = ‘127.0.0.1‘ ,user = ‘root‘ ,passwd = ‘1234‘ ,db = ‘mydb‘ ) cur = conn.cursor() reCount = cur.execute( ‘insert into UserInfo(Name,Address) values(%s,%s)‘ ,( ‘alex‘ , ‘usa‘ )) # reCount = cur.execute(‘insert into UserInfo(Name,Address) values(%(id)s, %(name)s)‘,{‘id‘:12345,‘name‘:‘wupeiqi‘}) conn.commit() cur.close() conn.close() print reCount |
import MySQLdbconn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘mydb‘)cur = conn.cursor()li =[ (‘alex‘,‘usa‘), (‘sb‘,‘usa‘),]reCount = cur.executemany(‘insert into UserInfo(Name,Address) values(%s,%s)‘,li)conn.commit()cur.close()conn.close()print reCount批量插入数据
二、删除数据
?
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 |
三、修改数据
?
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 |
四、查数据
?
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‘ ) 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 ] |
python连接mysql之pymysql模块
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。