Python Mysql--Pycharm connects to Mysql

1. Guide package

Insert picture description here

2. Create an object connected to the mysql server

Insert picture description here

3. Get the cursor object

Insert picture description here

4. Execute sql statement

Insert picture description here

5. Query result set

Insert picture description here

6. Add or modify the operation to submit the database

Commit the transaction using commit
Insert picture description here

7. Rollback

If the operation fails and you want to restore the object that has not been operated before, use rollback
Insert picture description here

8. Close the cursor

Insert picture description here

9. Close the connection

Insert picture description here

10 related code introduction

10.1 Query the database

#Query database
#1. Guide package
import pymysql
#2. Connect to mysql database service
try:
conn=pymysql.Connect(
#mysql server IP, default 127.0.0.1/locahost (real IP) host port default
#host=' 127.0.0.1',
user='root',
password="123456",
database='day14',
port=3306,
charset='utf8',
)
#3 Create a cursor
cur=conn.cursor()
#4. Write SQL Statement
sql='select * from users;'

#5.使用游标对象去调用SQL
result=cur.execute(sql)
print(result)
# 6.获取查询的结果 ---输出
ret = cur.fetchall()
print(ret)
# 7.关闭游标对象
cur.close()

# 8.关闭连接
conn.close()

except Exception as e:
print(e)

10.2 Add, modify and delete the database

#1.导包
import pymysql
#2. Connect to the mysql server
conn=pymysql.Connect( host='127.0.0.1', user='root', password=“123456”,
database='day14', port=3306,
charset='utf8')
#3. Create a cursor object
cur=conn.cursor()
try:
#4. Write SQL statements for adding, modifying, and deleting

#增加
# sql='insert into user values(null ,%s,%s);'
# data=['whs','123456']

#修改
# sql='update user set username=%s where username="whs";'
# data=['root']

#删除
sql='delete from user where id=4'
#5.使用游标对象执行sql
# cur.execute(sql,data)
cur.execute(sql)
#6.提交事务
conn.commit()

Exception AS E the except:
Print (E)
# rollback
conn.rollback ()
the finally:
. #. 7 Close cursor object
cur.close ()
#. 8 closes the connection.
conn.Close ()

Guess you like

Origin blog.csdn.net/weixin_42478365/article/details/109038286
Recommended