直接在terminal中輸入 pip install MySQL-python 若沒有安裝pip工具,則先在terminal中輸入
安裝和更新pip工具
Windows下安裝MySQL-python需要先安裝C++9.0環境,進入http://aka.ms/vcpython27下載并安裝 然后打開命令行輸入: pip install MySQL-python 會自動完成安裝
安裝完成后,進行Python環境,輸入 import MySQLdb 不報錯則說明安裝成功
新建了一張表testtable,包含id和name兩列,其中id為主鍵
上面的語句執行完后將會在testtable中插入一條記錄,id自動增長,name的值為test
還可以以帶入參數的方式執行
sql = 'insert into testtable (name) values (%s)'cur.execute(sql, ("test"))conn.commit()若想要帶入多個參數,可以使用executemany()
sql = 'insert into testtable (name) values (%s)'cur.executemany(sql, [("test"), ("test2")])conn.commit()可以看出executemany是用列表傳入參數的
輸出1,只是輸出得到的結果的數量而 如果想要得到結果,可以使用fetchone()和fetchmany()函數
cur.execute('select * from testtable')cur.fetchone()# (1L, 'test')cur.fetchone()# (2L, 'test')從上述語句輸出可以看出,fetchone()有點類似迭代器的next()函數,使用cur的scroll(0,'absolute')方法可以返回到第一條數據
使用cur.fetchmany()函數可以返回一個包含所有結果的元組
results = cur.execute('select * from testtable')result_tuple = cur.fetchmany(results)print result_tuple# ((1L, 'test'),(2L, 'test'))新聞熱點
疑難解答