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'}
原文地址:https://www.cnblogs.com/m-chen/p/10075735.html