check database whether a record exists

76 views
Skip to first unread message

new user

unread,
Apr 17, 2018, 1:28:05 AM4/17/18
to PyMySQL Users
# 1. Open database connection
db = pymysql.connect("localhost", "user", "password", "database")
# 2. prepare a cursor object using cursor() method
cursor = db.cursor()

list = ["Lucy", "Jim", "Patrick"]

for name in list:
    sql_query = "SELECT 'COUNT(*)' FROM 'database' WHERE 'Name' =%s"
    result = cursor.execute(sql_query, (name,))

there is error in the last line, it says SQL syntax, i dont't know why???

Naoki INADA

unread,
Apr 17, 2018, 5:29:28 AM4/17/18
to PyMySQL Users
Because your SQL is wrong.
Try mysql commandline client and learn SQL before using pymysql.

Miroslav Koula

unread,
Apr 17, 2018, 5:52:11 AM4/17/18
to pymysq...@googlegroups.com

import pymysql


db = pymysql.connect("localhost", "root", "", "test")

cursor = db.cursor()


list = ["English", "German"]


for name in list:

    sql_query = "SELECT COUNT(*) AS cnt FROM languages WHERE name_en = %s"

    result = cursor.execute(sql_query, (name,))

    print(result)


This is working for me. 
So as Naoki wrote, try to learn more SQL as you had errors in escaping characters: there's escaping for columns etc in mysql ` - character, which you need to use only in cases of reserved words in SQL language and it's not the ' character which is used for the strings.

Regards

Miro

--
You received this message because you are subscribed to the Google Groups "PyMySQL Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pymysql-users+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

new user

unread,
Apr 17, 2018, 12:17:50 PM4/17/18
to PyMySQL Users
Thank you for your reply. I found my errors. It's because i didn't define the utf8 when created the database. And the list has unicode 

new user

unread,
Apr 17, 2018, 12:18:34 PM4/17/18
to PyMySQL Users
Thank you for your reply. I found my errors. It's because i didn't define the utf8 when created the database. And the list has unicode 


Regards

Miro

To unsubscribe from this group and stop receiving emails from it, send an email to pymysql-user...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages