python 学习笔记-操作mysql

来源:互联网 发布:通用编程器报价 编辑:程序博客网 时间:2024/05/29 11:59
import pymysqldef connDB():    #连接数据库    conn=pymysql.connect(host='localhost',user='root',passwd='',db='first')    cur=conn.cursor()    return (conn,cur)def exeUpdate(conn,cur,sql):    #更新语句,可执行Update,Insert语句    sta=cur.execute(sql)    conn.commit()    return (sta)def exeDelete(conn,cur,IDs):    #删除语句,可批量删除    for eachID in IDs.split(' '):        sta=cur.execute('delete from students where Id=%d'%int(eachID))    conn.commit()    return (sta)def exeQuery(cur,sql):    #查询语句    cur.execute(sql)    result = cur.fetchone()    return (result)def connClose(conn,cur):    #关闭所有连接    cur.close()    conn.close()conn = connDB()[0]cur = connDB()[1]exeUpdate(conn,cur,"INSERT INTO first_note (idfirst_note, note_title , note_content ) VALUES (0,'Title','This is the content');")print(exeQuery(cur,"SELECT note_title ,note_content FROM first_note;"))connClose()

创建:

通过conn=pymysql.connect(host=’localhost’,user=’root’,passwd=”,db=’first’)方法获取一个connection对象。connection对象类似于数据操作过程中的管道,我们数据操作都是在connection之上进行的。然后再通过cur=conn.cursor()获取游标,游标对象则类似于管道中的载体,进行数据的传送。有了cur我们才能直接操作数据库。

增删查改:

代码中我们把增删查改分成四个函数,事实上这四个操作都是调用cur.execute()进行的,也就是直接使用SQL语言进行数据库操作。如果有必要我们应该对它们再次封装便于使用。具体代码看上面。

关闭:

最后我们使用cur.close() conn.close()分别关闭游标和connection对象,这样就结束了一次数据操作。

0 0