Python + MySQL从入门到精通(三):数据库的连接、创建、删除操作

# 前期工作

(31条消息) Python + MySQL从入门到精通(一):安装MySQL_栗子002的博客-优快云博客

(31条消息) Python + MySQL从入门到精通(二):配置账户密码_栗子002的博客-优快云博客

1 使用MySQL内置客户端操作

(1)以管理员身份打开命令符提示窗空

 

(2)打开服务:net sart mysql57 (mysql57服务的创建操作查看:(31条消息) Python + MySQL从入门到精通(一):安装MySQL_栗子002的博客-优快云博客

(3)登录MySQL:mysql -u root -p

(4)查看当前所有的数据库:show databases;

(5)创建数据库:create database 数据库名 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

(6)删除数据库:drop database 数据库名

(7)进入数据(进入文件):use 数据库;

(8)查看数据库中的表:show tables;

2 使用Python代码对数据库进行操作

2.1 准备工作:安装pymysql包

方法1:在使用conda创建的python环境中直接安装pymysql包

需要提前安装Ananconda并创建了名为pytorch的环境

step1:打开Anaconda Prompt

  • step2:利用conda激活需要安装 pymysql包的环境

    • conda activate 环境名

  • step3:输入命令 pip install pymysql -i Simple Index

    • Simple Index是清华镜像源地址,加快包下载的速度

方法2:直接在pycharm中安装

 

2.2 数据库的创建、删除代码

import pymysql
#连接(注意自己定义的端口号、注意使用自己定义的端口号port和用户密码password)
conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',password='root123',charset="utf8")
cursor=conn.cursor()
#1.查看所有存在的数据库
#发送指令
cursor.execute("show databases")
#获取指令的结果
result=cursor.fetchall()#做查询通过fetchall接收查询到的数据
print(result)
#输出已有的数据库:(('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('testdb1',))
​
#2.创建数据库
#发送指令
cursor.execute("create database TestDB2 default charset utf8 collate utf8_general_ci")
conn.commit()#新增、删除、修改之类的操作需要commit()操作
​
#3.查看数据库
#发送指令cursor.execute("show databases")
result=cursor.fetchall()
print(result)
#创建成功数据库testdb2:(('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('testdb1',), ('testdb2',))
​
#4.删除数据库
cursor.execute("drop database TestDB2")
conn.commit()
​
#5.查看数据库#发送指令cursor.execute("show databases")
result=cursor.fetchall()
print(result)
#(('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('testdb1',))
​
#6.进入数据库,查看表
cursor.execute("use mysql")
cursor.execute("show tables")
result=cursor.fetchall()
print(result)#输出(('columns_priv',), ('db',), ('engine_cost',), ('event',), ('func',),……)
​
#关闭连接
cursor.close()
conn.close()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值