之前的项目需要用Python操作Mysql数据库,本文就分享整理一些Python中操作Mysql的代码,包括Python中连接Mysql数据库,一次插入多条数据,一次接收返回的多条数据,多次接收返回的多条数据,获取返回数据的行数,以及获取数据库中的表信息。

1、Python连接Mysql

#!/usr/bin/env python
import  MySQLdb
print("Connecting...")
dbh=MySQLdb.conn(user="root",passwd="test",host="localhost",db="test")
print("Connection successful")
dbh.close()

2、一次插入多条数据

#!/usr/bin/env python
import MySQLdb
rows=(('2', 'two'),
           ('3', 'three'))
print("connecting...")
dbh= MySQLdb.connect (host="localhost" , user ="root" , passwd="test" , db="test")
print("connection successed")
cur =dbh.cursor()
query="insert into test values (%s,%s)"
for id in rows:
    cur.execute(query,i)
dbh.commit()
dbh.close()

3、一次接收返回的多条数据

#!/usr/bin env python
import MySQLdb
dbh=MySQLdb.connect (db="test" , user=" root" , passwd="test")
print("connection successful")
cur= dbh. cursor ()
cur.execute ("select * from test")
rows=cur.fetchall()
for i in rows:
    print(i)
dbh.close()

4、多次接收返回的数据

#!/usr/bin env python
import MySQLdb
dbh=MySQLdb.connect(db="test" , user="root", passwd="test")
print("connection successful")
cur=dbh.cursor()
cur.execute("select * from test")
cur.arraysize=2
while 1:
    rows=cur.fetchmany()
    print("%d results" % len(rows))
    if not len(rows) :
        break
    for i in rows:
        print(i)
dbh.close()

5、一次接一行数据

#!/usr/bin env python
import MySQLdb
dbh=MySQLdb.connect (db="test",user="root" ,passwd="test")
print("connection successful")
cur=dbh.cursor()
cur.execute("select * from test")
cur.arraysize=2
while 1:
    rows=cur.fetchone()
    if rows is None:
        break
    print(rows)
dbh.close()

6、返回数据行数

#!/usr/bin env python
import MySQLdb
dbh=MySQLdb.connect (db="test" , user="root" , passwd="test")
print("connection successful")
cur=dbh.cursor()
cur.execute("select * from test")
cur.fetchone()
print("%d" % cur.rowcount)
dbh.close()

7、返回获取表的描述信息

#!/usr/bin env python
import MySQLdb
dbh=MySQLdb.connect(db="test" , user="root" , passwd="test")
print("connection successful")
cur=dbh.cursor()
cur.execute("select * from test")
cur.arraysize=2
while 1 :
    rows= cur.fetchone()
    if rows is None:
        break
    print rows
for i in cur.description:
    name, type_code, display_size, internal_size, precision, scale,null_=ok=i
    print("Column name :" ,name)
    print("Type code",type_code)
    print("display_size",display_size)
dbh.close()

推荐文档