ubuntu下安裝MySQLdbpython
sudo apt-get install python-MySQLdb
導入MySQLdb庫mysql
import MySQLdb
建立數據庫鏈接git
conn = MySQLdb.connect(host="localhost",user="root",passwd="123456",db="test",charset="utf8")
commit()
:若是數據庫表進行了修改,提交保存當前的數據。固然,若是此用戶沒有權限就做罷了,什麼也不會發生。rollback()
:若是有權限,就取消當前的操做,不然報錯。cursor([cursorclass])
:遊標指針。建立遊標(指針)cursorgithub
cur = conn.cursor()
execute(query, args)
:執行單條sql語句。query爲sql語句自己,args爲參數值的列表。執行後返回值爲受影響的行數。executemany(query, args)
:執行單條sql語句,可是重複執行參數列表裏的參數,返回值爲受影響的行數在數據表中插入一條記錄sql
cur.execute("insert into users (username,password,email) values (%s,%s,%s)",("python","123456","python@gmail.com"))
在數據表中插入多條記錄docker
cur.executemany("insert into users (username,password,email) values (%s,%s,%s)",(("google","111222","g@gmail.com"),("facebook","222333","f@face.book"),("github","333444","git@hub.com"),("docker","444555","doc@ker.com")))
提交數據庫操做數據庫
conn.commit()
查詢數據ubuntu
cur.execute("select * from users")
fetchall(self)
:接收所有的返回結果行.fetchmany(size=None)
:接收size條返回結果行.若是size的值大於返回的結果行的數量,則會返回cursor.arraysize條數據.fetchone()
:返回一條結果行.scroll(value, mode='relative')
:移動指針到某一行.若是mode='relative',則表示從當前所在行移動value條,若是mode='absolute',則表示從結果集的第一行移動value條.fetch
cur.execute("select * from users") lines = cur.fetchall() for line in lines: print line cur.execute("select * from users where id=1") line_first = cur.fetchone() #只返回一條 print line_first cur.execute("select * from users") print cur.fetchall()
遊標cursor的操做
cur.scroll(n)
或cur.scroll(n,"relative")
:意思是相對當前位置向上或者向下移動,n爲正數,表示向下(向前),n爲負數,表示向上(向後)
還有一種方式,能夠實現「絕對」移動,不是「相對」移動:增長一個參數"absolute"
cur.scroll(1) cur.scroll(-2) cur.scroll(2,"absolute") #回到序號是2,但指向第三條
更新數據
cur.execute("update users set username=%s where id=2",("mypython")) conn.commit()
指定數據庫
conn = MySQLdb.connect("localhost","root","123456",port=3306,charset="utf8") #建立數據庫時不指定那個數據庫 conn.select_db("test") #鏈接建立後再指定
關閉數據庫
cur.close() #先關閉遊標 conn.close() #再關閉數據庫