python3连接mysql

本文提供了使用PyMySQL库连接数据库的示例代码,包括macOS和Windows环境下如何配置连接参数及执行基本查询。

1. 安装PyMysql;

2.mac版如下:

 1 # -*- coding: utf-8 -*-
 2 import pymysql
 3 # 密码我用*打马赛克啦 哇哈哈
 4 conn = pymysql.connect(host = '127.0.0.1', unix_socket = '/tmp/mysql.sock', user = 'root' , password = '******', db = 'mysql', charset = 'utf8s')
 5 cur = conn.cursor()
 6 cur.execute("USE mysql")
 7 
 8 cur.execute("select * from user")
 9 print(cur.fetchone())
10 cur.close()
11 conn.close()

3. windows版如下:

注意事项:1.port后面写int而不是str;

     2.添加charset='utf8'以保证查出的中文字符能正常显示;

 1 # -*- coding: utf-8 -*-
 2 import pymysql
 3 
 4 conn = pymysql.connect(host = 'XXXXXX', port = 1234, user = '****' , password = '*****', db = 'xxxx', charset = 'utf8')
 5 cur = conn.cursor()
 6 cur.execute("USE xxxx")
 7 
 8 cur.execute("SELECT * from  xxxx where id = 1039")
 9 print(cur.fetchone())
10 cur.close()
11 conn.close()

 

转载于:https://www.cnblogs.com/vivivi/p/5961972.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值