社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
安装: pip install pymysql
CREATE DATABASE IF NOT EXISTS xdd;
USE xdd;
CREATE TABLE `student`(
`id` int(11) not null AUTO_INCREMENT,
`name` varchar(30) not null,
`age` int(11) DEFAULT null,
primary key (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Connection初始化方法常用参数 | 说明 |
---|---|
host | 主机,ip地址 |
user | 用户名 |
password | 密码 |
database | 数据库名称 |
port | 数据库端口 |
Connection.ping()方法,测试数据库服务器是否活着。有一个参数reconnect表示断开与服务器连接是否重连。连接关闭抛出异常。
import pymysql
conn = None
try:
ip = "127.0.0.1"
username = "xdd"
password = "xdd"
database = "xdd"
port = 3306
conn = pymysql.connect(ip,username,password,database,port=port)
conn.ping(False) #ping不通则抛出异常
finally:
if conn:
conn.close()
数据库操作需要使用Cursor类的实例,提供execute()方法,执行SQL语句,成功返回影响的行数。
使用insert int 语句插入数据库。
import pymysql
conn = None
cursor = None
try:
ip = "127.0.0.1"
username = "xdd"
password = "xdd"
database = "xdd"
port = 3306
#创建数据库连接对象
conn = pymysql.connect(ip,username,password,database,port=port)
#连接数据库
cursor = conn.cursor()
insert_sql = "insert into student (name,age) value('tom',18)"
# 执行sql语句
print(cursor.execute(insert_sql))
# 提交事务
conn.commit()
except:
conn.rollback() #如果提交失败回滚
finally:
if conn:
conn.close()
if cursor:
cursor.close()
名称 | 说明 |
---|---|
fetchone() | 获取结果集的下一行 |
fetchmany(size=None) | size指定返回的行数的行,None则返回空元组 |
fetchall() | 返回剩余所有行,如果走到末尾,就返回空元组,否则返回一个元组,其元素是每一行的记录封装的一个元组 |
cursor.rownumber | 返回当前行号。可以修改,支持负索引 |
cursor.rowcount | 返回总行数 |
import pymysql
conn = None
cursor = None
try:
ip = "127.0.0.1"
username = "xdd"
password = "xdd"
database = "xdd"
port = 3306
#创建数据库连接对象
conn = pymysql.connect(ip,username,password,database,port=port)
#连接数据库
cursor = conn.cursor()
insert_sql = "select * from student"
# 执行sql语句
rows = cursor.execute(insert_sql) #返回受影响的行
print("- "*10,cursor.rownumber, cursor.rowcount)
print(cursor.fetchone())
print(cursor.fetchone())
print("- "*10,cursor.rownumber, cursor.rowcount)
print(cursor.fetchmany(2))
print("- " * 10, cursor.rownumber, cursor.rowcount)
print(cursor.fetchmany(2))
print("- " * 10, cursor.rownumber, cursor.rowcount)
print(cursor.fetchall())
print("- " * 10, cursor.rownumber, cursor.rowcount)
print(cursor.fetchone())
print(cursor.fetchmany(1))
print(cursor.fetchall())
#修改游标索引
cursor.rownumber = 0 #正负都支持
for x in cursor.fetchall():
print(x,"~~~~~~~")
except:
conn.rollback() #如果提交失败回滚
finally:
if conn:
conn.close()
if cursor:
cursor.close()
cursor = conn.cursor(DictCursor)就可以了
# 返回结果
{'name': 'tom', 'age': 18}
{'name': 'tom0', 'age': 18}
import pymysql
conn = None
cursor = None
try:
ip = "127.0.0.1"
username = "xdd"
password = "xdd"
database = "xdd"
port = 3306
#创建数据库连接对象
conn = pymysql.connect(ip,username,password,database,port=port)
#连接数据库
cursor = conn.cursor(pymysql.cursors.DictCursor)
insert_sql = "select name,age from student"
# 执行sql语句
rows = cursor.execute(insert_sql) #返回受影响的行
#修改游标索引
cursor.rownumber = 0 #正负都支持
for x in cursor.fetchall():
print(x)
except:
conn.rollback() #如果提交失败回滚
finally:
if conn:
conn.close()
if cursor:
cursor.close()
SQL注入攻击:猜测后台数据的查询语句使用拼接字符串等方式,从而经过设计为服务端传参,令其拼接出特殊字符串的SQL语句,返回攻击者想要的结果。
永远不要相信客户端传来的数据是规范及安全的!!!
解决SQL注入攻击,可以使用参数化查询,可以有效防止注入工具,并提高查询的效率。
Cursor.excute(query,args=None)
import pymysql
ip = "127.0.0.1"
username = "xdd"
password = "xdd"
database = "xdd"
port = 3306
#创建数据库连接对象
conn = pymysql.connect(ip,username,password,database,port=port)
cursor = None
try:
#连接数据库
cursor = conn.cursor(pymysql.cursors.DictCursor)
# insert_sql = "select * from student where name like %(name)s and age > %(age)s;"
# # 执行sql语句
# rows = cursor.execute(insert_sql,{"name":"tom%","age":17}) #返回受影响的行
insert_sql = "select * from student where name like %s and age > %s;"
rows = cursor.execute(insert_sql,("tom%",17))
for x in cursor.fetchall():
print(x)
except:
conn.rollback() #如果提交失败回滚
finally:
if conn:
conn.close()
if cursor:
cursor.close()
import pymysql
ip = "127.0.0.1"
username = "xdd"
password = "xdd"
database = "xdd"
port = 3306
#创建数据库连接对象
conn = pymysql.connect(ip,username,password,database,port=port)
cursor = None
try:
#连接数据库
cursor = conn.cursor(pymysql.cursors.DictCursor)
insert_sql = "insert into student (name,age) values (%s,%s);"
rows = cursor.executemany(insert_sql,(("jerry{}".format(i),18+i) for i in range(5)))
print(rows)
conn.commit()
except:
conn.rollback() #如果提交失败回滚
finally:
if conn:
conn.close()
if cursor:
cursor.close()
# 链接对象类
class Connection(object):
def __enter__(self):
"""Context manager that returns a Cursor"""
warnings.warn(
"Context manager API of Connection object is deprecated; Use conn.begin()",
DeprecationWarning)
return self.cursor()
def __exit__(self, exc, value, traceback):
"""On successful exit, commit. On exception, rollback"""
if exc:
self.rollback()
else:
self.commit()
#游标类
class Cursor(object):
def __enter__(self):
return self
def __exit__(self, *exc_info):
del exc_info
self.close()
链接类进入上下文的时候会返回一个游标对象,退出时如果没有异常会提交更改。
游标类也使用上下文,在退出时关闭游标对象。
conn的with进入是返回一个新的cursor对象,退出时,只是提交或者回滚了事务。并没有关闭cursor和conn。不关闭cursor就可以接着用,防止多次构建链接对象。
简单示例:
import pymysql
ip = "127.0.0.1"
username = "xdd"
password = "xdd"
database = "xdd"
port = 3306
#创建连接对象
conn = pymysql.connect(ip,username,password,database,port = port)
try:
with conn as cursor:
with cursor as cur:
sql = "select * from student"
cursor.execute(sql)
print(cursor.fetchall())
finally:
if conn:
conn.close()
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!