Python串連MySQL資料庫

來源:互聯網
上載者:User

標籤:python   mysql   

linux和windows下安裝並啟動mysql資料庫

python安裝MySQLdb包,建議使用pip安裝

pip使用方法如下:

yum install python-pip    (優先安裝python-pip才能使用pip)

pip類似於linux中的yum

pip install ipython    (安裝python補全工具)

pip uninstall ipython    (使用pip卸載ipython)

pip list    (查看安裝了哪些包)

pip install ipython==1.2.1    (適用於python2.6的版本)


python串連mysql

例子:

定義一個connect_mysql函數,在函數中指定mysql串連參數,如下所示

import MySQLdb

def connect_mysql():

    db_config = {

        ‘host‘: ‘192.168.1.1‘,

        ‘port‘: 3306,

        ‘user‘: ‘zabbix‘,

        ‘passwd‘: ‘123456‘,

        ‘db‘: ‘zabbix_user‘,

        ‘charset‘: ‘utf8‘

    }

try:

    cnx = MySQLdb.connect(**db_config)

except Exception as e:

        raise e

    return cnx

connect_mysql()

遊標操作

例子:

import MySQLdb

def connect_mysql():

    db_config = {

        ‘host‘: ‘192.168.48.128‘,

        ‘port‘: 3306,

        ‘user‘: ‘xiang‘,

        ‘passwd‘: ‘123456‘,

        ‘db‘: ‘python‘,

        ‘charset‘: ‘utf8‘

    }

    try:

    cnx = MySQLdb.connect(**db_config)

except Exception as e:

        raise e

    return cnx

if __name__ == ‘__main__‘:

    cnx = connect_mysql()

    #cursor():建立遊標對象

    cus = cnx.cursor()

    sql  = ‘‘‘create table test(id int not null);insert into test(id) values (100);‘‘‘

    try:

        #excute(sql[, args]):執行一個資料庫查詢或命令

        cus.execute(sql)

#close():關閉此遊標對象

        cus.close()

#提交遊標對象

        cnx.commit()

    except Exception as e:

#復原遊標對象到commi之前

        cnx.rollback()

        raise e

    finally:

        cnx.close()


本文出自 “粗糧麵包” 部落格,請務必保留此出處http://culiangmianbao.blog.51cto.com/10475024/1983635

Python串連MySQL資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.