### python 操作mysql(第三方操作)
import pymysql
1.基本语法
1:创建连接(返回对象) host user password(数据库有密码写密码,没有就为空) database(具体操作哪一个数据库) 这四个参数必须写
host 指定哪个数据库下的ip
conn = pymysql.connect(host="127.0.0.1",user="root",password="",database="db0618",charset="utf8"(指定字符集,可以不写,不需要加-),port=3306(指定端口,可以不写))
2:创建游标对象,该对象可以进行增删改查操作
cursor = conn.cursor()
3:执行sql语句 ==>对表或者数据进行操作,先在命令符中先use 该数据库,然后在pymysql进行操作(指定表或者内容)
sql = "select * from employee"
返回的是数据的总条数
res = cursor.execute(sql) ==>execute执行 ,返回的是个数或条数
print(res)
4:获取数据
res = cursor.fetchone()==.fetch 获取 one 是一条
print(res)
5:释放游标对象
cursor.close()
6:关闭连接
conn.close()
通过pymysql执行操作
数据是存储到文件中,永久存储,不会丢失
创建/删除 表
conn = pymysql.connect(host="127.0.0.1",user="root",password="",database="db0619")
cursor = conn.cursor()
创建一张表
sql = """
create table t1(
id int unsigned primary key auto_increment,
first_name char(10) not null,
last_name char(10) not null,
age int unsigned,
sex tinyint,
money float
)
res = cursor.execute(sql)
print(res)
查看表结构
python 中的None=sql中的null
sql = "desc t1"
res = cursor.execute(sql)
print(res) # 返回字段的个数
print(cursor.fetchone())
删除表==>在不指定删了没,用try
try :
sql = "drop table t1"
res = cursor.execute(sql)
print(res)
except:
pass
cursor.close()
conn.close()
### 事务处理
防止sql注入 : 使用预处理的方式,提前对特殊字符进行过滤
注释的时候外面是三个单引号,里面是三个双引号
sql写语句的时候如果有多个引号,要将多个引号内外换成单双,要将引号岔开
可以执行多个sql语句,如果在启动事务处理的时候,最后要在执行一条提交语句,
获取一次就可以了
python 操作事务处理 必须通过commit提交数据,才会真正的更新数据,否则rollback回滚,恢复到以前状态
conn = pymysql.connect(host="127.0.0.