Python對MySQL資料庫的操作

來源:互聯網
上載者:User

標籤:python   資料庫   mysql   

Python中,可以使用MySQLdb模組串連到MySQL資料庫,對MySQL資料庫進行操作


第一步】 MySQL安裝

參考文檔: http://blog.csdn.net/Jerry_1126/article/details/20837397 


第二步串連到MySQL

  • 建立資料庫

Welcome to the MySQL monitor.  Commands end with ; or \g.Your MySQL connection id is 5Server version: 5.5.19 MySQL Community Server (GPL)mysql>#建立資料庫mysql> create database python;Query OK, 1 row affected (0.09 sec)#使用資料庫mysql> use python;Database changed#建立表mysql> create table people (name VARCHAR(30), age INT, sex CHAR(1));Query OK, 0 rows affected (0.44 sec)#插入資料mysql> insert into people values('Tom', 20, 'M');Query OK, 1 row affected (0.13 sec)mysql> insert into people values('Jack', NULL, NULL);Query OK, 1 row affected (0.06 sec)#查看資料mysql> select * from people;+------+------+------+| name | age  | sex  |+------+------+------+| Tom  |   20 | M    || Jack | NULL | NULL |+------+------+------+2 rows in set (0.05 sec)
  • 安裝MySQLdb

官方網站: http://sourceforge.net/projects/mysql-python

下載與自己作業系統,Python版本吻合的exe檔案,點擊下一步即可完成安裝。如下,則表示安裝成功!
>>> import MySQLdb>>> 

  • 在Python中使用MySQL

import MySQLdb                                             # 匯入MySQLdb模組db = MySQLdb.connect(host   = 'localhost',                 # 串連到資料庫,伺服器為本機                                       user   = 'root',                      # 使用者名稱為:root                     passwd = '1234',                      # 密碼為:1234                     db     = 'python')                    # 資料庫:pythoncur = db.cursor()                                          # 獲得資料庫遊標                        cur.execute('insert into people values("Jee", 21, "F")')   # 執行SQL,添加記錄res = cur.execute('delete from people where age=20')       # 執行SQL,刪除記錄   db.commit()                                                # 提交事務res = cur.execute('select * from people')                  # 執行SQL, 擷取記錄res = cur.fetchall()                                       # 擷取全部資料print(res)                                                 # 列印資料cur.close()                                                # 關閉遊標db.close()                                                 # 關閉資料庫連接 


具體API定義,請參考:

http://blog.csdn.net/jerry_1126/article/details/40037899



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.