操作数据库

1.操作数据库
#1、连上数据库 ip 账号密码 端口号 数据库
#2、执行sql
#3、获取到结果
import pymysql
coon = pymysql.connect(host='111.22.3.49',user='je',password='123456',
port=3306,db='je',charset='utf8',autocommit=True)
cur = coon.cursor() #建立游标(类似于文件指针)
cur.execute('select * from nhy;') #执行sql语句,它只是帮你执行sql语句,不会给你返回数据
sql = 'insert into nhy (name,pwd) value ("xiaobai","1234567");'
cur.execute(sql)
cur.execute('select * from nhy where name="xiaobai";')
print(cur.fetchall()) #获取查询到的所有结果(返回结果为二维元组)
print(cur.fetchone()) #只获取一条
print(cur.fetchmany(2)) #指定获取几条
cur.close() #游标关闭
coon.close() #连接关闭
注:
autocommit = True 定义该参数,会自动提交,不加的话需手动添加coon.commit()

定义数据库连接函数:
def my_db(ip,user,passwd,db,sql,port=3306,charset='utf8'):
coon = pymysql.connect(host=ip,user=user,
password=passwd,db=db,
port=port,charset=charset,autocommit=True)
cur = coon.cursor()
sql=sql.strip()
cur.execute(sql)
sql_start = sql[:6].lower() #取sql的开头,转成小写
if sql_start.startswith('select') or sql_start.startswith('show'):
data = cur.fetchall()
else:
data = 'ok'
cur.close()
coon.close()
return data

posted on 2018-07-09 21:50  DAMAER  阅读(162)  评论(0编辑  收藏  举报

导航