1. MySQL
关系型数据库 使用pymysql包进行操作
1.1 连接查询操作
注意:
首先就是数据库的远程连接,假若是本地得到连接就是localhost 连接的关闭close 还有就是pycharm的pymysql包的安装
"""
ubuntu的MySQL在windows进行连接
grant all on *.* to root@'%' identified by '123456' with grant option;
修改配置文件
/etc/mysql/mysql.conf.d/mysqld.cnf
bind-address = 0.0.0.0
一个数据库连接对象可以创建多个游标对象
一般情况下,同一时刻,只会建立一个游标进行操作
"""
import pymysql
connect_db = pymysql.connect(host='192.168.3.88', port=3306, user='root', password='123456', charset='utf8',
database='jing_dong')
cur = connect_db.cursor()
sql_str = '''select * from goods'''
row_count = cur.execute(sql_str)
print('查询到的记录:', row_count)
result = cur.fetchone()
print(result)
print("*" * 10)
result1 = cur.fetchmany(4)
for t in result1:
print(t)
print("*" * 20)
result2 = cur.fetchall()
for v in result2:
print(v)
cur.close()
connect_db.close()
1.2 插入数据
注意:
这个时候就涉及到了数据库的事务 操作完成了需要commit提交,这个是connect的操作,不是游标的操作
"""
"""
import pymysql
connect_db = pymysql.Connect(host='192.168.3.88', port=3306, user='root', password='123456', charset='utf8',
database='jing_dong')
cur = connect_db.cursor()
sql_str = '''insert into goods(name,cate_id,brand_id) values('神州笔记本',1,1);'''
cur.execute(sql_str)
connect_db.commit()
cur.close()
connect_db.close()
1.3 更新与删除操作
import pymysql
connect_db = pymysql.connect(host='192.168.3.88', port=3306, user='root', password='123456', charset='utf8',
database='jing_dong')
cur = connect_db.cursor()
sql_str = ''' delete from goods where id = 21; '''
cur.execute(sql_str)
connect_db.commit()
cur.close()
connect_db.close()
2. Sql注入问题
2.1 sql注入的产生
import pymysql
connect_db = pymysql.connect(host='192.168.3.88', port=3306, user='root', password='123456', charset='utf8',
database='jing_dong')
cur = connect_db.cursor()
select_id = input('请输入要查询的id:')
sql_str = ''' select * from goods where id = %s; ''' % select_id
cur.execute(sql_str)
result = cur.fetchall()
for t in result:
print(t)
cur.close()
connect_db.close()
解决:利用execute方法的第二个参数
import pymysql
connect_db = pymysql.connect(host='192.168.3.88', port=3306, user='root', password='123456', charset='utf8',
database='jing_dong')
cur = connect_db.cursor()
select_id = input('请输入要查询的id:')
sql_str = ''' select * from goods where id = %s; '''
parms = (select_id,)
cur.execute(sql_str,parms)
result = cur.fetchall()
for t in result:
print(t)
cur.close()
connect_db.close()
3.mysql的一些使用
3.1 索引的建立
查看索引
show index from 表名;
创建索引
alter table 表名 add index 索引名称(字段名称);
alter table goods add index catex_id(caye_id);
删除索引
alter table goods drop index catex_id;
性能的测试:
set profiling=1;
select * from test_index where title='ha-99999';
show profiles;
alter table test_index add index (title);
select * from test_index where title='ha-99999';
show profiles;
联合索引
alter table teacher add index (name,age,sex);
最左原则 这个时候只会有name,(name,age),(name,age,sex)这三个联合索引
查看查询的次数
desc 查询语句;
|