我正在使用使用 mysql 的代码。我对 mysql 很陌生,所以如果您能提供帮助,我将不胜感激。我的输入是一个巨大的 xml bz2 格式的维基百科页面转储文件。输入格式是从该 xml 文件中提取的一些文本文件,格式如下:
<doc id="12" url="https://en.wikipedia.org/wiki?curid=12" title="Anarchism"> text... </doc>
将程序连接到sql的唯一部分如下:
def read_in_STOP_CATS(f_n = "/media/sscepano/Data/Wiki2015/STOPCAT/STOP_CATS.txt"):
s = []
f = open(f_n, "r")
for line in f:
s.append(line.rstrip().lower())
return s
def connect_2_db():
try:
cnx = mysql.connector.connect(user='test', password='test',
host='127.0.0.1',
database='wiki_category_links')
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
return cnx
def articles_selected(aid):
global cnx
global STOP_CATS
cursor = cnx.cursor(buffered=True)
cursor.execute("SELECT * FROM categorylinks where cl_from = " + str(aid))
row = cursor.fetchone()
while row is not None:
#print(row)
cat = row[1].lower()
#print cat
for el in STOP_CATS:
if el in cat:
return False
row = cursor.fetchone()
return True
cnx = connect_2_db()
STOP_CATS = read_in_STOP_CATS()
TITLE_WEIGHT = 4
我的问题是,现在我不知道应该如何连接到mysql才能运行代码,主要问题是我不知道代码中的categorylinks是什么?那应该是我的sql表的名称?这是否意味着我需要用这个名称创建一个 sql 表并将所有文本文件导入到这个表中? 这行中的“where”是什么意思???
最佳答案
正如 RiggsFolly 所说,你需要得到类似 WHERE cl_from = 'some string'
你可以这样做:
cursor.execute("SELECT * FROM categorylinks where cl_from ='" + str(aid)+"'")
但最好使用像这样的准备好的语句:
select_stmt = "SELECT * FROM categorylinks where cl_from = %(aid)s"
cursor.execute(select_stmt, { 'aid':str(aid) })
所以在你的代码中你有:
A database named wiki_category_links
In that database you have a table called categorylinks
您所做的选择意味着您将从表类别链接中获取 cl_from 列等于辅助变量值的所有行。
关于python - mysql表中的"where",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53857623/