1. 程式人生 > >python連線資料庫查詢DEMO

python連線資料庫查詢DEMO

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# __author__ :zhuhongqiang
import pymysql as MySQLdb

dburl = "127.0.0.1"
username = "root"
password = "root"
dbname = "test"


# 根據sql 操作資料庫
def getConnection(sql,type): #1:查詢 2:增刪改
    connections = MySQLdb.connect(dburl, username, password, dbname,charset="utf8")
    # 使用cursor()方法獲取操作遊標
    cursor = connections.cursor()
    results = ""
    create_table_sql ="CREATE TABLE IF NOT EXISTS `user001` " \
                      "(`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(20) DEFAULT '' COMMENT '使用者名稱'," \
                      "`age` int(2) DEFAULT '0' COMMENT '年齡',`sex` tinyint(1) DEFAULT '0' COMMENT '0:男1:女'," \
                      "PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8"
    try:
        # 執行sql語句
        cursor.execute(create_table_sql)
        cursor.execute(sql)
        # 提交到資料庫執行
        connections.commit()
        # 獲取所有記錄列表
        if type==1:
            results = cursor.fetchall()
        elif type ==2:
            results=cursor.rowcount
        else:
            results = "請求型別引數未識別..."
        print("主鍵: %d " %cursor.lastrowid)
        print(results)
    except Exception as e:
        # Rollback in case there is any error
        print("get db is error....",e)
        connections.rollback()
    finally:
        cursor.close()
        connections.close()
    return results


if __name__ == "__main__":
    userName ="jack"
    age = 18
    sex = 1
    sql = "INSERT INTO `test`.`user001` (`username`, `age`, `sex`) VALUES ('%s', '%s', '%d')" % (userName,age,sex) #插入
    # sql =" select * from user001" #查詢
    # sql =" UPDATE user001 SET username="李斯特" where id =1" #修改
    # sql ="DELETE FROM user001 WHERE id =1" #刪除
    result = getConnection(sql,2)