Python 2 和 Python 3 操作 MySQL 数据库实现创建表删除表增删改查操作

Posted 魏晓蕾

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 2 和 Python 3 操作 MySQL 数据库实现创建表删除表增删改查操作相关的知识,希望对你有一定的参考价值。

1、mysql数据库和表的编码格式

(1)创建数据库并指定字符集

mysql> create database testpythondb character set utf8;
Query OK, 1 row affected, 1 warning (0.60 sec)

(2)查看数据库的编码格式

mysql> show variables like 'character_set_database';
+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| character_set_database | utf8  |
+------------------------+-------+
1 row in set (0.10 sec)

(3)创建表并指定字符集

mysql> create table tb_books (
    -> id varchar(10) not null,
    -> name varchar(20) not null,
    -> author varchar(20) not null,
    -> price double not null) default charset = utf8;
Query OK, 0 rows affected, 1 warning (2.16 sec)

mysql> show tables;
+------------------------+
| Tables_in_testpythondb |
+------------------------+
| tb_books               |
+------------------------+
1 row in set (0.17 sec)

mysql> desc tb_books;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id     | varchar(10) | NO   |     | NULL    |       |
| name   | varchar(20) | NO   |     | NULL    |       |
| author | varchar(20) | NO   |     | NULL    |       |
| price  | double      | NO   |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.10 sec)

(4)查看数据表的编码格式

mysql> show create table tb_books;
+----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                          |
+----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tb_books | CREATE TABLE `tb_books` (
  `id` varchar(10) NOT NULL,
  `name` varchar(20) NOT NULL,
  `author` varchar(20) NOT NULL,
  `price` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.10 sec)

(5)修改数据库的编码格式

mysql> alter database testpythondb character set gbk;
Query OK, 1 row affected (0.17 sec)

mysql> show variables like 'character_set_database';
+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| character_set_database | gbk   |
+------------------------+-------+
1 row in set (0.06 sec)

(6)修改数据表的编码格式

mysql> alter table tb_books character set gbk;
Query OK, 0 rows affected (0.31 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table tb_books;
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                                                                  |
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tb_books | CREATE TABLE `tb_books` (
  `id` varchar(10) CHARACTER SET utf8 NOT NULL,
  `name` varchar(20) CHARACTER SET utf8 NOT NULL,
  `author` varchar(20) CHARACTER SET utf8 NOT NULL,
  `price` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=gbk |
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

(7)修改字段的编码格式

mysql> alter table tb_books change name bookname varchar(25) character set gbk not null;
Query OK, 0 rows affected, 1 warning (0.18 sec)
Records: 0  Duplicates: 0  Warnings: 1

mysql> desc tb_books;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | varchar(10) | NO   |     | NULL    |       |
| bookname | varchar(25) | NO   |     | NULL    |       |
| author   | varchar(20) | NO   |     | NULL    |       |
| price    | double      | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> show create table tb_books;
+----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                                                                                            |
+----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tb_books | CREATE TABLE `tb_books` (
  `id` varchar(10) CHARACTER SET utf8 NOT NULL,
  `bookname` varchar(25) CHARACTER SET gbk COLLATE gbk_chinese_ci NOT NULL,
  `author` varchar(20) CHARACTER SET utf8 NOT NULL,
  `price` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=gbk |
+----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

(8)添加表外键

mysql> create table tb_bookstore (
    -> storeid varchar(10) not null,
    -> storename varchar(20) not null,
    -> address varchar(50) not null);
Query OK, 0 rows affected (1.02 sec)

mysql> show tables;
+------------------------+
| Tables_in_testpythondb |
+------------------------+
| tb_books               |
| tb_bookstore           |
+------------------------+
2 rows in set (0.00 sec)

mysql> show create table tb_bookstore;
+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table        | Create Table                                                                                                                                                             |
+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tb_bookstore | CREATE TABLE `tb_bookstore` (
  `storeid` varchar(10) NOT NULL,
  `storename` varchar(20) NOT NULL,
  `address` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=gbk |
+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> alter table tb_bookstore add constraint idx_id primary key (storeid);
Query OK, 0 rows affected (1.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc tb_bookstore;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| storeid   | varchar(10) | NO   | PRI | NULL    |       |
| storename | varchar(20) | NO   |     | NULL    |       |
| address   | varchar(50) | NO   |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table tb_books add storeid varchar(10) not null;
Query OK, 0 rows affected (0.46 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc tb_books;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | varchar(10) | NO   |     | NULL    |       |
| bookname | varchar(25) | NO   |     | NULL    |       |
| author   | varchar(20) | NO   |     | NULL    |       |
| price    | double      | NO   |     | NULL    |       |
| storeid  | varchar(10) | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> alter table tb_books add constraint fk_book_store foreign key(storeid) references tb_bookstore(storeid);
Query OK, 0 rows affected (1.89 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc tb_books;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | varchar(10) | NO   |     | NULL    |       |
| bookname | varchar(25) | NO   |     | NULL    |       |
| author   | varchar(20) | NO   |     | NULL    |       |
| price    | double      | NO   |     | NULL    |       |
| storeid  | varchar(10) | NO   | MUL | NULL    |       |
+----------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> show create table tb_books;
+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                                                                                                                                                                                                                                                             |
+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tb_books | CREATE TABLE `tb_books` (
  `id` varchar(10) CHARACTER SET utf8 NOT NULL,
  `bookname` varchar(25) CHARACTER SET gbk COLLATE gbk_chinese_ci NOT NULL,
  `author` varchar(20) CHARACTER SET utf8 NOT NULL,
  `price` double NOT NULL,
  `storeid` varchar(10) NOT NULL,
  KEY `fk_book_store` (`storeid`),
  CONSTRAINT `fk_book_store` FOREIGN KEY (`storeid`) REFERENCES `tb_bookstore` (`storeid`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk |
+----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

(9)删除表外键

mysql> alter table tb_books drop foreign key fk_book_store;
Query OK, 0 rows affected (0.17 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table tb_books;
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                                                                                                                                                                 |
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tb_books | CREATE TABLE `tb_books` (
  `id` varchar(10) CHARACTER SET utf8 NOT NULL,
  `bookname` varchar(25) CHARACTER SET gbk COLLATE gbk_chinese_ci NOT NULL,
  `author` varchar(20) CHARACTER SET utf8 NOT NULL,
  `price` double NOT NULL,
  `storeid` varchar(10) NOT NULL,
  KEY `fk_book_store` (`storeid`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk |
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> desc tb_books;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | varchar(10) | NO   |     | NULL    |       |
| bookname | varchar(25) | NO   |     | NULL    |       |
| author   | varchar(20) | NO   |     | NULL    |       |
| price    | double      | NO   |     | NULL    |       |
| storeid  | varchar(10) | NO   | MUL | NULL    |       |
+----------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> alter table tb_books drop key fk_book_store;
Query OK, 0 rows affected (0.24 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc tb_books;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | varchar(10) | NO   |     | NULL    |       |
| bookname | varchar(25) | NO   |     | NULL    |       |
| author   | varchar(20) | NO   |     | NULL    |       |
| price    | double      | NO   |     | NULL    |       |
| storeid  | varchar(10) | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> show create table tb_books;
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                                                                                                                              |
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tb_books | CREATE TABLE `tb_books` (
  `id` varchar(10) CHARACTER SET utf8 NOT NULL,
  `bookname` varchar(25) CHARACTER SET gbk COLLATE gbk_chinese_ci NOT NULL,
  `author` varchar(20) CHARACTER SET utf8 NOT NULL,
  `price` double NOT NULL,
  `storeid` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=gbk |
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

(10)删除数据库

mysql> drop database testpythondb;
Query OK, 2 rows affected (0.62 sec)

2、PyCharm默认编码格式设置


3、Python 2 操作 MySQL 数据库

  • 安装MySQL-python-1.2.5.win32-py2.7.exe,下载地址:https://pypi.org/project/MySQL-python/#files
    在 Python 2.7 环境下,pip install mysql 报错,故只能安装MySQL-python程序。
  • 连接数据库
# coding=utf-8

import MySQLdb

connection = MySQLdb.connect(user='root', passwd='123456', db='testpythondb')
cursor = connection.cursor()
cursor.execute("SELECT VERSION()")
result = cursor.fetchone()

print "数据库版本:{}".format(result)

connection.close()

输出:

数据库版本:('5.7.35',)

Python 2.7 只能连接 MySQL 5.x 版本。
本机 MySQL 5.7.35 和 MySQL 8.0.21 版本切换方式:
修改注册表:Computer\\HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\MySQL\\ImagePath,编辑该文件,“G:\\Program Files\\mysql-5.7.35-win32\\bin\\mysqld” MySQL为MySQL 5.7.35版本,“E:\\Program Files\\mysql-8.0.21-winx64\\bin\\mysqld” MySQL为MySQL 8.0.21 版本。

  • 删除表、创建表
# coding=utf-8

import MySQLdb

connection = MySQLdb.connect(user='root', passwd='123456', db='testpythondb')
cursor = connection.cursor()

cursor.execute("DROP TABLE IF EXISTS tb_books")

sql = "create table tb_books (          \\
        id varchar(10) not null,        \\
        name varchar(20) not null,      \\
        author varchar(20) not null,    \\
        price double not null) default charset = utf8"

cursor.execute(sql)

connection.close()
mysql> show tables;
+------------------------+
| Tables_in_testpythondb |
+------------------------+
| tb_books               |
+------------------------+
1 row in set (0.00 sec)
  • INSERT操作
# coding=utf-8

# import sys
import MySQLdb

# reload(sys)
# sys.setdefaultencoding("utf-8")

connection = MySQLdb.connect(user='root', passwd='123456', db='testpythondb', charset='utf8')
cursor = connection.cursor()

sql1 = "insert into tb_books (id, name, author, price) values ('1', '呼啸山庄', '艾米莉·勃朗特', 80.5)"
sql2 = "insert into tb_books (id, name, author, price) values('%s', '%s', '%s', '%g')" % ("2", "老人与海", "欧内斯特·米勒尔·海明威", 88.2)

try:
    cursor.execute(sql1)
    cursor.execute(sql2)
    connection.commit()
except:
    connection.rollback()

connection.close()
mysql> select * from tb_books;
+----+--------------+------------------------------------+-------+
| id | name         | author                             | price |
+----+--------------+------------------------------------+-------+
| 1  | 呼啸山庄     | 艾米

以上是关于Python 2 和 Python 3 操作 MySQL 数据库实现创建表删除表增删改查操作的主要内容,如果未能解决你的问题,请参考以下文章

python集合

python集合

python集合

python中集合的特点和注意点?

Python中的枚举

python list 复制拷贝问题