zoukankan      html  css  js  c++  java
  • python的MySQLdb库基本使用介绍

    MySQLdb库

    import MySQLdb

    简介

    提供mysql的基本操作(包括建表,读取表数据,插入数据到表)

    数据库操作基本步骤

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import MySQLdb
    
    if __name__ == "__main__":
        # 打开数据库连接
        db = MySQLdb.connect("localhost", "root", "root", "iquota", charset='utf8')
    
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
    
        # 查看表
        sql_cmd="select * from app;"
    
        cursor.execute(sql_cmd)
        data = cursor.fetchone()
        data_all = cursor.fetchall()
    
        # 关闭数据库连接
        db.close()
    
        # 读取一行
        print data
        # 读取全部内容
        print data_all
    mysql基本读取举例

    输出结果

    (10L, u'5c26736821d24de48942d982b1c69000', u'qa-stress', u'qa app for stress test', u'zhangsan')
    ((11L, u'5c26736821d24de48942d982b1c69000', u'qa-stress', u'qa app for stress test', u'lisi'), (12L, u'37ea7ce186404c2ea3a1fb4079d58c15', u'qa-stress-test', u'qa app for stress test', u'zhangsan'), (13L, u'37ea7ce186404c2ea3a1fb4079d58c15', u'qa-stress-test', u'qa app for stress test', u'lisi'), (14L, u'283182bf5ffe4398932d72e9a6d239cc', u'app1', u'add_request', u'lisi'), (21L, u'394c56cde2cb4434a01cff43defcc0a6', u'liurong07Test', u'add_request', u'lisi'))
    View Code

    简单demo

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import MySQLdb
    
    
    DB_HOST = "120.92.81.22"
    DB_PORT = 55219
    DB_USER = "admin"
    DB_PASSWORD = "LIUrong123@"
    
    
    def cyc_execute(cmd, num):
    
        # 打开数据库
        db = MySQLdb.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, passwd=DB_PASSWORD, charset='utf8')
    
        # 获取游标
        cursor = db.cursor()
    
    
        # 循环执行sql
        for i in range(0, num):
    
            # 执行sql
            cursor.execute(cmd)
    
            # 获取数据
            data = cursor.fetchone()
    
            # 打印结果
            print "Database version : %s " % data
    
        # 关闭数据库
        db.close()
    
    
    
    if __name__ == "__main__":
    
        sql_cmd = "select user();"
        num = 10
    
        cyc_execute(sql_cmd, num)
    

      

    大道至简
  • 相关阅读:
    pyqt 过滤事件
    python 编码问题
    xpath使用
    BeautifulSoup
    webpack.config.js 大概架构(3)
    图片,html,和其他的打包(2)
    今天开始第一篇
    第一次面试前端,记录下
    阻止默认事件和冒泡
    cookit localStorage sessionStorage 区别
  • 原文地址:https://www.cnblogs.com/liurong07/p/9816316.html
Copyright © 2011-2022 走看看