python 中数据库的使用
1、安装pymysql库
在 dos 窗口输入如下命令:win +r 输入cmd
pip install pymysql 或者 python -m pip install pymysql
import pymysql #导入pymysql这个库
'''
:param host: Host where the database server is located
:param user: Username to log in as
:param password: Password to use.
:param database: Database to use, None to not use a particular one.
:param port: MySQL port to use, default is usually OK. (default: 3306)
'''
2、创建一个数据库连接对象db
db = pymysql.connect(host='192.168.59.128',user='root',password='123456',
database='dcs2',port=3306)
游标对象作用
1)执行sql语句
2)把执行的结果返回保存到cursor游标对象中
创建一个mysql数据库游标对象
cursor = db.cursor()
cursor.execute('select * from test1;') #执行sql语句
3、返回表中第一条数据
one = cursor.fetchone() #打印第一条数据
print(one) #(1, 25, 1, 'zhangsan', 1833, 90) 数据类型元组
4、插入数据
insert_sql = 'insert into test1 values(13,30,1,"xiaoduan",1835,90);'
cursor.execute(insert_sql)
5、返回表中所有数据(返回一个元组)
all = cursor.fetchall() #打印所有的数据
print(all)
上面写的叫线性脚本
把线性脚本进行封装
import pymysql
class Db_Auto:
def __init__(self): #构造函数 把连接的数据库参数设置为实例变量 self.host = '192.168.59.128' self.user = 'root' self.password = '123456' self.database = 'dcs2' self.port = 3306def get_connect(self): 封装一个连接数据库的对象 db = pymysql.connect(host=self.host,user=self.user,password=self.password, database=self.database,port=self.port) return db #把连接数据库的方法返回给函数调用处def find_one(self,sql): #封装一个查询数据库第一条数据的方法 db = self.get_connect() #对象调用实例方法 拿到数据库的连接方法 cursor = db.cursor() #创建按一个游标对象 cursor.execute(sql) one = cursor.fetchone() #打印第一条数据 return onedef delete_one(self,del_sql,select_sql): #封装删除第一条数据的方法 db = self.get_connect() ##对象调用实例方法 拿到数据库的连接方法 cursor = db.cursor() cursor.execute(del_sql) #执行删除操作 cursor.execute(select_sql) #查询删除后的结果 all = cursor.fetchall() return all
if name == 'main':
m = Db_Auto() #创建一个对象m
print(m.find_one('select * from test1;'))
print(m.delete_one('delete from test1 where id = 12;','select * from test1;'))
#作业封装一个查询all数据和删除所有数据
|
|