您的位置:首页 > 编程语言 > Python开发

Python-MySQL summary

2015-12-15 21:43 549 查看
1. 安装MySQL, Python, MySQL-python

MySLQ-python下载地址:https://pypi.python.org/pypi/MySQL-python/
下载MySQL-python-1.2.5.zip 文件之后直接解压。进入MySQL-python-1.2.5目录:
>>python setup.py install
MySQL-python API说明:
https://www.python.org/dev/peps/pep-0249/

2. 使用

create connection (MySQLdb.connect)
-> connection.cursor()
-> cursor.operations... (execute)
-> cursor.close 
-> connection.commit,close

1) 基本操作:

#coding=utf-8import MySQLdbonn= MySQLdb.connect(
c 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()关闭数据库连接

2) 插入数据:

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

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'),    ])
3) 查询数据cursor.fetchone()cursor.scroll()cursor.fetchmany()cursor.fetchall()
>>>aa=cur.execute("select * from student")>>>print aa5它获得的只是我们的表中有多少条数据。获得数据:
>>> 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') 方法可以将游标定位到表中的第一条数据。打印多条数据:
#获得表中有多少条数据aa=cur.execute("select * from student")print aa
#打印表中的多少数据info = cur.fetchmany(aa)for ii in info:print iicur.close()conn.commit()conn.close()
4) 其它操作connection.select_db()
cursor.executemany()
cur.fetchall()commit() 提交rollback() 回滚cursor用来执行命令的方法:callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数nextset(self):移动到下一个结果集
cursor用来接收返回值的方法:fetchall(self):接收全部的返回结果行.fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.fetchone(self):返回一条结果行.scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.
3. 其它例子

import
 
MySQLdb

 
try
:

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

    
cur
=
conn.cursor()

    
 
    
cur.execute(
'create
database if not exists python'
)

    
conn.select_db(
'python'
)

    
cur.execute(
'create
table test(id int,info varchar(20))'
)

    
 
    
value
=
[
1
,
'hi
rollen'
]

    
cur.execute(
'insert
into test values(%s,%s)'
,value)

    
 
    
values
=
[]

    
for
 
in
 
range
(
20
):

        
values.append((i,
'hi
rollen'
+
str
(i)))

        
 
    
cur.executemany(
'insert
into test values(%s,%s)'
,values)

 
    
cur.execute(
'update
test set info="I am rollen" where id=3'
)

 
    
conn.commit()

    
cur.close()

    
conn.close()

 
except
 
MySQLdb.Error,e:

     
print
 
"Mysql
Error %d: %s"
 
%
 
(e.args[
0
],
e.args[
1
])


请注意一定要有conn.commit()这句来提交事务,要不然不能真正的插入数据。
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python mysql