python数据库-mysql

只愿长相守 提交于 2020-11-10 07:34:16

1 mysql

1.1 安装mysql

下载并安装MySQL,设置用户名root的密码为'password',便于记忆。 安装navicate,这是一款数据库的可视化软件。

1.2 使用powershell登陆mysql

在系统环境变量path中添加mysql的bin目录, 打开powershell命令行,输入mysql -u root -p,随后在powershell的密码输入提示处,输入root用户的密码。

1.3 数据库的操作

在powershell中登陆mysql后,显示mysql>,目前可以输入数据库操作指令了。

1.3.1 创建数据库

create database <数据库名>;

1.3.2 显示数据库

show databases;

1.3.3 删除数据库

drop database <数据库名>;

1.3.4 连接数据库

use database <数据库名>;

1.3.5 创建表

create table <表名> ( <字段名1> <类型1> [,..<字段名n> <类型n>]);

例如: create table myclass(id int(4), name char(20));

2 使用pymysql库的数据读写

pymsql是Python中操作MySQL的模块。

import pymysql

# 1、创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='password', db='db01', charset='utf8')
# 2、创建游标
cursor = conn.cursor()

# 3、执行SQL,并返回受影响的行数
sql = 'select * from price where close>10'
cursor.execute(sql)

# 4、提交,否则无法保存新建或者修改的数据
conn.commit()

# 5、获取查询的数据
row_1 = cursor.fetchone()
row_2 = cursor.fetchmany(10)
row_3 = cursor.fetchall()

# 6、关闭游标
cursor.close()

# 7、关闭连接
conn.close()

3 使用sqlalchemy库的数据读写

# 1、创建dataframe
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,(8,4)),index=list('abcdefgh'),columns=list('ABCD'))

# 2、写入数据
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://root:password@localhost:3306/db01?charset=utf8')
df.to_sql('normal',engine,schema='db01',if_exists='replace',index=False,index_label=False)

# 3、读取mysql中的数据为dataframe格式
sql_cmd = "SELECT * FROM normal"
df2 = pd.read_sql(sql=sql_cmd, con=engine)
print(type(df2))

to_sql()解析: xy: 指数据库中的表名

engine: 指连接数据库的引擎

schname: 指将导入的数据库名字

if_exists: 指添加方式:      append表示若表存在,把数据插入,若不存在则创建一个表插入数据;      fail表示若表存在,则啥也不做;      replace表示若表存在,则删了表,再重新建一个表掺入数据。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!