-
Notifications
You must be signed in to change notification settings - Fork 0
/
Python操作数据库
53 lines (43 loc) · 2.09 KB
/
Python操作数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import pymysql
#连接数据库
conn = pymysql.connect(host="localhost",user="root",passwd="123456",db="test",port=3306,charset="utf8")
#也可以不指定数据库,而是直接连接MySQL
#conn = MySQLdb.connect("localhost","root","123123",port=3306,charset="utf8")
#选择数据库
#conn.select_db("wanghao")
#新建数据库
#cur.execute("create database newtest")
#获取游标cursor,用cursor操作数据库
cur = conn.cursor()
#用cursor执行SQL语句,向表users中插入一条记录,该函数的返回值是SQL语句影响的行数
cur.execute("insert into users (username, password, email) values (%s, %s, %s)", ("xiaohong", "123456", "[email protected]"))
#执行完SQL语句后要提交
conn.commit()
#插入多条记录
cur.executemany("insert into users (username,password,email) values (%s,%s,%s)",(("google","111222","[email protected]"),("facebook","222333","[email protected]"),("github","333444","[email protected]"),("docker","444555","[email protected]")))
conn.commit()
#查询数据,同样返回值是查询到的行数
cur.execute("select * from users");
#如果要接收查询结果,则要使用下面的方法
#fetchall(self):接收全部的返回结果行.
lines = cur.fetchall()
#fetchmany(size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
lines = cur.fetchmany(3)
#fetchone():返回一条结果行.
lines = cur.fetchone()
#scroll(value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的第一行移动value条.
cur.scroll(1, mode='relative')
cur.scroll(-1, mode='relative')
#还可以将读取到的数据变成字典形式
cur = conn.cursor(cursor=MySQLdb.cursors.DictCursor)
cur.execute("select * from users")
user_info = cur.fetchall()
#打印出所有的username
for line in cur.fetchall():
print line["username"]
#更新记录,把表中id为2的记录的username改为xiaolan
cur.execute("update users set username=%s where id=2",("xiaolan"))
conn.commit()
#完成操作后,关闭连接
cur.close()
conn.close()