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 connect to a library of MySQL server in python

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

Editor to share with you how to connect to the MySQL server in python of a library, I hope you will learn something after reading this article, let's discuss it together!

PyMySQL is a library used to connect to MySQL servers in the Python3.x version.

Installation:

The process of adding, deleting, modifying and querying pip install PyMySQL database is similar, mainly in the sql statement. #! / usr/bin/env python3#-*- coding:utf-8-*-import pymysql# create a database link db = pymysql.connect ("localhost", 'root','drcom','TESTDB') # create a cursor object # cursor is a data buffer opened by the system for users, which stores the execution result of the sql statement cursor = db.cursor () # execute the sql query The return value is the number of items cursor.execute ("select version ()") # gets the query data # fetchone returns only one row at a time, that is, the next row of the result set # fetchall () gets all the remaining rows in the result set data = cursor.fetchone () print ("database version:%s"% data) # executes sql. If the table exists, delete cursor.execute ("drop table if exists EMPLOYEE") # create the table sql =''CREATE TABLE EMPLOYEE (FIRST_NAME CHAR (20) NOT NULL, LAST_NAME CHAR (20), AGE INT, SEX CHAR (1), INCOME FLOAT)' 'cursor.execute (sql) # sql insert statement insert_db =' 'INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME) AGE,SEX,INCOME) VALUES ('Mac','Mohan',20,'M',2000)' 'try: cursor.execute (insert_db) # submit to the database for execution If you do not perform this step, the data will not be actually written to the db.commit () except:#. If an error occurs, roll back db.rollback () cursor.execute ("SELECT * FROM TESTDB.EMPLOYEE") result = cursor.fetchall () print (result) # close the database db.close (). After reading this article, I believe you have some understanding of "how to connect to a library of MySQL servers in python". If you want to know more related knowledge, welcome to follow the industry information channel, thank you for reading!

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

Database

Wechat

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

12
Report