CentOS Python 安装MySQL-python

一。安装mysql

yum list | grep mysql

>>yum install -y mysql-server mysql mysql-devel

 CentOS 7的yum源中貌似没有正常安装mysql时的mysql-sever文件。须要去官网上下载

wget http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm

rpm -ivh mysql-community-release-el7-5.noarch.rpm

yum install mysql-community-server


安装成功之后重新启动mysql服务

service mysqld restart


设置开机启动

chkconfig mysqld on


初次安装mysql是root账户是没有password的

设置password的方法

# mysql -uroot
mysql> set password for ‘root’@‘localhost’ = password('mypasswd');
mysql> exit

二,安装MySQL-python

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

wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz

tar zxvf MySQL-python-1.2.3.tar.gz

 cd MySQL-python-1.2.3
$ python setup.py build
$ python setup.py install


三。測试

測试很easy,检查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的基本操作:

 

 第一次设置rootpassword能够使用下面命令:

1 mysqladmin -u root password NEWPASSWORD

假设你已经设置过password了。须要要下面命令:

1 mysqladmin -u root -p'oldpassword' password newpass

比方说,旧password是“12345”。新password是“nowamagic”。运行下面命令:

1 mysqladmin -u root -p'12345' password 'nowamagic'

四。mysql 的基本操作

 

$ mysql -u root -p  (有password时)

$ mysql -u root     (无password时)

 

复制代码
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() 方法用于创建数据库的连接,里面能够指定參数:username,password,主机等信息。

这仅仅是连接到了数据库,要想操作数据库须要创建游标。

 

>>> 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]
复制代码

 

原文地址:https://www.cnblogs.com/tlnshuju/p/7202199.html