python连接mysql数据库

1、安装pymysql
打开cmd输入pip install pymysql

PyMySQL是从Python连接到MySQL数据库服务器的接口。

PyMySQL参考文档:http://pymysql.readthedocs.io/

2、安装MySQL
windows安装包下载:https://dev.mysql.com/downloads/windows/installer/
或百度网盘下载:链接:https://pan.baidu.com/s/18Je7uaS4KaCgtpUN4jop9A
提取码:9xqn
在这里插入图片描述
在设置root管理员密码是默认设置为123456
安装过程全点下一步就行

3、安装一个管理MySQL的工具(可以选择不安装)
下载地址链接:https://pan.baidu.com/s/1YiytCbhM17zrH7cu2zXhEg 提取码:7gvb

破解过程参考:https://www.jianshu.com/p/46ea86e099d2
简单说,
名称:ddooo;
证书秘钥:8d8120df-a5c3-4989-8f47-5afc79c56e7c
注册时输入这两就行

sqlyog问题:
1、连接数据库时,报 “ Plugin caching——sha2_passward could not be loaded:******** ”这样的错误。
将报错信息翻译过来就是:“插件缓存——sha2_密码无法进行加载”,这是由于你的SQLyog mysql 密码加密方法变了,SQLyog未能正确解析使用。
解决方法参考https://jingyan.baidu.com/article/7908e85cda0de1af481ad22c.html
简单说,就是管理员方式打开cmd登录MySQL执行一句ALTER USER ‘root’@‘localhost’ IDENTIFIED WITH mysql_native_password BY ‘123456’;
执行该命令的前提是给MySQL配置了环境变量。配环境变量自行百度

4、连接数据库
完成1、2步骤,连接数据的前提条件算是准备完成了(我默认你已经安装了Python)。

连接

# -*- coding: utf-8 -*-

import pymysql
 
# Open database connection 打开数据库连接
db = pymysql.connect("localhost","root","123456","xzh_student" )
 
# prepare a cursor object using cursor() method  获得一个光标对象
cursor = db.cursor()
 
# execute SQL query using execute() method. 使用 execute()方法进行SQL查询
cursor.execute("SELECT VERSION()")
 
# Fetch a single row using fetchone() method. 使用fetchone() 抓取得到一行数据
data = cursor.fetchone()
 
print ("Database version : %s " % data)
 
# disconnect from server  与服务器断开连接
db.close()

创建一张数据库表

# -*- coding: utf-8 -*-
 
import pymysql
 
# Open database connection
db = pymysql.connect("localhost","root","123456","xzh_student" )
 
# prepare a cursor object using cursor() method
cursor = db.cursor()
 
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS employee")
 
# Create table as per requirement
sql = """CREATE TABLE `employee` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `first_name` char(20) NOT NULL,
  `last_name` char(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` char(1) DEFAULT NULL,
  `income` float DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
 
cursor.execute(sql)
print("Created table Successfull.")
# disconnect from server
db.close()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值