import pymysql
'''
连接mysql数据库参数
: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)
'''
#创建一个数据库的连接对象
db=pymysql.Connect(host='192.168.2.113',
user='root',
password='123456',
database='duoceshi',
port=3306)
#游标对象的2个作用:
#1.执行sql语句
#2.把执行的结果返回保存到cursor游标对象中
#创建一个mysql数据库游标对象
cursor=db.cursor()
# cursor.execute('select * from cc;')
#返回表中第一行数据
# one=cursor.fetchone() #fetchone()方法返回表中第一行
# print(one)
# print(type(one))
#插入数据
# insert_sql='insert into cc(s_id,score)values(2,88),(3,89);'
# cursor.execute(insert_sql)
# cursor.execute('select * from cc;') #插入数据进行查询
# all=cursor.fetchall() #fetchall() 方法是返回表中所有数据
# print(all)
#上面写的都是属于线性脚本
#把线性脚本进行封装
import pymysql
class Db_utils():
def __init__(self,host,user,password,database,port):
self.host=host #ip地址
self.user=user #用户名
self.password=password #密码
self.database=database #库
self.port=port #端口3306
def connect(self):
self.db=pymysql.Connect(host=self.host,
user=self.user,
password=self.password,
database=self.database,
port=self.port)
self.cursor=self.db.cursor() # 创建一个mysql数据库游标对象
def excute(self,sql):
self.cursor.execute(sql)
def fetchone(self):
print(self.cursor.fetchone()) # fetchone()方法返回表中第一行数据
def fetchall(self):
print(self.cursor.fetchall()) # fetchone()方法返回表中全部数据
if __name__ == '__main__':
d=Db_utils(host='192.168.0.178',
user='root',
password='123456',
database='duoceshi',
port=3306)
d.connect()
d.excute('select * from cc;')
d.fetchone()
d.fetchall()
标签:database,self,MySQL,cursor,host,UI,自动化,password,port From: https://www.cnblogs.com/jjm414/p/17262861.html