找回密码
 立即注册

推荐阅读

  • 便民服务
  • 关注我们
  • 社区新手
# python  中的数据库


# 1、安装pymysql库
# 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)
'''

#创建一个数据库连接对象
# db = pymysql.connect(host='192.168.59.128',user='root',password='123456'
#                      ,database='dcs4',port=3306)

# 游标对象的2个作用
# 1)执行sql语句or = db.cursor()
# 2)把执行的结果返回保存到cursor 游标对象中

# 创建一个数据库的游标对象
# curs
# cursor.execute('select * from test;')        #调游标对像执行查询

# 3)返回表中第一条数据(数据是元组)
# one = cursor.fetchone()
# print(one)       #打印表中第一条数据    (1, 'xiaoduan', 7)

# 4)插入语句
# insert_sql = 'insert into test values(5,"xiaogao",7),(6,"xiaokang",7);'
# 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 ='dcs4'
        self.port = 3306
    def connect_db(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.connect_db()       #对象调用实例方法  拿到数据库的连接对象
        cursor = db.cursor()
        cursor.execute(sql)
        one = cursor.fetchone()    #查询第一条数据
        return one
    def delete_one(self,delete_sql,select_sql):
        db = self.connect_db()       #对象调用实例方法
        cursor = db.cursor()
        cursor.execute(delete_sql)      #删除语句
        cursor.execute(select_sql)      #删除后查询语句
        all = cursor.fetchall()       #all 是删除后的所有数据
        return all


if __name__ == '__main__':
    m = Db_auto()     #创建一个对象
    print(m.find_one('select * from test;'))
    print(m.delete_one('delete from test where id =1;','select * from test;'))

分享至 : QQ空间
收藏
您需要登录后才可以回帖 登录 | 立即注册