使用 mysql-python 执行 Select 语句得到 None

Executing Select statement by using mysql-python gives None

我正在使用 python-2.7 和 mysql/mysql-python 连接器的新手。

我只想通过使用以下查询来检索数据-

SELECT d_id,d_link,d_name 来自 d_details

但它 gives/returns None 。以下是我的代码-

def getdbconnection(self):

    try:

        self.cnx = mysql.connector.connect(user='abc',password='xxx',host = 'localhost',port = 'xxx', database='details',buffered=True)      

        print "Done"
        self.cursor = self.cnx.cursor()

    except MySQLdb.Error as error:      
                print "ERROR IN CONNECTION"

def selectst(self):
        try:
                    print "S E L E C T"
                    self.d_deta = self.cursor.execute("SELECT d_id,d_link,d_name FROM `d_details`")
                    print self.d_deta


        except MySQLdb.Error as error:
                            print "---------------------"""
                            print(error)
        self.cnx.commit()

并且输出是

   Done

    S E L E C T

    None

尽管查询在 workbench

中运行良好

Help/guidance欢迎任何形式。

你应该像这样修改你的代码

代码:

def selectst(self):
    try:
          print "S E L E C T"
          self.cursor.execute("SELECT d_id,d_link,d_name FROM `d_details`")
          print  self.cursor.fetchall() # or fetchone() for one record

    except MySQLdb.Error as error:
                        print "---------------------"""
                        print(error)
    #self.cnx.commit() there is no need of commit here since we are not changing the data of the table

备注:

  • 你得到 None 因为 cursor.execute 是一个内存操作,比如 list.sort()
  • 可以通过遍历 cursor object 或使用 fetch*()
  • 来获取该行