提示:本文章详解python通过sqlite3模块操作MySQL的相关知识
在进行Python编程的时候,我们经常将一些数据保存起来,大家最常使用的是文本文件。但是,当保存的数据过大时,使用文本文件就会显得力不从心,因此我们选择使用数据库MySQL,那么如何让Python和MySQL进行交互呢?
MySQL是一个开放源代码的关系数据库管理系统。由于其性能高、成本低、可靠性好,被广泛应用在Internet上的中小型网站上。目前是甲骨文公司旗下产品。
代码如下:
mysql> create database mrsoft;
Query OK, 1 row affected (0.00 sec)
代码如下:
mysql> drop database mrsoft;
Query OK, 0 rows affected (0.00 sec)
代码如下:
mysql> alter database mrsoft charset=utf8;
Query OK, 1 row affected (0.00 sec)
代码如下:
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mrsoft |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)
代码如下:
mysql> use mrsoft
Database changed
语法:
CREATE TABLE IF NOT EXISTS table_name (column_name column_type)
mysql> create table if not exists stud01(
-> id int auto_increment primary key,//primary key就是主键
-> name varchar(20) not null,
-> age int,
-> address varchar(50) not null default '重庆',
-> score int
-> )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.03 sec)
语法:
DROP TABLE IF EXISTS table_name
mysql> show tables;
+------------------+
| Tables_in_mrsoft |
+------------------+
| stud01 |
| stud02 |
+------------------+
2 rows in set (0.00 sec)
mysql> drop table if exists stud01;
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+------------------+
| Tables_in_mrsoft |
+------------------+
| stud02 |
+------------------+
1 row in set (0.00 sec)
语法:
ALTER TABLE table_name RENAME AS new_table_name
mysql> show tables;
+------------------+
| Tables_in_mrsoft |
+------------------+
| stud01 |
+------------------+
1 row in set (0.00 sec)
mysql> alter table stud01 rename as stud02;
Query OK, 0 rows affected (0.00 sec)
mysql> show tables;
+------------------+
| Tables_in_mrsoft |
+------------------+
| stud02 |
+------------------+
1 row in set (0.00 sec)
2、修改数据表的属性(engine、charset等)
语法:
ALTER TABLE table_name ENGINE=INNODB;
mysql> alter table stud02 engine=innodb;
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
语法:
ALTER TABLE table_name ADD column_name column_type
mysql> alter table stud02 add male varchar(10);
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
2、删除数据表中的字段
语法:
ALTER TABLE table_name DROP column_name
mysql> alter table stud02 drop male;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
3、修改数据表中的字段(字段名和字段属性)
修改字段名语法:
ALTER TABLE table_name CHANGE column_name new_column_name column_type
mysql> alter table stud02 change male xingbie int;//这里可以同时修改字段名和字段属性
修改字段属性语法:
ALTER TABLE table_name MODIFY column_name column_type
mysql> alter table stud02 modify xingbie varchar(