python 链接mysql 原生语句 链接远程数据库

python 连接mysql 原生语句
本人 myslq 5.0 Python 3.7
pymysql 官方网站点击进入
安装 pymysql pip install PyMySQL
引入 import pymysql

链接mysql

import pymysql
connection = pymysql.connect(
	host='localhost',  # 连接的是本地数据库
	user='root',        # 自己的mysql用户名
	passwd='root',  # 自己的密码
	db='test',      # 数据库的名字
	charset='utf8mb4',     # 默认的编码方式:
	cursorclass=pymysql.cursors.DictCursor
)
cursor = connection.cursor()

查询语句
sql = "select * from user" cursor.execute(sql) result = cursor.fetchall() print(result)
结果

[{'u_id': 11, 'name': '自由', 'pwd': '202cb962ac59075b964b07152d234b70'}]
[Finished in 1.3s]

DOS 命令运行 查看

+------+------+----------------------------------+
| u_id | name | pwd                              |
+------+------+----------------------------------+
|   11 | 自由     | 202cb962ac59075b964b07152d234b70 |
+------+------+----------------------------------+
1 row in set (0.01 sec)

效果一致
添加语句

cursor = connection.cursor()
sql = "insert into user(name,pwd) values('python','akjnasknfoaslnflasn')"
result = cursor.execute(sql) 
connection.commit();
print(result)

返回 true
1 [Finished in 1.4s]
查看数据库是否添加

mysql> select * from user;
+------+--------+----------------------------------+
| u_id | name   | pwd                              |
+------+--------+----------------------------------+
|   11 | 自由       | 202cb962ac59075b964b07152d234b70 |
|   47 | python | akjnasknfoaslnflasn              |
|   48 | python | akjnasknfoaslnflasn              |
+------+--------+----------------------------------+
3 rows in set (0.00 sec)

OK

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值