Python connects to Mysql database and performs data table operations

Article directory

  • Preface
  • 1. What is pymsql?
  • 2. Usage steps
    • 1.Install the library

    • 2.Introduce the library

    • 3. Connect to the database

    • 4. Get the cursor object

    • 5. Select the database you want to operate on

    • 6. Use cursor objects to execute SQL

    • 7. Get query results

    • 8. Close the connection

  • Complete code
  • Summarize

Preface

       With the continuous development of artificial intelligence technology, python and mysql, the combination of python and mysql is the best choice for massive data in addition to massive data. The following is a brief introduction on how to use mysql database for read and write operations in python.

1. What is pymysql?

pymysql is a python package based on python that is used to process mysql, that is, a tool. This tool was created to solve the task of reading and writing databases in python.

2. Usage steps

1.Install the library

pip install pymysql

2.Introduce the library

from pymysql import Connection

3. Connect to the database

con = Connection(
    host="localhost",
    port=3306,
    user='root',
    password="123456",
    autocommit=True
)

4. Get the cursor object

cursor = con.cursor()

5. Select the database you want to operate on

con.select_db("python")

6. Use cursor objects to execute SQL

cursor.execute("create table python2(id int,ptime varchar(10))")
cursor.execute("select * from python2")

7. Get query results

result = cursor.fetchall()

8. Close the connection

con.close

Complete code

# 使用python连接mysql数据库
from pymysql import Connection

con = Connection(
    host="localhost",
    port=3306,
    user='root',
    password="123456"
)

#打印连接信息,验证是否连接成功,如果显示版本号,即连接成功
print(con.get_server_info())  

#获取游标对象,便于后续的查询与结果获取操作
cursor = con.cursor()  
#选择数据库
con.select_db("python")
#执行SQL语句
cursor.execute("create table python2(id int,ptime varchar(10))")
#执行sql查询语句(
cursor.execute("select * from python2")
#获取查询结果
result = cursor.fetchall()
#打印结果
print(result)
#关闭连接
con.close()

Summarize

At this point, the above is the specific operation of how to connect to the mysql database in python that I will talk about today. hope it helps you!

Guess you like

Origin blog.csdn.net/weixin_52890053/article/details/132322487