簡體   English   中英

python mysql連接器查詢無返回

[英]python mysql connector query returns none

我在使用mysql連接器時遇到問題。 我確實搜索了很長時間,但什么都沒找到。

如果執行第一個僅包含查詢的文件,它將按預期工作。 但是,如果我嘗試制作一個db類並將查詢放在其中,它將返回None。 我已經取出了位置變量,它是相同的。 無論我嘗試查詢什么,它都將返回None。 我什至試圖做一個“ SHOW TABLES”,它返回None。

此外,我已經在調試器中運行了此命令,並確定了游標對象以及mysql常規日志。 該查詢是正確的,一切看起來對我來說都應如此。

這是我第一次嘗試使用python,我希望解決方案是一些簡單的新手錯誤。

有效的查詢: test.py

import mysql.connector

_config = {
    'user': 'user',
    'password': 'password',
    'host': '127.0.0.1',
    'database': 'testdb',
    'raise_on_warnings': True,
    }
cnx = mysql.connector.connect(**_config)

cursor = cnx.cursor()
query = ("SELECT * FROM testtbl WHERE location=%s")
location='HERE'
cursor.execute(query, (location, ))

print("--- " + str(cursor) + " ----")
for (stuff) in cursor:
  print("stuff: '" + stuff[0] + "', more stuff: '" + stuff[1] + "'")

cursor.close()
cnx.close()

那些不起作用的: somedb.py

import mysql.connector

class SomeDB(object):
    def __init__(self):
        _config = {
            'user': 'user',
            'password': 'password',
            'host': '127.0.0.1',
            'database': 'testdb',
            'raise_on_warnings': True,
        }
        self.conn = mysql.connector.connect(**_config)
        self.cur = self.conn.cursor()

    def get_stuff(self):
        query = ("SELECT * FROM testtbl WHERE location=%s")
        location="HERE"
        result = self.cur.execute(query, (location, ))
        return result

    def __del__(self):
        self.conn.close()

遵循Alu的建議,我將get_stuff方法更改為:

def get_nodes(self):
    query = ("SELECT * FROM testtbl WHERE location=%s")
    location="HERE"
    cursor = self.cur.execute(query, (location, ))
    list = []
    for (thing) in cursor:
        list.append(([thing[0],thing[1]]))
    return list

test2.py

import somedb

db = somedb.SomeDB()

cursor = db.get_stuff()
print("--- " + str(cursor) + " ----")
for (stuff) in cursor:
  print("stuff: '" + stuff[0] + "', more stuff: '" + stuff[1] + "'")

UPDATE

好的,我無法使它正常工作。 我已經用調試器看過了這段代碼,並且除了類抽象之外,其他所有東西似乎都是平等的。 因此,讓我細化一下我的問題:是否可以使用任何mysql驅動程序? 這就是我想要做的: https : //softwareengineering.stackexchange.com/questions/200522/how-to-deal-with-database-connections-in-a-python-library-module

UPDATE2

我找到了!

    result = self.cur.execute(query, (location, ))
    return result

需要簡單地說:

    self.cur.execute(query, (location, ))
    return self.cur

據我記得,您必須在每次交易后提交連接。

您可以嘗試以此為例。 這是我的數據庫類。 https://github.com/CatCookie/DomainSearch/blob/master/src/additional/database.py

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM