1. 使用
import MySQLdb
1.1. 連接
conn = MySQLdb.Connection(host, user, password, dbname)
1.2. 選擇數據庫,如果上面沒有指定數據庫,則使用此方法指定!
conn.select_db(’database name’)
1.3. 獲得cursor
cur = conn.cursor()
1.4. cursor位置設定
cur.scroll(int, mode)
mode可為相對位置或者絕對位置,分別為relative和absolute。
1.5. select
cur.execute(‘select clause’)
例如
cur.execute(‘select * from mytable’)
row = cur.fetchall()
或者:
row1 = cur.fetchone()
1.6. insert
cur.execute(‘inset clause’)
例如
cur.execute("insert into user (Name, Password) values ('maggie','12345')")
conn.commit()
1.7. update
cur.execute(‘update clause’)
例如
cur.execute("update user set Name = 'eric chau' where id = 1")
conn.commit()
1.8. delete
cur.execute(‘delete clause’)
例如
cur.execute("delete from user where id = 1")
conn.commit()
完整代碼:
from MySQLdb import Connect
def conn():
#conn = Connect('localhost','root','root')
#conn.select_db('eric')
conn = Connect('localhost','root','root','eric')
cur = conn.cursor()
cur.execute('select * from user')
cur.scroll(0)
row1 = cur.fetchone()
print 'id:', row1[0]
print 'name:', row1[1]
print 'password:', row1[2]
#cur.execute("insert into user (Name, Password) values ('maggie','12345')")
#cur.execute("update user set Name = 'eric chau' where id = 1")
cur.execute("delete from user where id = 11")
conn.commit()
if __name__=='__main__':
conn()