Python连接远程及本地MySQL数据库
安装
pip install pymysql
实现代码
import pymysql
def insert(start, destination, dis):
db = pymysql.connect(host='YOUR_HOSTNAME',user='YOUR_USER_NAME',passwd='YOUR_PASSWORD',db='YOUR_DATABASE_NAME',port=1024,charset='utf8')
cursor = db.cursor()
try:
sql = ('INSERT INTO distance() VALUES(%s ,%s, %s)')
cursor.execute(sql,(start, destination, dis))
db.commit()
except pymysql.Error as e:
print(e)
print('Operate the database failed!')
insert("start", "destination", 1024)
简介
- 注意
上述实现需要先在数据库中创建表,或者修改insert中的语句创建
- 使用
pymysql.connect语句中需要修改对应语句的参数,依次为远程主机名(外网IP,连接本机即为"localhost"),数据库用户名,用户密码,数据库名,端口号(整型),charset默认为"utf8"
- MySQL语句
修改insert方法中的MySQL语句可以实现MySQL语句对数据库进行操作,在此不再赘述
最后
- 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!