python操作mysql数据库

Posted 战术鬼才

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python操作mysql数据库相关的知识,希望对你有一定的参考价值。

1.安装mysql

2.安装pymysql驱动 pip install pymysql  

3.创建一张数据表

CREATE TABLE `players` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(30) COLLATE utf8_bin NOT NULL,
    `club` VARCHAR(20) COLLATE utf8_bin NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1;

 

4.python操作mysql数据库

1). 添加数据

import pymysql

# 连接数据库
conn = pymysql.connect(
    host=127.0.0.1,
    port=3306,
    user=root,
    password=root,
    db=news,
    charset=utf8mb4,
    cursorclass=pymysql.cursors.DictCursor
    )

# 创建游标
cursor = conn.cursor()

# 创建SQL语句并执行
sql = "INSERT INTO `players` (`name`, `club`) VALUES (‘James‘, ‘Lakers‘), (‘Westbrook‘, ‘Thunder‘)"
cursor.execute(sql)

#提交sql
conn.commit()

其中host为数据库的主机IP地址,本地一般为‘127.0.0.1’, port为MySQL的默认端口号,一般为3306,user为数据的用户名,password为数据库的登录密码,db为数据库的名称。

cursor()方法创建数据库游标。

execute()方法执行SQL语句。

commit()将数据库的操作真正的提交到数据。

 

2)查询数据

import pymysql

# 连接数据库
conn = pymysql.connect(
    host=127.0.0.1,
    port=3306,
    user=root,
    password=root,
    db=news,
    charset=utf8mb4,
    cursorclass=pymysql.cursors.DictCursor
    )

# 创建游标
cursor = conn.cursor()

# 创建SQL语句并执行
sql = "SELECT `name`, `club` FROM `players` WHERE `id`=‘1‘"
cursor.execute(sql)

#单条语句查询
rest = cursor.fetchone()
print(rest)

print("---------我是分割线-------------")

# 创建SQL语句并执行
sql = "SELECT `name`, `club` FROM `players`"
cursor.execute(sql)

# 多条语句查询
rest = cursor.fetchall()
for item in rest:
    print(item)

执行结果:

{name: James, club: Lakers}
---------我是分割线-------------
{name: James, club: Lakers}
{name: Westbrook, club: Thunder}

 

以上是关于python操作mysql数据库的主要内容,如果未能解决你的问题,请参考以下文章

部分代码片段

在 Python代码中操作mysql数据

通过Python代码操作MySQL:

python 用于数据探索的Python代码片段(例如,在数据科学项目中)

如何在片段中填充列表视图?

用python操作mysql数据库(之代码归类)