我使用MySQLdb
操縱MySQL
數據庫,我有這個按照常規,注入在一個表中的一些數據稱爲urls
:數據插入到MySQL,但不是永久 - Python的
def insert_urls(dbconn, filenames):
root = "<path>/"
link = "http://<url>/"
for f in filenames:
filename = root + f + ".html"
local_url = link + f + ".html"
print(filename, local_url)
sql = """
INSERT INTO urls(url, filename) VALUES('%s', '%s');
""" % (local_url, filename)
print(sql)
dbconn.execute_query(sql)
的所述urls
表的聲明這裏找到:
def create_urls_table():
sql = """
CREATE TABLE IF NOT EXISTS urls (
id INT NOT NULL AUTO_INCREMENT,
url BLOB NOT NULL,
filename BLOB NOT NULL,
PRIMARY KEY(id)
) ENGINE=INNODB;
"""
return sql
dbconn
是類Dbconn
的對象,定義爲:
class Dbconn:
def __init__(self,
host="",
user="",
pwd="",
database=""):
self.host = host
self.user = user
self.pwd = pwd
self.db = database
self.cursor = None
self.conn = None
try:
self.conn = MySQLdb.connect(host=self.host,
user=self.user,
passwd =self.pwd,
db=self.db)
self.cursor = self.conn.cursor()
print "Connection established"
except MySQLdb.Error, e:
print "An error has occurred ", e
def execute_query(self, sql=""):
try:
self.cursor.execute(sql)
except MySQLdb.Error, e:
print "An error has occurred ", e
運行insert_urls
我得到以下輸出的步驟之後:
INSERT INTO urls(url, filename) VALUES ('http://<url>/amazon.html','<path>/amazon.html');
INSERT INTO urls(url, filename) VALUES('http://<url>/linkedin.html', '<path>/linkedin.html');
INSERT INTO urls(url, filename) VALUES('http://<url>/nytimes.html', '<path>/nytimes.html');
其中我能夠通過命令行手動注入MySQL
。 但是做一個SELECT * FROM urls
查詢我什麼也沒找到。我手動插入兩行後,我得到了:
mysql> select * from urls;
+----+------------------------------------------------+------------------------+
| id | url | filename |
+----+------------------------------------------------+------------------------+
| 19 | http://<url>/yelp.html | <path>/yelp.html |
| 29 | http://<url>/amazon.html | <path>/amazon.html |
+----+------------------------------------------------+------------------------+
請注意id
值遞增......它可能表示有數據插入,但不持久化?有人可以幫助我嗎? (事實上,INNODB是一個事務型數據庫)
上的錢!THXü – cybertextron