標籤: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)
官方網站: http://sourceforge.net/projects/mysql-python
下載與自己作業系統,Python版本吻合的exe檔案,點擊下一步即可完成安裝。如下,則表示安裝成功!
>>> import MySQLdb>>>
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資料庫的操作