MySQL基础语句与其在Python中的使用

时间:2023-03-08 21:03:51


一、MySQL基础语句
$ mysql -u root -p (有密码时)
$ mysql -u root     (无密码时)
QUIT (or \q)  退出
查看当前所有数据库 show databases;  
创建数据库 create database db_test;  
作用于某数据库 use db_test;  
查看当前数据库下的所有表 show tables;  
创建表(字段1 属性1,字段2 属性2,… ) create table tb_test(name varchar(20), id varchar(20));  
向表中插入一条数据 insert into tb_test values(’Tom’, ‘1234’);  
向表中导入数据 load data infile “绝对路径” into table tb_test fields terminated by “,” lines terminated by “\r”(or \n) ; 许多时候,由于各种因素限制(如office版本问题),会导致导入数据不成功。可以先把xlsx之类的文件存成csv(这种文件类型是逗号分隔),再转换为txt,再利用该语句导入,成功率非常高。
查看表中的数据 select * from tb_test;  
获取特定行
select * from tb_test where name=’Tom’;
select * from tb_test where id > 1000;
select * from tb_test where name=’Tom’ and/or id > 1000;
 
获取特定列
select name from tb_test;
select distinct name from tb_test;
distinct: 相同结果只输出一次
排序
select name from tb_test order by name;
select name from tb_test order by name desc
desc: 降序排列,且只对紧邻产生影响。若不加desc则默认升序
修改一条数据的值 update tb_test set id=“2345” where name=’Tom’;  
修改表名 alter table tb_test rename to tb_test1;  
删除字段 alter table tb_test drop id;  
     

二、MySQL在Python中的使用
1、安装好MySQL之后,要安装MySQL驱动
$ pip install mysql-connector-python --allow--external mysql-connector-python
如果上面的命令安装失败,可以试试另一个驱动:
$ pip install mysql-connector
2、 在Python中连接到MySQL服务器的test数据库
MySQL基础语句与其在Python中的使用
3、插入数据的更为方便的方法
MySQL基础语句与其在Python中的使用
MySQL基础语句与其在Python中的使用
4、查询数据
在cur.execute(“select * from student”) 并不能查询到表中的数据,只能返回数据条数。
需要用cur.fetchone( )方法或cur.fetchall( )方法来获取表中的数据
cur.fetchone( )每次只能获取一条数据,每执行一次,游标会移到下一条数据是位置;
cur.fetchall( )可以获取表中所有的数据
cur.scroll( 0, ‘absolute’ ) 方法可以将游标定位到表中的第一条数据。

相关文章