MySQL基础语句与其在Python中的使用
2017-03-08 14:17
405 查看
一、MySQL基础语句
$ mysql -u root -p (有密码时)
$ mysql -u root (无密码时)
QUIT (or \q) 退出
二、MySQL在Python中的使用
1、安装好MySQL之后,要安装MySQL驱动
$ pip install mysql-connector-python --allow--external mysql-connector-python
如果上面的命令安装失败,可以试试另一个驱动:
$ pip install mysql-connector
2、 在Python中连接到MySQL服务器的test数据库
3、插入数据的更为方便的方法
4、查询数据
在cur.execute(“select * from student”) 并不能查询到表中的数据,只能返回数据条数。
需要用cur.fetchone( )方法或cur.fetchall( )方法来获取表中的数据
cur.fetchone( )每次只能获取一条数据,每执行一次,游标会移到下一条数据是位置;
cur.fetchall( )可以获取表中所有的数据
cur.scroll( 0, ‘absolute’ ) 方法可以将游标定位到表中的第一条数据。
$ 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 local infile “绝对路径” into table tb_test fields terminated by “,” lines terminated by “\r”(or “\n" or "\r\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; | |
删除一条记录 | delete from tb_test where name=“Tom”; | |
1、安装好MySQL之后,要安装MySQL驱动
$ pip install mysql-connector-python --allow--external mysql-connector-python
如果上面的命令安装失败,可以试试另一个驱动:
$ pip install mysql-connector
2、 在Python中连接到MySQL服务器的test数据库
3、插入数据的更为方便的方法
4、查询数据
在cur.execute(“select * from student”) 并不能查询到表中的数据,只能返回数据条数。
需要用cur.fetchone( )方法或cur.fetchall( )方法来获取表中的数据
cur.fetchone( )每次只能获取一条数据,每执行一次,游标会移到下一条数据是位置;
cur.fetchall( )可以获取表中所有的数据
cur.scroll( 0, ‘absolute’ ) 方法可以将游标定位到表中的第一条数据。
相关文章推荐
- mysql使用基础 sql语句与数据完整性(二)
- python使用变量操作mysql语句
- mysql使用基础 sql语句与数据完整性(二)
- python基础(六)——mysql的使用
- 数据库基础知识及MySQL语句的使用
- mysql使用基础 sql语句(一)
- python mysql插入语句使用dict快速
- python文件基础(4)--使用with语句
- 命令行使用MySql的入门基础语句
- mysql使用基础 sql语句(一)
- Python学习入门基础教程(learning Python)--1.2.1 Python输出语句print基本使用 .
- 老紫竹JAVA基础培训(6),For循环语句的使用
- mysql导出数据库表的创建sql语句(使用mysql control center/MYSQL-Front)
- VBScript基础教程之七使用条件语句
- Mysql中使用case语句
- [转] 在 MySQL 数据库中使用 C 执行 SQL语句
- mysql索引的使用及语句优化
- 使用Jmeter对Mysql进行压力测试无法执行多条sql语句问题
- 使用Python将数据从Access导入到MySQL
- Mysql的sql语句中使用判断语句遇到的问题