python-MySQLdb学习

  1. 特别提示:在浏览本教程时,不要强行记忆。记住一点:在使用中学习。  

很久之前就像学习数据库了,但是一直仅仅在于想学而没有动手去学。今天再一次看到这个东西了,然后就复制粘贴了一些东西,作为学习过得见证。同时还可以作为复习资料,当自己再次遇到时首先是去看自己的笔记而不是去百度海量的资源(google暂时用不了,用公司的内网。)。

先上原地址:http://docs.pythontab.com/learnpython/230/

上面是python中文社区的一个入门教程,下面则是我复制粘贴的部分东西。

到目前为止,地球上有三种类型的数据:
关系型数据库:MySQL、Microsoft Access、SQL Server、Oracle、...
非关系型数据库:MongoDB、BigTable(Google)、...
键值数据库:Apache Cassandra(Facebook)、LevelDB(Google) ...

安装:
sudo apt-get install mysql-server
配置:
/etc/mysql/mysql.conf.d/mysqld.cnf 
修改bind使其能够远程访问
运行:
service mysqld start
$mysql -u root -p


设置Mysql中的root用户密码:
mysql> GRANT ALL PRIVILEGES ON *.* TO root@localhost IDENTIFIED BY "123456";
mysql> show databases;

python操作数据库的模块——python-MySQLdb
安装(源码):
1. https://pypi.python.org/pypi/MySQL-python/
2. sudo apt-get install build-essential python-dev libmysqlclient-dev
   sudo apt-get install python-MySQLdb
3. pip install mysql-python

使用数据库:import MySQLdb

链接数据库:
先创建一个数据库。
$ mysql -u root -p
Enter password:
mysql> create database qiwsirtest character set utf8;
Query OK, 1 row affected (0.00 sec)
# 建立的数据库qiwsirtest,编码为utf-8

>>> import MySQLdb
>>> conn = MySQLdb.connect(host="localhost",user="root",passwd="123123",db="qiwsirtest",port=3306,charset="utf8")

逐个解释上述命令的含义:
host:等号的后面应该填写mysql数据库的地址,因为就数据库就在本机上(也称作本地),所以使用localhost,注意引号。如果在其它的服务器上,这里应该填写ip地址。一般中小型的网站,数据库和程序都是在同一台服务器(计算机)上,就使用localhost了。
user:登录数据库的用户名,这里一般填写"root",还是要注意引号。当然,如果读者命名了别的用户名,数据库管理者提供了专有用户名,就更改为相应用户。但是,不同用户的权限可能不同,所以,在程序中,如果要操作数据库,还要注意所拥有的权限。在这里用root,就放心了,什么权限都有啦。不过,这样做,在大型系统中是应该避免的。
passwd:上述user账户对应的登录mysql的密码。我在上面的例子中用的密码是"123123"。不要忘记引号。
db:就是刚刚通create命令建立的数据库,我建立的数据库名字是"qiwsirtest",还是要注意引号。看官如果建立的数据库名字不是这个,就写自己所建数据库名字。
port:一般情况,mysql的默认端口是3306,当mysql被安装到服务器之后,为了能够允许网络访问,服务器(计算机)要提供一个访问端口给它。
charset:这个设置,在很多教程中都不写,结果在真正进行数据存储的时候,发现有乱码。这里我将qiwsirtest这个数据库的编码设置为utf-8格式,这样就允许存入汉字而无乱码了。注意,在mysql设置中,utf-8写成utf8,没有中间的横线。但是在python文件开头和其它地方设置编码格式的时候,要写成utf-8。切记!

注:connect中的host、user、passwd等可以不写,只有在写的时候按照host、user、passwd、db(可以不写)、port顺序写就可以,端口号port=3306还是不要省略的为好,如果没有db在port前面,直接写3306会报错.

MySQL官方文档:http://mysql-python.sourceforge.net/MySQLdb.html

数据库模型:
username password email
qiwsir 123123 qiwsir@gmail.com

mysql> use qiwsirtest;
Database changed
mysql> show tables;  # 显示数据库中是否有数据表
Empty set (0.00 sec)

# 创建数据表
mysql> create table users(id int(2) not null primary key auto_increment,username varchar(40),password text,email text)default charset=utf8;
Query OK, 0 rows affected (0.12 sec)
# 查询显示,在qiwsirtest这个数据库中,已经有一个表,它的名字是:users。
mysql> show tables;
+----------------------+
| Tables_in_qiwsirtest |
+----------------------+
| users                |
+----------------------+
1 row in set (0.00 sec)

# 显示表users的结构:
mysql> desc users;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(2)      | NO   | PRI | NULL    | auto_increment |
| username | varchar(40) | YES  |     | NULL    |                |
| password | text        | YES  |     | NULL    |                |
| email    | text        | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

# 查询表格
mysql> select * from users;
Empty set (0.01 sec)

# 插入信息
mysql> insert into users(username,password,email) values("qiwsir","123123","qiwsir@gmail.com");
Query OK, 1 row affected (0.05 sec)

mysql> select * from users;
+----+----------+----------+------------------+
| id | username | password | email            |
+----+----------+----------+------------------+
|  1 | qiwsir   | 123123   | qiwsir@gmail.com |
+----+----------+----------+------------------+
1 row in set (0.00 sec)

python操作数据库:
链接数据库
>>> import MySQLdb
>>> conn = MySQLdb.connect(host="localhost",user="root",passwd="123123",db="qiwsirtest",charset="utf8")

