Python操作mysql数据库(封装基本的增删改查)

新学Python,在这里分享操作mysql的全过程

1、安装MySQL-python-1.2.3.win-amd64-py2.7.exe,这是操作mysql数据库的python库,有32位和64位之分,看自机器下载

2、64位机器安装MySQL-python-1.2.3.win-amd64-py2.7.exe出现 which was not found the regidtry,请点这里

3、引入mysql库:

import MySQLdb

4、获取数据库连接:

conn=MySQLdb.connect(host='localhost',user='mjy',passwd='123',db='python',port=3306,charset='utf8')
 

connect连接对象的方法:

close() --关闭的方法

commit()  --如果支持事务则提交挂起的事务

rollback() --回滚挂起的事务

cursor() --返回连接的游标对象

5、获取游标:

#该游标对象执行查询操作返回的结果是序列
cur=con.cursor() 
#该游标对象执行查询操作返回的结果是字典(字典可以方便我们队查询的结果进行操作,所以我采用这种方法)
cur=con.cursor(MySQLdb.cursors.DictCursor)  

游标对象的方法:

callproc(name,[params]) --用来执行存储过程,接收的参数为存储过程的名字和参数列表,返回受影响的行数

close() --关闭游标

execute(sql,[params])--执行sql语句,可以使用参数,(使用参数时,sql语句中用%s进行站位注值),返回受影响的行数

executemany(sql,params)--执行单挑sql语句,但是重复执行参数列表里的参数,返回受影响的行数

fetchone() --返回结果的下一行

fetchall() --返回结果的 所有行

fetchmany(size)--返回size条记录,如果size大于返回结果行的数量,则会返回cursor.arraysize条记录

nextset() --条至下一行

setinputsizes(size)--定义cursor

游标对象的属性:

description--结果列的描述,只读

rowcount --结果中的行数,只读

arraysize --fetchmany返回的行数,默认为1

6、我自己封装的一些基本操作

# -*- coding: cp936 -*-
import MySQLdb

class MysqldbHelper:
    #获取数据库连接
    def getCon(self):
        try:
            conn=MySQLdb.connect(host='localhost',user='mjy',passwd='123',db='python',port=3306,charset='utf8')
            return conn
        except MySQLdb.Error,e:
            print "Mysqldb Error:%s" % e
    #查询方法,使用con.cursor(MySQLdb.cursors.DictCursor),返回结果为字典    
    def select(self,sql):
        try:
            con=self.getCon()
            print con
            cur=con.cursor(MySQLdb.cursors.DictCursor)
            count=cur.execute(sql)
            fc=cur.fetchall()
            return fc
        except MySQLdb.Error,e:
            print "Mysqldb Error:%s" % e
        finally:
            cur.close()
            con.close()
    #带参数的更新方法,eg:sql='insert into pythontest values(%s,%s,%s,now()',params=(6,'C#','good book')
    def updateByParam(self,sql,params):
        try:
            con=self.getCon()
            cur=con.cursor()
            count=cur.execute(sql,params)
            con.commit()
            return count
        except MySQLdb.Error,e:
            con.rollback()
            print "Mysqldb Error:%s" % e
        finally:
            cur.close()
            con.close()
    #不带参数的更新方法
    def update(self,sql):
        try:
            con=self.getCon()
            cur=con.cursor()
            count=cur.execute(sql)
            con.commit()
            return count
        except MySQLdb.Error,e:
            con.rollback()
            print "Mysqldb Error:%s" % e
        finally:
            cur.close()
            con.close()
            
if __name__ == "__main__":
    db=MysqldbHelper() 
    def get(): 
        sql="select * from pythontest"
        fc=db.select(sql)
        for row in fc:
            print row["ptime"]
            
    def ins():
        sql="insert into pythontest values(5,'数据结构','this is a big book',now())"
        count=db.update(sql)
        print count
    def insparam():
        sql="insert into pythontest values(%s,%s,%s,now())"
        params=(6,'C#','good book')
        count=db.updateByParam(sql,params)
        print count
    def delop():
        sql="delete from pythontest where pid=4"
        count=db.update(sql)
        print "the:"+str(count)
    def change():
        sql="update pythontest set pcontent='c# is a good book' where pid=6"
        count=db.update(sql)
        print count
        
    #get()     
    #ins()
    #insparam()
    #delop()
    #change()
    
            
            
    
    

