2015-12-20 70 views
1

我想检查一个字符串是从HTML页面中的窗体传递。所以表单会提取用户名,然后检查数据库是否已经创建。如果没有,它会继续并创建它。我的错误位于查找用户名的逻辑部分。为什么我不能在我的mysql查询中使用python比较这些表单变量?

注意,我注释掉了一些地方的各种错误还冒出了:

import mysql.connector 
import web 

from mysql.connector import Error 
import cgi, cgitb 

cgitb.enable() 

conn = mysql.connector.connect(host='localhost', database='database', user='root', password='root') 
cursor = conn.cursor() 
form = cgi.FieldStorage() 
username = form.getvalue('username') 
password = form.getvalue('password') 


# check_existence = """ 
# SELECT username FROM members WHERE username = '%s' 
# """ 

check_existence = """ 
    SELECT username FROM members WHERE username = %s 
""" 

# cursor.execute(check_existence, username) 
# "Wrong number of arguments during string formatting") 


cursor.execute(check_existence, (username)) 

# ^pushes down to con.commit 
# cursor.execute(check_existence, (username,)) 
# ^wrpmg number of arguments during string formatting 
# with comma, the error is in commit, with comma, its in execute 


conn.commit() 

matches = cursor.rowcount() 

现在的错误指向conn.commit。虽然这取决于语法,但有时它指向它上面的行。 错误:

=> 203 conn.commit() 
<class 'mysql.connector.errors.InternalError'>: Unread result found. 
     args = (-1, 'Unread result found.', None) 
     errno = -1 
     message = '' 
     msg = 'Unread result found.' 

回答

1

在我有限的经验,提交()只用于更新保存(提交)到数据库中。它看起来像你正在执行一个选择查询,但对结果无所作为,而且错误与此有关。尝试将提交移到最后,或者废除它。尝试使用/执行游标中存储的结果。我相信后者是解决方案。

+0

啊,我以为.commit必须按照每个查询。 – munchschair

+0

根据https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-commit.html它在每个改变数据的语句之后。 – Redbeard011010

+0

我拿出来了,但现在我得到'“字符串格式化过程中参数数量错误”)“'cursor.execute'' – munchschair

1

.commit方法刚刚起步,但并不是代码唯一的问题。我有两个问题,虽然其中一个没有发布在原来的帖子中,我会解释两者。

A)cursor.rowcount返回-1。不知道为什么,但确实如此。我对它的理解是它会返回行数。但是你可以使用cursor.fetchall()来代替。这将返回数组中的匹配....但是如果数组为空,它将返回一个空数组。

所以我用这个逻辑:

if not(cursor.fetchall()): 
    the set/array is empty>> Create user 
else: 
    something was found >>dont create user 

B)这是我的代码的其余部分。我被检查,如果连接已连接:

if conn.is_connected(): 

有这样做的问题是,如果你一个.execute之后做到这一点,它会返回false。所以我把它放在逻辑上,当它试图连接到数据库时检查它是否正确。

+0

In非缓冲查询cursor.rowcount在提取行之前默认为-1为了避免使用缓冲查询=> mysql.connector.connect(buffered = True) –

相关问题