Python模块之pymysql 增删改查数据库
pymysql
作用:
增、删、改、查、数据库内容。
必要操作:
import pymysql
帮助查看:
help(pymysql)
或 单独查看某个方法(函数)
help(pymysql.cursor)
方法(函数):
1.connect 链接数据库
db=pymysql.connect(host='192.168.83.144',user='ideal',password='ideal',port=3306,db='entegor')
2.打印数据库版本信息和IP信息
print(db.get_server_info(),db.get_host_info())
3.execute向数据库执行一条命令,插入一行数据:
方式一:
cur.execute(INSERT INTO testdb(FIRST_NAME) VALUES ('Mac'))
方式二:
sql_1 = CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ) cur.execute(sql_1)
方式三:
sql_2= INSERT INTO testdb(FIRST_NAME) VALUES (%s) % ('Mac') cur.execute(sql_2)
4.executemany向数据库执行一条命令,插入多行数据:
sql_3= INSERT INTO testdb(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES(%s, %s, %s, %s, %s) list03= [ ('Mac1', 'Mohan1', 21, 'M', 2001), ('Mac2', 'Mohan2', 22, 'M', 2002), ('Mac3', 'Mohan3', 23, 'M', 2003) ] cur.executemany(sql_3,list03)
5.提交数据
db.commit()
6.关闭数据库连接
db.close()
-