INSERT、UPDATE、DELETE 等修改数据的语句需手动执行commit()
完成对数据修改的提交
import pymysql
db = pymysql.connect(host = "localhost",
port = 3306,
user = "root",
password = "xxx",
db = "test",
charset='utf8')
#获取光标
cursor = db.cursor()
effect_row = cursor.execute('''
CREATE TABLE student(
id varchar(10) NOT NULL,
name varchar(10) NOT NULL,
age int(10) NOT NULL DEFAULT 0,
score int(10) NOT NULL DEFAULT 0,
PRIMARY KEY(id)
)
''')
effect_row = cursor.execute('''INSERT INTO student VALUES
('1', 'lzj', 22, 99),
('2', 'zjl', 23, 98),
('3', 'wrh', 21, 80)''')
db.commit()
db.close()
db.ping()
函数会校验连接的可用性,如果连接不可用将会产生异常
可以捕获异常进行处理(重连之类的)
执行多条sql语句使用executemany
, 如果插入数量较少, 使用execute
没有什么大关系, 但是数量较多, executemany
的效率要高很多倍
sql = "insert into student (id, name, age, score) values (%s, %s, %s, %s)"
values=[("5", "zhangsan", 25, 89), ("6","lisi", 23, 60)]
effect_row = cursor.executemany(sql, values)
%s
,且不能加上引号list[tuple(),tuple(),tuple()]
或者tuple(tuple(),tuple(),tuple())
sql = "SELECT * from test.student"
effect_row = cursor.execute(sql)
result_one = cursor.fetchone()
print(result_one)
cursor.scroll(-1, mode='relative')
result_two = cursor.fetchmany(2)
print(result_two)
游标类型决定了查询默认返回结果的数据结构, 默认为元组
, 可以自定义设置返回类型
db = pydb.connect(host = "localhost",
port = 3306,
user = "root",
password = "zijianlv",
db = "test",
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
返回结果是元组:
((‘1’, ‘lzj’, 22, 99), (‘2’, ‘zjl’, 23, 98), (‘3’, ‘wrh’, 21, 80), (‘5’, ‘zhangsan’, 25, 89), (‘6’, ‘lisi’, 23, 60))
使用迭代器访问其中元素写入文件:
result_all = cursor.fetchall()
with open("./test.txt", "wt") as f :
it = iter(result_all)
for x in it :
print(x[0], x[1], x[2], x[3], file = f)
SQL语句是字符串拼接生成的时,这也一定会存在SQL注入安全问题
解决办法:
SQL = "select name,password from tb1 where name = %s and password = %s"
info=('min" -- ', 1234)
cursor.execute(SQL,info)
而不是
SQL= SQL %('min" -- ', 1236)
execute()函数具有接受SQL语句参数变量的参数位置, 正确使用就可以对传入的值进行转义, 从而避免SQL注入攻击, 即不要直接使用%
将参数拼接到SQL上然后直接这样:execute(SQL)
使用