Python實戰之MySQL資料庫操作
阿新 • • 發佈:2018-11-12
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
本文地址:http://blog.csdn.net/kongxx/article/details/7094018
1. 要想使Python可以操作MySQL資料庫,首先需要安裝MySQL-python包,在CentOS上可以使用一下命令來安裝
$ sudo yum install MySQL-python
2. 啥都不說了,走兩步吧,下面的程式建立了一個到mysql資料庫的連線,然後執行了一個簡單的查詢,並列印查詢結果
import MySQLdbconn = MySQLdb.connect (host = "172.17.23.121", user = "fkong", passwd = "fkong", db = "fkong")cursor = conn.cursor ()cursor.execute ("SELECT VERSION()")row = cursor.fetchone ()print "MySQL server version:", row[0]cursor.close ()conn.close ()
3. 下面看一個數據庫建表和插入操作
import MySQLdbconn = MySQLdb.connect (host = "172.17.23.121", user = "fkong", passwd = "fkong", db = "fkong")cursor = conn.cursor ()cursor.execute (""" CREATE TABLE TEST ( ID INT, COL1 VARCHAR(40), COL2 VARCHAR(40), COL3 VARCHAR(40) ) """ )cursor.execute (""" INSERT INTO TEST (ID, COL1, COL2, COL3) VALUES (1, 'a', 'b', 'c'), (2, 'aa', 'bb', 'cc'), (3, 'aaa', 'bbb', 'ccc') """)conn.commit()cursor.close ()conn.close ()
4. 下面再來看看查詢,查詢通常有兩種方式:一種是使用cursor.fetchall()獲取所有查詢結果,然後再一行一行的迭代;另一種每次通過cursor.fetchone()獲取一條記錄,直到獲取的結果為空為止。看一下下面的例子:
import MySQLdbconn = MySQLdb.connect (host = "172.17.23.121", user = "fkong", passwd = "fkong", db = "fkong")cursor = conn.cursor ()cursor.execute ("SELECT * FROM TEST")rows = cursor.fetchall()for row in rows: print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3])print "Number of rows returned: %d" % cursor.rowcountcursor.execute ("SELECT * FROM TEST")while (True): row = cursor.fetchone() if row == None: break print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3]) print "Number of rows returned: %d" % cursor.rowcountcursor.close ()conn.close ()