• record-10 程序与数据库


    #__author: hasee
    #date:  2018/1/17
    
    # python程序连接数据库,需要提前准备好第三方库(不同类型的数据库第三方库不同)
    # 利用python开发环境中自带的pip工具完成第三方库的安装   pip install pymysql
    
    
    
    # 数据库连接过程
    # 1、准备第三方库
    # 2、在程序中import模块
    # 3、利用pymysql模块中的connect建立与数据库服务器的连接
    # 4、建立连接后返回连接对象
    # 4.1 close()
    # 4.2 commit()
    # 4.3 rollback()
    # 4.4 cursor()
    # 5、利用连接对象调用cursor()创建一个游标对象,完成对数据库的操作
    # 5.1 execute()
    # 5.2 executemany()
    # 5.3 callproc()
    # 5.4 fetchone() 在执行了SELECT命令后
    # 5.5 fetchall() 在执行了SELECT命令后
    # 5.6 fetchmany()在执行了SELECT命令后
    # 5.7 close()
    # 6、如果对数据库做了增、删、改操作,需要commit()
    # 7、释放游标、释放连接
    
    import pymysql
    
    # connect()函数返回一个数据库连接对象,主要负责管理程序与数据库的连接
    # grant all on *.* to 'root'@'%' identified by '123456'
    # flush previleges
    
    conn = pymysql.connect(host='192.168.8.30', port=3306, user='root', password='123456', db='test', charset='utf8')
    
    cur = conn.cursor()  # 创建游标对象,主要负责完成数据库中数据的具体操作
    
    cur.execute('select * from student')
    # result1=cur.fetchone() #readline()相似
    # print(result1) #fetchone()获取结果集中的一行记录,并把这一行记录中的多个属性值放到元组中管理
    
    # result2=cur.fetchall() #readlines相似
    # print(result2) #fetchall()获取多行记录,每行记录包含多个属性值  放到元组(嵌套)中管理  外层元组管理多行记录,内层元组管理每行记录的多个属性值
    
    # result3=cur.fetchmany(2) #同fetchall()类似,需要指定获取的记录数量
    # print(result3)
    
    
    # result=cur.execute('insert into student values(1,"zhangsan"))  #execute()返回值为SQL命令执行后,数据库中收到影响的记录数量
    # cur.execute('insert into student values(%d,%r)'%(i,'zhangsan'+str(i)))
    
    # cur.execute('insert into student values(%d,"zhangsan")'%10) #字符串格式化
    # cur.execute('insert into student values(%s,"zhangsan")',10) #第二个参数
    # cur.execute('insert into student values(%s,%s)',[10,'zhangsan'])
    # cur.execute('insert into student values(%s,%s),(%s,%s)',[10,'zhangsan',20,'lisi'])
    
    # cur.executemany('insert into student values(%s,"zhangsan")',[1,2,3,4,5]) #executemany() 将同样一条SQL命令重复执行多次,相当于execute()+for循环
    # cur.executemany('insert into student values(%s,%s)',[[1,'zhangsan'],[2,'lisi'],[3,'wangwu']])
    '''
    for i in range(1,6):
        cur.execute('insert into student values(%s,"zhangsan")',i)
    '''
    
    # cur.callproc('p1') #完成数据库中已经定义好的存储过程的调用(存储过程不能有输出参数)
    
    cur.close()
    conn.commit()  # 提交事务,程序中对数据库做的操作默认都是属于同一个事务的
    # conn.rollback() #撤销事务
    conn.close()
    

      

  • 相关阅读:
    程序集重用
    bash on windows
    NET 2016
    C#_事件
    AspNetCore.Hosting
    你是否是团队里面最默默付出的那个coder,却发现滔滔不绝的产品和设计是团队里的开心果(转)
    redis来共享各个服务器的session,并同时通过redis来缓存一些常用的资源,加快用户获得请求资源的速度(转)
    使用MYCAT作为Mysql HA的中间件(转)
    cookie是指web浏览器存储的少量数据,该数据会在每次请求一个相关的URL时自动传到服务器中(转)
    网页favicon.ico图标设置(转)
  • 原文地址:https://www.cnblogs.com/minkillmax/p/8305079.html
Copyright © 2020-2023  润新知