美文网首页python学习
python连接使用mysql数据库

python连接使用mysql数据库

作者: 小阿六Minasix | 来源:发表于2020-11-09 10:44 被阅读0次

    1.安装pymysql模块

    方法:pip install pymysql

    2.代码示例

    import pymysql
    
    bdk = pymysql.Connect(host="127.0.0.1",port=3306,user="root",password="123456",database="forpython")
    cursor=bdk.cursor()
    
    
    def bdk_lj():
        #打开数据库连接
        global bdk
    
    def bdk_sql(sql):
        #取sql查到的最后一条数据
    
        #使用cursor()方法创建游标对象cursor
        global cursor
        #使用execute()方法执行sql
        sql_result=cursor.execute(sql)
        result_one=cursor.fetchone()
        return result_one
    
    
    def bdk_sqlall(sql):
        # 取sql查到的所有数据
    
        # 使用cursor()方法创建游标对象cursor
        global cursor
        # 使用execute()方法执行sql
        sql_result = cursor.execute(sql)
        result_all = cursor.fetchsall()
        result_list=list(result_all)
    
        #将元组列表转化为可写的二维列表
        listlist=[]
        for cpn in result_list:
            listlist.append(list(cpn))
        return listlist
    
    def bdk_gb():
        global bdk
        bdk.close()
    
    
    if __name__=='__main__':
        bdk_lj()
        sql="SELECT * FROM CHANPIN WHERE ID = '1'"
        ress=bdk_sql(sql)
        print(ress)
        bdk_gb()
    

    相关文章

      网友评论

        本文标题:python连接使用mysql数据库

        本文链接:https://www.haomeiwen.com/subject/xwklbktx.html