常用方法:
commit():如果数据库表进行了修改,提交保存当前的数据。当然,如果此用户没有权限就作罢了,什么也不会发生。
rollback():如果有权限,就取消当前的操作,否则报错。
cursor([cursorclass]):返回连接的游标对象。通过游标执行SQL查询并检查结果。游标比连接支持更多的方法,而且可能在程序中更好用。
close():关闭连接。此后,连接对象和游标都不再可用了。

获取游标对象:
>>> cur = conn.cursor()
'''
名称 描述
close() 关闭游标。之后游标不可用
execute(query[,args]) 执行一条SQL语句,可以带参数
executemany(query, pseq) 对序列pseq中的每个参数执行sql语句
fetchone() 返回一条查询结果
fetchall() 返回所有查询结果
fetchmany([size]) 返回size条结果
nextset() 移动到下一个结果
scroll(value,mode='relative') 移动游标到指定行,如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的第一行移动value条.
'''

# 插入数据
>>> cur.execute("insert into users (username,password,email) values (%s,%s,%s)",("python","123456","python@gmail.com"))
1L
>>> conn.commit()
mysql> select * from users;
+----+----------+----------+------------------+
| id | username | password | email            |
+----+----------+----------+------------------+
|  1 | qiwsir   | 123123   | qiwsir@gmail.com |
|  2 | python   | 123456   | python@gmail.com |
+----+----------+----------+------------------+
2 rows in set (0.00 sec)

>>> cur.executemany("insert into users (username,password,email) values (%s,%s,%s)",(("google","111222","g@gmail.com"),("facebook","222333","f@face.book"),("github","333444","git@hub.com"),("docker","444555","doc@ker.com")))
4L
>>> conn.commit()
mysql> select * from users;
+----+----------+----------+------------------+
| id | username | password | email            |
+----+----------+----------+------------------+
|  1 | qiwsir   | 123123   | qiwsir@gmail.com |
|  2 | python   | 123456   | python@gmail.com |
|  3 | google   | 111222   | g@gmail.com      |
|  4 | facebook | 222333   | f@face.book      |
|  5 | github   | 333444   | git@hub.com      |
|  6 | docker   | 444555   | doc@ker.com      |
+----+----------+----------+------------------+
6 rows in set (0.00 sec)

# 查询
>>> cur.execute("select * from users")    
7L
>>> lines = cur.fetchall()
>>> for line in lines:
...     print line
... 
(1L, u'qiwsir', u'123123', u'qiwsir@gmail.com')
(2L, u'python', u'123456', u'python@gmail.com')
(3L, u'google', u'111222', u'g@gmail.com')
(4L, u'facebook', u'222333', u'f@face.book')
(5L, u'github', u'333444', u'git@hub.com')
(6L, u'docker', u'444555', u'doc@ker.com')
(7L, u'\u8001\u9f50', u'9988', u'qiwsir@gmail.com')

>>> cur.execute("select * from users where id=1")
1L
>>> line_first = cur.fetchone()     #只返回一条
>>> print line_first
(1L, u'qiwsir', u'123123', u'qiwsir@gmail.com')

# 用cur.execute()从数据库查询出来的东西被“保存在了cur所能找到的某个地方”
>>> cur.execute("select * from users")
7L
>>> print cur.fetchall()
((1L, u'qiwsir', u'123123', u'qiwsir@gmail.com'), (2L, u'python', u'123456', u'python@gmail.com'), (3L, u'google', u'111222', u'g@gmail.com'), (4L, u'facebook', u'222333', u'f@face.book'), (5L, u'github', u'333444', u'git@hub.com'), (6L, u'docker', u'444555', u'doc@ker.com'), (7L, u'\u8001\u9f50', u'9988', u'qiwsir@gmail.com'))

# 游标读取 scroll(n,"relative"or"absolute")移动游标
>>> cur.execute('select * from users')
7L
>>> print cur.fetchone() 
(1L, u'qiwsir', u'123123', u'qiwsir@gmail.com')
>>> print cur.fetchone()
(2L, u'python', u'123456', u'python@gmail.com')
>>> print cur.fetchone()
(3L, u'google', u'111222', u'g@gmail.com')
>>> cur.scroll(1)
>>> print cur.fetchone()
(5L, u'github', u'333444', u'git@hub.com')
>>> cur.scroll(-2)
>>> print cur.fetchone()
(4L, u'facebook', u'222333', u'f@face.book')

>>> cur.scroll(2,"absolute")    #回到序号是2,但指向第三条
>>> print cur.fetchone()        #打印,果然是
(3L, u'google', u'111222', u'g@gmail.com')

>>> cur.scroll(1,"absolute")
>>> print cur.fetchone()
(2L, u'python', u'123456', u'python@gmail.com')

>>> cur.scroll(0,"absolute")    #回到序号是0,即指向tuple的第一条
>>> print cur.fetchone()
(1L, u'qiwsir', u'123123', u'qiwsir@gmail.com')

# 这个操作,就是实现了从当前位置(游标指向tuple的序号为1的位置,即第二条记录)开始,含当前位置,向下列出3条记录。
>>> cur.fetchmany(3)
((2L, u'python', u'123456', u'python@gmail.com'), (3L, u'google', u'111222', u'g@gmail.com'), (4L, u'facebook', u'222333', u'f@face.book'))

>>> cur.scroll(0,"absolute")
>>> for line in cur.fetchall():
...     print line["username"]
... 
qiwsir
mypython
google
facebook
github
docker
老齐

更新数据
>>> cur.execute("update users set username=%s where id=2",("mypython"))
1L
>>> cur.execute("select * from users where id=2")
1L
>>> cur.fetchone()
(2L, u'mypython', u'123456', u'python@gmail.com')
>>> conn.commit()

结束操作
>>> cur.close()
>>> conn.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值