在python安装pip install pymysql cryptography
插入
import pymysql
conn = pymysql.connect(host='ip地址', port=3306,
user='用户名', password='密码',
database='数据库名', charset='utf8mb4')
try:
with conn.cursor() as cursor:
affected_rows = cursor.execute(
'insert into `表` values (%s, %s, %s)',
(xx, xx, xx)
)
if affected_rows == 1:
print('新增成功!!!')
conn.commit()
except pymysql.MySQLError as err:
conn.rollback()
print(type(err), err)
finally:
conn.close()
删除
import pymysql
conn = pymysql.connect(host='ip地址', port=3306,
user='用户名', password='密码',
database='数据库名', charset='utf8mb4',
autocommit=True)
try:
with conn.cursor() as cursor:
affected_rows = cursor.execute(
'delete from `表` where `dno`=%s',
(xx,)
)
if affected_rows == 1:
print('删除成功!!!')
finally:
conn.close()
更新
import pymysql
conn = pymysql.connect(host='ip地址', port=3306,
user='用户名', password='密码',
database='数据库名', charset='utf8mb4')
try:
with conn.cursor() as cursor:
affected_rows = cursor.execute(
'update `表` set `dname`=%s, `dloc`=%s where `dno`=%s',
(xx, xx, xx)
)
if affected_rows == 1:
print('更新成功!!!')
conn.commit()
except pymysql.MySQLError as err:
conn.rollback()
print(type(err), err)
finally:
conn.close()
查询
import pymysql
conn = pymysql.connect(host='ip地址', port=3306,
user='用户名', password='密码',
database='数据库名', charset='utf8mb4')
try:
with conn.cursor() as cursor:
cursor.execute('select `dno`, `dname`, `dloc` from `tb_dept`')
row = cursor.fetchone()
while row:
print(row)
row = cursor.fetchone()
except pymysql.MySQLError as err:
print(type(err), err)
finally:
conn.close()