python 操作 mysql
查詢(兩種方法):
import MySQLdb
conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "root", db = "fish")
cursor = conn.cursor ()
cursor.execute ("SELECT * FROM polls_poll")
rows = cursor.fetchall() #獲取所有結果集
for row in rows: #從結果集中一條一條讀出來
print "%d, %s, %s" % (row[0], row[1], row[2])
print "Number of rows returned: %d" % cursor.rowcount
cursor.execute ("SELECT * FROM polls_poll")
while (True):
row = cursor.fetchone() #從結果集的開始,獲取一條記錄, 移動一下游標,直到結束返回None
if row == None:
break
print "%d, %s, %s" % (row[0], row[1], row[2])
print "Number of rows returned: %d" % cursor.rowcount
cursor.close ()
conn.close ()
插入:
cursor.execute ("INSERT INTO two(name, age) VALUES ('bill', 18)") #返回受影響的行數,執行錯誤返回異常
更新:
cursor.execute ("UPDATE two SET name = 'jack', age = '22' WHERE name = 'bill'") #返回受影響的行數,執行錯誤返回異常
本文由用戶 bc56 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!