python操作mysql

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python操作mysql相关的知识,希望对你有一定的参考价值。

功能:通过python操作mysql数据库

1.安装MySQL-python

要想使python可以操作mysql 就需要MySQL-python驱动,它是python 操作mysql必不可少的模块。

下载地址:https://pypi.python.org/pypi/MySQL-python/

下载后安装就行了

检测是否安装通过import MySQLdb查看,如何没有安装成功,就会报错。

安装成功,导入没有提示的。

2.MYSQ的基本操作

回顾下mysql基本操作

0.产看mysql信息                    status;
1.整个命令写错                                  可以在后面输入 \\c 取消执行
2.单行命令写错                                  可以按esc键清除某行
3.给某个数据库创建单独管理员和密码        grant all on houdunwang.* to "hdw"@"localhost" identified by "hdw";
4.创建数据库                                    cerate database houdunwang;
                        create database hd default character set utf8;//指定字符集
5.删除数据库                    drop database houdunwang;
6.创建数据表                    create table students(id int(10) primary key auto_increment,name varchar(30),age tinyint(2));
                        create table user(id int(10) unsigned primary key auto_increment,name varchar(60),age tinyint(2)) default character
                        set utf8;//指定字符集

7.查看所有数据表                show tables;
8.查看指定数据表                desc students;

9.增                        insert into students (name,age) values("zhansan",22);


10.导出数据库(先退出数据库)            C:\\Users\\Admin>mysqldump -uroot -p houdunwang>d:/houdunwang.sql    
11.删除数据表                    drop table students;
12.导入数据库                    C:\\Users\\Admin>mysql -uroot -p houdunwang < d:/houdunwang.sql
13.执行外部的sql语句(先选择一个数据库)    source d:/houdunwang.sql;

3.通过python操作

数据库中写入数据
import
MySQLdb conn = MySQLdb.connect("localhost","root","root","hd") #连接数据库 cur=conn.cursor()  #创建游标 cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))") cur.execute("insert into student values(‘2‘,‘Tom‘,‘3 year 2 class‘,‘9‘)") cur.close() conn.commit() conn.close()

技术分享

数据库中遍历数据
import
MySQLdb conn = MySQLdb.connect("localhost","root","root","hd") cur=conn.cursor() #cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))") #cur.execute("insert into student values(‘2‘,‘Tom‘,‘3 year 2 class‘,‘9‘)") res=cur.execute("select * from student") print res info = cur.fetchmany(res) for i in info: print i cur.close() conn.commit() conn.close()

技术分享



以上是关于python操作mysql的主要内容,如果未能解决你的问题,请参考以下文章

部分代码片段

Python操作Mysql实例代码教程在线版(查询手册)_python

常用python日期日志获取内容循环的代码片段

linux中怎么查看mysql数据库版本

python 有用的Python代码片段

Python 向 Postman 请求代码片段