附查询结果:




  • 1
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Python中的MySQLdb模块来封装MySQL增删改查类,关键步骤如下:1、首先,在代码中引入MySQLdb模块;2、接着,创建连接对象,连接MySQL数据库;3、随后,编写增删改查操作,实现业务逻辑;4、最后,关闭连接,释放资源。 ### 回答2: 封装一个PythonMySQL增删改查类可以通过使用Python的`pymysql`库来实现。下面是一个示例代码,实现了一个MySQL增删改查类。 ```python import pymysql class MySQLHelper: def __init__(self, host, user, password, database): self.host = host self.user = user self.password = password self.database = database self.connection = self.connect() def connect(self): try: connection = pymysql.connect( host=self.host, user=self.user, password=self.password, database=self.database, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) print("Connected to MySQL database") return connection except pymysql.Error as e: print(f"Connection failed: {e}") return None def execute_query(self, query, params=None): with self.connection.cursor() as cursor: try: cursor.execute(query, params) result = cursor.fetchall() return result except pymysql.Error as e: print(f"Query execution failed: {e}") return None def execute_update(self, query, params=None): with self.connection.cursor() as cursor: try: cursor.execute(query, params) self.connection.commit() return True except pymysql.Error as e: print(f"Update execution failed: {e}") self.connection.rollback() return False def close(self): if self.connection: self.connection.close() print("Connection closed") if __name__ == '__main__': host = "localhost" user = "root" password = "your_password" database = "your_database" helper = MySQLHelper(host, user, password, database) # 执行查询 result = helper.execute_query("SELECT * FROM your_table") if result is not None: for row in result: print(row) # 执行更新 success = helper.execute_update("UPDATE your_table SET column1 = %s WHERE column2 = %s", ("new_value", "condition")) if success: print("Update successful") helper.close() ``` 这个类封装了与MySQL数据库的连接、查询和更新操作。在实例化时,需要传入数据库的主机名、用户名、密码和数据库名,然后可以使用`execute_query()`方法来执行查询语句并获得结果,使用`execute_update()`方法来执行更新语句。最后,使用`close()`方法来关闭数据库连接。请注意,需要替换`your_password`、`your_database`、`your_table`和`condition`为实际的值。 ### 回答3: 在Python封装MySQL增删改查类的关键步骤如下: 第一步:导入所需模块 首先,我们需要导入`mysql.connector`模块来连接MySQL数据库。 ```Python import mysql.connector ``` 第二步:定义一个MySQL增删改查类 我们可以创建一个类来封装MySQL增删改查操作。在这个类中,我们可以定义一些方法来执行具体的操作。 ```Python class MySQLManager: def __init__(self, host, user, password, database): self.host = host self.user = user self.password = password self.database = database self.conn = mysql.connector.connect( host=self.host, user=self.user, password=self.password, database=self.database ) def execute_query(self, query): cursor = self.conn.cursor() cursor.execute(query) result = cursor.fetchall() cursor.close() return result def execute_update(self, query): cursor = self.conn.cursor() cursor.execute(query) self.conn.commit() cursor.close() ``` 在`__init__`方法中,我们通过`mysql.connector.connect`方法连接到MySQL数据库。在`execute_query`方法中,我们执行查询操作,并返回结果。在`execute_update`方法中,我们执行插入、更新或删除操作,并提交更改。 第三步:实例化MySQL增删改查类 现在,我们可以实例化`MySQLManager`类,并调用相应的方法来执行MySQL增删改查操作。 ```Python manager = MySQLManager(host='localhost', user='root', password='password', database='test') result = manager.execute_query('SELECT * FROM my_table') manager.execute_update('INSERT INTO my_table (column1, column2) VALUES (value1, value2)') ``` 在实例化时,我们需要传入正确的主机名、用户名、密码和数据库名。 通过调用`execute_query`方法,我们可以执行查询并获取结果。 通过调用`execute_update`方法,我们可以执行插入、更新或删除操作。 这样,我们就可以使用Python封装MySQL增删改查类来执行相关的操作了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值