python 操作mysql

#!_*_coding:utf-8_*_
#__author__:"Alex huang"

import pymysql #得安装pymysql模块
data = [  #要批量插入的行
    (1,'a'),
    (2,'b'),
    (3,'c'),
]
conn = pymysql.connect(host='192.168.80.100',port=3306,user='hrg',password='123',db='test')
cur = conn.cursor()  #实例化一个游标,所有的操作都是通过它的,或者conn

a = cur.execute("show global variables") #中间直接写sql原生语句就行了,执行后用fetch显示,只能执行单条sql语句
print(cur.fetchone())  #获取一条执行结果
print(cur.fetchmany(2))  #获取N条结果
print(cur.fetchall())   #获取所有结果

cur.execute("create table tb2(id int,name char(20))")  #创建表不需要commit
cur.executemany("insert tb2(id,name) value(%s,%s)",data)  #数据是在一个事务中,需要commit才写到文件中
conn.commit()
conn.close()

  ...

猜你喜欢

转载自www.cnblogs.com/alex-hrg/p/9119390.html