【问题标题】:Mysql Database query error in pythonpython中的Mysql数据库查询错误
【发布时间】:2016-01-27 15:29:55
【问题描述】:

我的数据库无法查询。当我运行此代码时,它会显示一个错误。

def button_click(self):
    # shost is a QString object
    shost = self.le.text()
    if shost:

       s_h = "127.0.0.1"
       s_n = "root"
       s_p = ""
       s_d = "code"

       s_cn = mdb.connect(s_h, s_n, s_p, s_d)

       cursor = s_cn.cursor()
       today = datetime.date.today()
       mac = get_mac()
       query = "INSERT INTO `ac` (`acc`, `mac`, `date`) VALUES (%s, %s, %s)"
       re = cursor.execute(query,(shost,mac,today,))          

       if re: 
           self.ex = Example()
           self.ex.show()

       else:
          query1 = "SELECT * FROM  `ac` WHERE  `acc` = %s,`mac` = $s"
          ck = cursor.execute(query1,(shost,mac))
          if(ck):
             self.ex = Example()
             self.ex.show()
          else:
              print 'no'  

我想知道如何用 python 变量编写 sql 代码,那么我该如何解决呢?

  query = "INSERT INTO `ac` (`acc`, `mac`, `date`) VALUES (%s, %s, %s)"
   re = cursor.execute(query,(shost,mac,today,))

          query1 = "SELECT * FROM  `ac` WHERE  `acc` = %s,`mac` = $s"
          ck = cursor.execute(query1,(shost,mac))

【问题讨论】:

    标签: python mysql python-2.7 python-3.x


    【解决方案1】:

    query1 = "SELECT * FROMacWHEREacc= %s,mac= $s"

    $s - 这不是一个有效的占位符,请将其替换为 %s

    【讨论】:

    • 什么也没发生,仍然是错误,$s 是打印错误
    • @alibaba 你遇到了什么错误?您可能还需要在插入后提交:mdb.commit().
    • 此错误:回溯(最近一次调用最后一次):文件“C:\Users\Tanver\Desktop\pypro\final.py”,第 51 行,在 button_click re = cursor.execute(query, (shost,mac,today,)) 文件“C:\Python27\lib\site-packages\MySQLdb\cursors.py”,第 202 行,在执行 self.errorhandler(self, exc, value) 文件“C:\Python27 \lib\site-packages\MySQLdb\connections.py",第 36 行,在 defaulterrorhandler 中引发错误类,errorvalue _mysql_exceptions.IntegrityError: (1062, "Duplicate entry 'Sabbir' for key 'PRIMARY'")
    • @alibaba 这是一个不同的问题。你有一个唯一的键约束并且你违反了它。
    【解决方案2】:
    re = cursor.execute(query % (m, n, k))
    

    【讨论】:

    • 你应该添加一些解释以获得更好的帖子质量
    猜你喜欢
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 2016-07-21
    • 2017-04-13
    • 1970-01-01
    • 2019-08-09
    • 2018-01-14
    相关资源
    最近更新 更多