Python筆記13-操作數據庫

【安裝MySQL-python】

要想使python可以操作mysql 就需要MySQL-python驅動,它是python 操作mysql必不可少的模塊。下載地址:https://pypi.python.org/pypi/MySQL-python/

檢查MySQLdb 模塊是否可以正常導入:import MySQLdb

 

【python 操作mysql數據庫基礎 01.py】

#coding=utf-8
import MySQLdb
#Connect() 方法用於創建數據庫的連接,裏面可以指定參數:用戶名,密碼,主機等信息。
#這只是連接到了數據庫,要想操作數據庫需要創建遊標。
conn= MySQLdb.connect(
    host='localhost',
    port = 3306,
    user='root',
    passwd='',
    db ='rxpython',
)
#通過獲取到的數據庫連接conn下的cursor()方法來創建遊標。
#通過遊標cur 操作execute()方法可以寫入純sql語句。
#通過execute()方法中寫如sql語句來對數據進行操作。
cur = conn.cursor()
#創建數據表
#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
#插入一條數據
#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
#修改查詢條件的數據
#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
#刪除查詢條件的數據
#cur.execute("delete from student where age='9'")
#cur.close() 關閉遊標
cur.close()
#conn.commit()方法在提交事物,在向數據庫插入一條數據時必須要有這個方法,否則數據不會被真正的插入。
conn.commit()
#Conn.close()關閉數據庫連接
conn.close()

【我要想插入新的數據,必須要對這條語句中的值做修改。我們可以做如下修改: 02.py】

sqli = "insert into student values(%s,%s,%s,%s)"
cur.execute(sqli,('3','renxing','wwwwww','7'))

【一次性向數據表中插入多條值 03.py】

sqli = "insert into student values(%s,%s,%s,%s)"
cur.executemany(sqli,[
    ('11','zhang','aaaaa','1001'),
    ('12','wang','bbbbb','1002'),
    ('13','li','ccccc','1003'),
    ('14','zhao','ddddd','1004'),
]) 

【查詢語句 04.py】

(1)aa=cur.execute("select * from student"); print aa; ----> 獲得的只是表中有多少條數據。

(2)fetchone() 方法可以獲得表中的數據,可是每執行一次,遊標會從表中的第一條數據移動到下一條數據的位置。scroll(0,'absolute') 方法可以將遊標定位到表中的第一條數據。

(3)獲得表中的多條數據並打印出來,使用 fetchmany()

【代碼】https://github.com/rxbook/study-python/tree/master/13

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章