python 操作數據庫1--連接、執行sql語句



#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2017/11/20 16:03
# @Author : lijunjiang
# @File   : demo.py

import MySQLdb

# 連接數據庫
# host 數據庫IP
# port 數據庫監聽端口
# user 數據庫用戶
# passwd 用戶密碼
# db 數據庫名
# charset 字符集  默認uft-8

# MySQLdb.Connect 方法
#comn=MySQLdb.Connect(host="11.11.11.11",user="python",passwd="python",db="python",charset="utf8",port=3306)

# 函數型式
def connect_mysql():
    db_config = dict(host="11.11.11.11", port=3306, db="python", charset="utf8", user="python", passwd="python")
    try:
        cnx = MySQLdb.connect(**db_config)
    except Exception as err:
        raise err
    return cnx

if __name__ == "__main__":
    sql = "create table test(id int not null);"
    cnx = connect_mysql()  # 連接mysql
    cns = cnx.cursor()     # 創建一個游標對象
    # print(dir(cnx))

    try:
        cns.execute(sql)    # 執行 sql execute執行一條語句
        cns.close()         # 關閉游標
        cnx.commit()        # 提交操作
    except Exception as err:
        raise err
    finally:
        cnx.close()         # 關閉連接

# 執行多條語
    sql_many = 'insert into test(id) value (%s);'
    param = []
    for i in xrange(90,101):
        param.append([str(i)])
    # print(param)

    cnx = connect_mysql()  
    cus = cnx.cursor()

    try:
        cus.executemany(sql_many,param)   # executemany()接收一個sql語句,一個列表
        # print(dir(cus))
        cus.close()
    except Exception as err:
        raise err
    finally:
        cnx.close()

# 獲取執行結果

    sql_select = 'select * from test;'

    cnx = connect_mysql()
    cus = cnx.cursor()

    try:
        cus.execute(sql_select)

        result_one = cus.fetchone()     # fetchone()  獲取一條結果
        print("resutl1 {0}",format(result_one))

        result_many = cus.fetchmany(3)   # fetchmany(n) 獲取n條結果
        print("resutl1 {0}", format(result_many))

        result_all = cus.fetchall()      # fetchall()  獲取所有結果
        print("resutl1 {0}", format(result_all))
        cus.close()
    except Exception as err:
        raise err
    finally:
        cnx.close()

mysql> select * from test;
+-----+
| id  |
+-----+
|  90 |
|  91 |
|  92 |
|  93 |
|  94 |
|  95 |
|  96 |
|  97 |
|  98 |
|  99 |
| 100 |
+-----+
11 rows in set (0.00 sec)



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM