Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add data through placeholders after connecting to a database using python

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report