My database cannot query. when i run this code then it's show me an error .
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'
I want to know how to write sql code with python variable so how can i fix it ?
query = "INSERT INTO `ac` (`acc`, `mac`, `date`) VALUES (%s, %s, %s)"
re = cursor.execute(query,(shost,mac,today,))
and
query1 = "SELECT * FROM `ac` WHERE `acc` = %s,`mac` = $s"
ck = cursor.execute(query1,(shost,mac))
ekhumoro
122k23 gold badges272 silver badges400 bronze badges
2 Answers 2
query1 = "SELECT * FROMacWHEREacc= %s,mac= $s"
$s - this is not a valid placeholder, replace it with %s.
answered Jan 27, 2016 at 15:30
alecxe
476k127 gold badges1.1k silver badges1.2k bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
alibaba
Nothing happen it's still error and $s is printing mistake
alecxe
@alibaba What errors are you getting? You may also need to commit after the insert:
mdb.commit().alibaba
This Error : Traceback (most recent call last): File "C:\Users\Tanver\Desktop\pypro\final.py", line 51, in button_click re = cursor.execute(query,(shost,mac,today,)) File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute self.errorhandler(self, exc, value) File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.IntegrityError: (1062, "Duplicate entry 'Sabbir' for key 'PRIMARY'")
alecxe
@alibaba and this is a different problem. You have a unique key constraint and you are violating it.
re = cursor.execute(query % (m, n, k))
tumultous_rooster
12.7k34 gold badges96 silver badges156 bronze badges
1 Comment
Dhia
you should add some explanation for better post quality
default