Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 05f27dd

Browse filesBrowse files
Create Python数据库编程.md
1 parent 4bfe6f7 commit 05f27dd
Copy full SHA for 05f27dd

File tree

Expand file treeCollapse file tree

1 file changed

+241
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+241
-0
lines changed
Open diff view settings
Collapse file

‎Python数据库编程.md‎

Copy file name to clipboard
+241Lines changed: 241 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
1+
2+
* [1.什么是MySQLdb?](#1什么是mysqldb)
3+
* [2.如何连接数据库?](#2如何连接数据库)
4+
* [3.如何创建数据库表?](#3如何创建数据库表)
5+
* [4.如何执行数据插入?](#4如何执行数据插入)
6+
* [5.如何执行数据库查询操作?](#5如何执行数据库查询操作)
7+
* [6.如何更新数据库数据?](#6如何更新数据库数据)
8+
* [7.如何删除数据库数据?](#7如何删除数据库数据)
9+
* [8.如何使用数据库事务?](#8如何使用数据库事务)
10+
* [9.python如何操作redis?](#9python如何操作redis)
11+
* [10.如果redis中的某个列表中的数据量非常大,如何实现循环显示每一个值?](#10如果redis中的某个列表中的数据量非常大如何实现循环显示每一个值)
12+
* [11.什么是一致性哈希?Python中是否有相应模块?](#11什么是一致性哈希python中是否有相应模块)
13+
14+
15+
## 数据库编程
16+
17+
18+
#### 1.什么是MySQLdb?
19+
20+
MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。
21+
22+
#### 2.如何连接数据库?
23+
24+
```
25+
#!/usr/bin/python
26+
# -*- coding: UTF-8 -*-
27+
28+
import MySQLdb
29+
30+
# 打开数据库连接
31+
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
32+
33+
# 使用cursor()方法获取操作游标
34+
cursor = db.cursor()
35+
36+
# 使用execute方法执行SQL语句
37+
cursor.execute("SELECT VERSION()")
38+
39+
# 使用 fetchone() 方法获取一条数据
40+
data = cursor.fetchone()
41+
42+
print "Database version : %s " % data
43+
44+
# 关闭数据库连接
45+
db.close()
46+
```
47+
48+
#### 3.如何创建数据库表?
49+
50+
```
51+
#!/usr/bin/python
52+
# -*- coding: UTF-8 -*-
53+
54+
import MySQLdb
55+
56+
# 打开数据库连接
57+
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
58+
59+
# 使用cursor()方法获取操作游标
60+
cursor = db.cursor()
61+
62+
# 如果数据表已经存在使用 execute() 方法删除表。
63+
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
64+
65+
# 创建数据表SQL语句
66+
sql = """CREATE TABLE EMPLOYEE (
67+
FIRST_NAME CHAR(20) NOT NULL,
68+
LAST_NAME CHAR(20),
69+
AGE INT,
70+
SEX CHAR(1),
71+
INCOME FLOAT )"""
72+
73+
cursor.execute(sql)
74+
75+
# 关闭数据库连接
76+
db.close()
77+
78+
```
79+
80+
#### 4.如何执行数据插入?
81+
82+
```
83+
#!/usr/bin/python
84+
# -*- coding: UTF-8 -*-
85+
86+
import MySQLdb
87+
88+
# 打开数据库连接
89+
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
90+
91+
# 使用cursor()方法获取操作游标
92+
cursor = db.cursor()
93+
94+
# SQL 插入语句
95+
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
96+
LAST_NAME, AGE, SEX, INCOME)
97+
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
98+
try:
99+
# 执行sql语句
100+
cursor.execute(sql)
101+
# 提交到数据库执行
102+
db.commit()
103+
except:
104+
# Rollback in case there is any error
105+
db.rollback()
106+
107+
# 关闭数据库连接
108+
db.close()
109+
```
110+
111+
#### 5.如何执行数据库查询操作?
112+
113+
Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
114+
115+
fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
116+
fetchall():接收全部的返回结果行.
117+
rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
118+
119+
#### 6.如何更新数据库数据?
120+
121+
```
122+
#!/usr/bin/python
123+
# -*- coding: UTF-8 -*-
124+
125+
import MySQLdb
126+
127+
# 打开数据库连接
128+
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
129+
130+
# 使用cursor()方法获取操作游标
131+
cursor = db.cursor()
132+
133+
# SQL 更新语句
134+
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
135+
try:
136+
# 执行SQL语句
137+
cursor.execute(sql)
138+
# 提交到数据库执行
139+
db.commit()
140+
except:
141+
# 发生错误时回滚
142+
db.rollback()
143+
144+
# 关闭数据库连接
145+
db.close()
146+
```
147+
148+
#### 7.如何删除数据库数据?
149+
150+
```
151+
#!/usr/bin/python
152+
# -*- coding: UTF-8 -*-
153+
154+
import MySQLdb
155+
156+
# 打开数据库连接
157+
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
158+
159+
# 使用cursor()方法获取操作游标
160+
cursor = db.cursor()
161+
162+
# SQL 删除语句
163+
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
164+
try:
165+
# 执行SQL语句
166+
cursor.execute(sql)
167+
# 提交修改
168+
db.commit()
169+
except:
170+
# 发生错误时回滚
171+
db.rollback()
172+
173+
# 关闭连接
174+
db.close()
175+
176+
```
177+
178+
#### 8.如何使用数据库事务?
179+
180+
```
181+
# SQL删除记录语句
182+
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
183+
try:
184+
# 执行SQL语句
185+
cursor.execute(sql)
186+
# 向数据库提交
187+
db.commit()
188+
except:
189+
# 发生错误时回滚
190+
db.rollback()
191+
```
192+
193+
#### 9.python如何操作redis?
194+
195+
```
196+
连接
197+
- 直接连接:
198+
import redis
199+
r = redis.Redis(host='10.211.55.4', port=6379)
200+
r.set('foo', 'Bar')    # 这里的方法与Redis命令类似
201+
print r.get('foo')
202+
- 连接池:
203+
import redis
204+
pool = redis.ConnectionPool(host='10.211.55.4', port=6379)
205+
r = redis.Redis(connection_pool=pool)
206+
r.set('foo', 'Bar')
207+
print r.get('foo')
208+
209+
```
210+
211+
#### 10.如果redis中的某个列表中的数据量非常大,如何实现循环显示每一个值?
212+
213+
```
214+
     def list_iter(key, count=3):
215+
start = 0
216+
while True:
217+
result = conn.lrange(key, start, start+count-1)
218+
start += count
219+
if not result:
220+
break
221+
for item in result:
222+
yield item
223+
    # 调用
224+
for val in list_iter('num_list'):
225+
print(val)
226+
227+
```
228+
229+
#### 11.什么是一致性哈希?Python中是否有相应模块?
230+
231+
一致性hash算法(DHT)可以通过减少影响范围的方式,解决增减服务器导致的数据散列问题,从而解决了分布式环境下负载均衡问题;
232+
如果存在热点数据,可以通过增添节点的方式,对热点区间进行划分,将压力分配至其他服务器,重新达到负载均衡的状态。
233+
234+
Python模块--hash_ring,即Python中的一致性hash。
235+
236+
237+
#### 参考资料
238+
239+
https://www.runoob.com/python/python-mysql.html
240+
241+
https://www.cnblogs.com/wcwnina/p/10304641.html

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.