How to add data through placeholders after connecting to a database using python
This article mainly introduces how to use python to connect to the database after adding data through placeholders, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
If you define a string in a SQL statement, the string must be declared using "'" that is, single quotes, but if the database you are working on now contains "'" single quotes, it will cause a syntax error and the data will not be successfully saved to the database. To solve this problem and support the handling of placeholders in pymysql, developers need to define placeholders in SQL using "%" and populate the data of placeholders when executed using the excute () method.
For example, the field mr'yootk in the database table itself contains "'" single quotes, so the syntax is incorrect at execution time.
# use placeholder to add data # coding utf-8import pymysql,tracebackSQL = "insert into user (name,age,birthday,salary,note)"\ "values (% SJM% SPI% s) % s) "def main (): try: name =" mr'Yootk "age = 18 birthday = '2013-09-26' salary = 9600.23 note =" www.wangyi.com "conn = pymysql.connect (host='10.139.7.39', port=3306, user='root') Passwd='Bccdr@123456', database='yootk', charset='utf8') cmd = conn.cursor () cmd.execute (query=SQL,args= [name,age,birthday,salary) Note]) conn.commit () print ("data rows affected by the update:% s"% cmd.rowcount) print ("Last growth ID:% s"% cmd.lastrowid) except Exception: print ("handling exceptions:" + traceback.format_exc () finally: conn.close () if _ _ name__ = = "_ _ main__": main ()
Thank you for reading this article carefully. I hope the article "how to use python to connect to the database and add data through placeholders" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!