lex*_*_9x 4 python mysql linux mysql-python
我是 Python 新手。我有一个带有 3 个属性(名称、价格、图像)的 Item 表,我想从链接中获取 html 并保存到表中。所以我这样做
from books.models import Book, Author, Publisher, Item
import urllib
import gzip
from StringIO import StringIO
from BeautifulSoup import BeautifulSoup
import MySQLdb as mdb
def updateItems(request):
con = mdb.connect('localhost', 'anhnt', '12', 'db_django');
cur = con.cursor()
link = "http://pandagift.vn/i263/price1/qua-tang-doc-dao.htm"
request = urllib.urlopen(link)
output1 = open('web.txt', 'wb')
html = ""
html = request.read()
output1.write(html)
output1.close()
beautifulSoup = BeautifulSoup(html)
list_item = beautifulSoup.findAll("div", {"class":"Item_ProcNews"})
if list_item:
for item in list_item :
#lay anh san pham
image = item.findAll("img")[0]
st = str(image)
beginindex = st.find('src') + 5
endindex = st.find('jpg') + 3
if(endindex == 2):
endindex = st.find('png') + 3
if(endindex == 2):
endindex = st.find('jpeg') + 4
if(endindex == 3):
endindex = st.find('gif') + 3
if(endindex == 2):
endindex = st.find('bmp') + 3
if(endindex == 2):
endindex = st.find('JPG') + 3
itemimage = str(image)[beginindex:endindex].encode('utf-8')
#lay ten san pham
name = item.findAll("span", {"class":"item-name"})[0]
temp = name.findAll("a")[0]
#itemname = temp.get('alt').encode('utf-8')
itemname = temp.string.encode('utf-8')
#lay gia san pham
price = item.findAll("span", {"class":"price"})[0]
#temp1 = str(price)
#beginindex1 = temp1.find('price') + 7
#endindex1 = temp1.find('/span') -1
#itemprice = str(temp1)[beginindex1:endindex1]
itemprice = str(price.string)
#luu vao csdl
query = "INSERT INTO books_item(name, price, image) VALUES('"+itemname+"', '"+itemprice+"', '"+itemimage+"')"
cur.execute(query)
#print query
else:
cur.execute("INSERT INTO books_item(name, price) VALUES('Hat', '10000vnd')")
updateItems(request)
Run Code Online (Sandbox Code Playgroud)
它的回报
Exception Type: OperationalError
Exception Value: (1040, 'Too many connections')
Run Code Online (Sandbox Code Playgroud)
请告诉我为什么会发生这种情况,我可以修复它。非常感谢:)
小智 6
我通过在 django app settings.py 文件中增加 MySQL 允许的最大连接数解决了这个问题。MySQL 文档中的更多信息
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
"init_command": "SET GLOBAL max_connections = 100000", #<-- The fix
}
}
}
Run Code Online (Sandbox Code Playgroud)
http://dev.mysql.com/doc/refman/5.0/en/too-many-connections.html
如果在尝试连接到 mysqld 服务器时出现连接过多错误,这意味着所有可用连接都被其他客户端使用。
允许的连接数由 max_connections 系统变量控制。它的默认值是100。如果需要支持更多的连接,这个变量应该设置一个更大的值。
这意味着您打开了比服务器允许的更多的数据库连接,而没有关闭它们。我从未在您的代码中看到close对连接的调用con。