Python-连接mysql数据库

更多方法参考原博。

1.安装pymysql模块   pip install pymysql

2.连接数据库:账号、密码、ip、端口号、数据库

3.建立游标

4.执行sql

5.获取结果

6.关闭游标

7.关闭连接

import pymysql
coon = pymysql.connect(
    host = '127.0.0.1',user = 'root',passwd = '123456',
    port = 3306,db = 'mydb',charset = 'utf8'
    #port必须写int类型
    #charset必须写utf8,不能写utf-8
)
cur = coon.cursor()  #建立游标
cur.execute("select * from stu")  #查询数据
res = cur.fetchall()    #获取结果
print(res)
cur.close()     #关闭游标
coon.close()    #关闭连接
---------------------------------------------------------------------------
#如果是插入数据,则要commit一下,把第9行换成以下两行
cur.execute('insert into stu(name,sex) VALUE ("pzp","man");')
coon.commit()

封装成一个函数 

def my_db(host,user,passwd,db,sql,port= 3306,charset = 'utf8'):
    import pymysql
    coon = pymysql.connect(host=host,
                           port=port,
                           user=user,
                           passwd = passwd,
                           db = db,
                           charset = charset
                           )
    cur = coon.cursor()
    cur.execute(sql)
    if sql.strip()[:6].upper() == 'SELECT':
        res = cur.fetchall()
    else:
        coon.commit()
        res = 'ok'
    cur.close()
    coon.close()
    return res

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值