【问题标题】:Executing Select statement by using mysql-python gives None使用 mysql-python 执行 Select 语句给出 None
【发布时间】:2016-03-20 20:23:28
【问题描述】:

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

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

d_details中选择d_id、d_link、d_name

但它给出/返回 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

虽然查询在工作台中运行良好

欢迎任何形式的帮助/指导。

【问题讨论】:

  • 试试print self.cursor.fetchall()
  • @VigneshKalai - 非常感谢,效果很好!

标签: python mysql mysql-python


【解决方案1】:

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

代码:

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*() 来获得该行

【讨论】:

    猜你喜欢
    • 2012-08-27
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 2012-05-11
    • 1970-01-01
    相关资源
    最近更新 更多