python使用mysql数据库

 

Python使用MySQL数据库(新)

 

一,安装mysqlhtml

 

若是是windows 用户,mysql 的安装很是简单,直接下载安装文件,双击安装文件一步一步进行操做便可。python

Linux 下的安装可能会更加简单,除了下载安装包进行安装外,通常的linux 仓库中都会有mysql ,咱们只须要经过一个命令就能够下载安装:mysql

Ubuntu\deepinlinux

>>sudo apt-get install mysql-server sql

>>Sudo apt-get install  mysql-clientshell

centOS/redhat数据库

>>yum install mysqlwindows

 

二,安装MySQL-pythonpost

要想使python能够操做mysql 就须要MySQL-python驱动,它是python 操做mysql必不可少的模块。测试

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

下载MySQL-python-1.2.5.zip 文件以后直接解压。进入MySQL-python-1.2.5目录:

>>python setup.py install

 

三,测试

测试很是简单,检查MySQLdb 模块是否能够正常导入。

 

fnngj@fnngj-H24X:~/pyse$ python 
Python 2.7.4 (default, Sep 26 2013, 03:20:56) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb

 

没有报错提示MySQLdb模块找不到,说明安装OK ,下面开始使用python 操做数据库以前,咱们有必要来回顾一下mysql的基本操做:

 

 

四,mysql 的基本操做

 

$ mysql -u root -p  (有密码时)

$ mysql -u root     (无密码时)

 

mysql> show databases;  // 查看当前全部的数据库
+--------------------+
| Database           |
+--------------------+
| information_schema |
| csvt               |
| csvt04             |
| mysql              |
| performance_schema |
| test               |
+--------------------+
6 rows in set (0.18 sec)

mysql> use test;   //做用与test数据库
Database changed
mysql> show tables;   //查看test库下面的表
Empty set (0.00 sec)

//建立user表,name 和password 两个字段
mysql> CREATE  TABLE  user (name VARCHAR(20),password VARCHAR(20));  Query OK, 0 rows affected (0.27 sec)

//向user表内插入若干条数据
mysql> insert into user values('Tom','1321');
Query OK, 1 row affected (0.05 sec)

mysql> insert into user values('Alen','7875');
Query OK, 1 row affected (0.08 sec)

mysql> insert into user values('Jack','7455');
Query OK, 1 row affected (0.04 sec)

//查看user表的数据
mysql> select * from user;
+------+----------+
| name | password |
+------+----------+
| Tom  | 1321     |
| Alen | 7875     |
| Jack | 7455     |
+------+----------+
3 rows in set (0.01 sec)

//删除name 等于Jack的数据
mysql> delete from user where name = 'Jack';
Query OK, 1 rows affected (0.06 sec)

//修改name等于Alen 的password 为 1111
mysql> update user set password='1111' where name = 'Alen';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1  Changed: 1  Warnings: 0

//查看表内容
mysql> select * from user;
+--------+----------+
| name   | password |
+--------+----------+
| Tom    | 1321     |
| Alen   | 1111     |
+--------+----------+
3 rows in set (0.00 sec)

 

 

 

五,python 操做mysql数据库基础

#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
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.execute("update student set class='3 year 1 class' where name = 'Tom'")

#删除查询条件的数据
#cur.execute("delete from student where age='9'")

cur.close()
conn.commit()
conn.close()

>>> conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='123456',db ='test',)

Connect() 方法用于建立数据库的链接,里面能够指定参数:用户名,密码,主机等信息。

这只是链接到了数据库,要想操做数据库须要建立游标。

 

>>> cur = conn.cursor()

经过获取到的数据库链接conn下的cursor()方法来建立游标。

 

>>> cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")

经过游标cur 操做execute()方法能够写入纯sql语句。经过execute()方法中写如sql语句来对数据进行操做。

 

>>>cur.close()

cur.close() 关闭游标

>>>conn.commit()

conn.commit()方法在提交事物,在向数据库插入一条数据时必需要有这个方法,不然数据不会被真正的插入。

>>>conn.close()

Conn.close()关闭数据库链接

 

 

六,插入数据

 

经过上面execute()方法中写入纯的sql语句来插入数据并不方便。如:

>>>cur.execute("insert into student values('2','Tom','3 year 2 class','9')")

我要想插入新的数据,必需要对这条语句中的值作修改。咱们能够作以下修改:

#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#插入一条数据
sqli="insert into student values(%s,%s,%s,%s)"
cur.execute(sqli,('3','Huhu','2 year 1 class','7'))

cur.close()
conn.commit()
conn.close()

 

假如要一次向数据表中插入多条值呢?

#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#一次插入多条记录
sqli="insert into student values(%s,%s,%s,%s)"
cur.executemany(sqli,[
    ('3','Tom','1 year 1 class','6'),
    ('3','Jack','2 year 1 class','7'),
    ('3','Yaheng','2 year 2 class','7'),
    ])

cur.close()
conn.commit()
conn.close()

executemany()方法能够一次插入多条值,执行单挑sql语句,可是重复执行参数列表里的参数,返回值为受影响的行数。

 

 

七,查询数据

 

也许你已经尝试了在python中经过

>>>cur.execute("select * from student")

来查询数据表中的数据,但它并无把表中的数据打印出来,有些失望。

来看看这条语句得到的是什么

>>>aa=cur.execute("select * from student")

>>>print aa

5

它得到的只是咱们的表中有多少条数据。那怎样才能得到表中的数据呢?进入python shell

 

>>> import MySQLdb
>>> conn = MySQLdb.connect(host='localhost',port = 3306,user='root',    passwd='123456',db ='test',)
>>> cur = conn.cursor()
>>> cur.execute("select * from student")
5L
>>> cur.fetchone()
(1L, 'Alen', '1 year 2 class', '6')
>>> cur.fetchone()
(3L, 'Huhu', '2 year 1 class', '7')
>>> cur.fetchone()
(3L, 'Tom', '1 year 1 class', '6')
...
>>>cur.scroll(0,'absolute') 

 

  fetchone()方法能够帮助咱们得到表中的数据,但是每次执行cur.fetchone() 得到的数据都不同,换句话说我没执行一次,游标会从表中的第一条数据移动到下一条数据的位置,因此,我再次执行的时候获得的是第二条数据。

  scroll(0,'absolute') 方法能够将游标定位到表中的第一条数据。

 

仍是没解决咱们想要的结果,如何得到表中的多条数据并打印出来呢?

#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='123456',
        db ='test',
        )
cur = conn.cursor()

#得到表中有多少条数据
aa=cur.execute("select * from student")
print aa

#打印表中的多少数据
info = cur.fetchmany(aa)
for ii in info:
    print ii
cur.close()
conn.commit()
conn.close()

  经过以前的print aa 咱们知道当前的表中有5条数据,fetchmany()方法能够得到多条数据,但须要指定数据的条数,经过一个for循环就能够把多条数据打印出啦!执行结果以下:

 

5
(1L, 'Alen', '1 year 2 class', '6')
(3L, 'Huhu', '2 year 1 class', '7')
(3L, 'Tom', '1 year 1 class', '6')
(3L, 'Jack', '2 year 1 class', '7')
(3L, 'Yaheng', '2 year 2 class', '7')
[Finished in 0.1s]
相关文章
相关标签/搜索