• Python 连接数据库 day5


    import pymysql
    #连接数据库,port必须是int型,字符编码是utf8,不能是utf-8,password必须是字符串
    conn = pymysql.connect(host='数据库ip',user='user1',password='123456',
                           db='db_name',port=3306,charset='utf8',autocommit=True)#建立连接
    cur= conn.cursor()#建立游标,可以把游标当作仓库管理员
    
    cur.execute('show tables;')#只是帮你执行sql语句
    print(cur.fetchall())#获取sql语句执行的结果
    sql1="select * from app_student limit 5;"
    cur.execute(sql1)
    print(cur.fetchall())#取所有数据
    sql2="select * from app_student where name='smh'"
    cur.execute(sql2)
    print(cur.fetchone())#只取一条,若返回结果有多条,只取第一条
    sql3="select * from app_student where name ='hhh'"
    cur.execute(sql3)
    print(cur.fetchmany(3))#取几条
    sql4="insert app_student ( `name`, `sex`, `age`, `addr`, `grade`, `phone`, `gold`) " 
           "values ( 'test', 'girl', '18', 'beijing', 'jxz', '13121211111', '100');"
    cur.execute(sql4)
    conn.commit()
    #提交,update、delete、insert这些修改数据库的语句,执行需要commit才能成功
    #在connect中添加autocommit=True则自动提交
    
    cur.close()#关闭游标
    conn.close()#关闭连接,使用完了要关连接,不然会占数据库

     将sql执行返回结果转为字典格式:

    import pymysql
    #连接数据库,port必须是int型,字符编码是utf8,不能是utf-8,password必须是字符串
    conn = pymysql.connect(host='118.24.3.40',user='jxz',password='123456',
                           db='jxz',port=3306,charset='utf8',autocommit=True)#建立连接
    cur=conn.cursor(pymysql.cursors.DictCursor)#传一个游标类型,可展示为字典
    sql5= "select * from app_student where name='hhh'"
    cur.execute(sql5)
    print(cur.fetchmany(3))
    cur.close()
    conn.close()
    
    
    结果为:
    [{'id': 328, 'name': 'hhh', 'sex': 'girl', 'age': 18, 'addr': '河南省济源市北海大道32号', 'grade': '天蝎座', 'phone': '18612539012', 'gold': 100},
    {'id': 345, 'name': 'hhh', 'sex': 'girl', 'age': 18, 'addr': '河南省济源市北海大道32号', 'grade': '天蝎座', 'phone': '18612539012', 'gold': 100},
    {'id': 347, 'name': 'hhh', 'sex': 'girl', 'age': 18, 'addr': '河南省济源市北海大道32号', 'grade': '天蝎座', 'phone': '18612539012', 'gold': 100}]

     将连接数据库写为方法

    import pymysql
    
    def op_mysql(host,user,password,db,sql,port=3306,many_tag=False):#mang_tag是标识返回数据
        conn = pymysql.connect(host=host,user=user,password=password,db=db,port=port,charset='utf8',autocommit=True)
        cur = conn.cursor(pymysql.cursors.DictCursor)
        cur.execute(sql)
        if many_tag:#
            result = cur.fetchall()
        else:
            result = cur.fetchone()
        cur.close()
        conn.close()
        return result
  • 相关阅读:
    Webform中Repeater控件--绑定嵌入C#代码四种方式
    webform中listbox运用,2个相互传值练习1:
    webform基础介绍及页面传值(session,cookie)、跳转页面
    Webform 常用控件
    使用VS建立Web网站及IIS
    linq to object
    linq to sql用partial扩展属性,创建一个部分类(用于多表连接)
    LINQ 图解
    Linq to sql介绍及增、删、改、查
    数据库操作
  • 原文地址:https://www.cnblogs.com/candysalty/p/11074488.html
Copyright © 2020-2023  润新知