python怎麼連線資料庫
Python3.x連線MySQL的方案有:oursql,PyMySQL,myconnpy等,這裡主要是安裝pymysql。
1、安裝
pymysql安裝:找到python資料夾pip程式的位置開啟命令視窗:
pip install pymysql3
2、使用
安裝完畢後,資料庫連線的具體步驟如下:
·引入 API 模組。
·獲取與資料庫的連線。
·執行SQL語句和儲存過程。
·關閉資料庫連線。
相關推薦:《》
程式碼如下:
import pymysql #查詢 #連線資料庫 conn = pymysql.connect(host='資料庫伺服器名',user='使用者名稱',passwd='密碼',db='資料庫名',pot='資料路埠號', charset='utf8') #獲取遊標 cur = conn.cursor() cur.execute('資料庫查詢語句') #獲取資料,fetchone獲取一條資料,fetchall獲取全部資料 data = cur.fetchall() for d in data: print(d) #關閉遊標 cur.close() #關閉資料庫 conn.close() #插入、刪除,修改操作 #連線資料庫 conn = pymysql.connect(host='資料庫伺服器名',user='使用者名稱',passwd='密碼',db='資料庫名',pot='資料路埠號', charset='utf8') #獲取遊標 cur = conn.cursor() cur.execute('資料庫插入語句') #提交當前事務到資料庫 conn.commit() #rowcount:返回資料條數或影響行數 print('插入:',cur.rowcount,'條資料') #關閉遊標 cur.close() #關閉資料庫 conn.close()
對資料庫的操作中可以加入try...except語句捕捉錯誤,發生錯誤時,可以回滾資料庫操作,回到修改前:
try: # 執行sql語句 cur.execute(sql) # 提交到資料庫執行 cur.commit() except: # 發生錯誤時回滾 cur.rollback() # 關閉遊標 cur.close() #關閉資料庫 conn.close()
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/4422/viewspace-2836496/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- mysql資料庫怎麼連線MySql資料庫
- Pycharm 怎麼連線 MySQL 資料庫PyCharmMySql資料庫
- python資料庫連線池Python資料庫
- Python 連線 Oracle資料庫PythonOracle資料庫
- Python連線SQLite資料庫PythonSQLite資料庫
- 使用Python連線資料庫Python資料庫
- Python連線oracle資料庫PythonOracle資料庫
- Python連線mysql資料庫PythonMySql資料庫
- python 連線 mongo 資料庫連線超時PythonGo資料庫
- 資料庫三表連線查詢怎麼做資料庫
- python資料插入連線MySQL資料庫PythonMySql資料庫
- Python資料庫連線池DButilsPython資料庫
- 資料庫與python的連線資料庫Python
- python連線資料庫測試Python資料庫
- 【Oracle】Python 連線Oracle 資料庫OraclePython資料庫
- python怎麼連線mysqlPythonMySql
- Jtti:連線不上SQL資料庫怎麼解決?JttiSQL資料庫
- 用Navicat連線資料庫-資料庫連線(MySQL演示)資料庫MySql
- python操作MySQL資料庫連線(pymysql)PythonMySql資料庫
- 如何掌握python連線redis資料庫?PythonRedis資料庫
- python連線mysql資料庫步驟PythonMySql資料庫
- python3.4連線oracle資料庫PythonOracle資料庫
- python3.6連線oracle資料庫PythonOracle資料庫
- 連線資料庫資料庫
- 資料庫連線資料庫
- python 怎麼連線 sql server,不是連線 mysqlPythonServerMySql
- 寶塔皮膚 資料庫怎麼連資料庫
- Python 連線mysql資料庫進行操作PythonMySql資料庫
- python+selenium 連線MySQL資料庫PythonMySql資料庫
- Python 中的 MySQL 資料庫連線池PythonMySql資料庫
- Python連線資料庫程式碼結構Python資料庫
- JDBC連線資料庫JDBC資料庫
- java連線資料庫Java資料庫
- Mybatis連線資料庫MyBatis資料庫
- Mongodb資料庫連線MongoDB資料庫
- mysqli連線資料庫MySql資料庫
- 資料庫的連線資料庫
- 連線mysql資料庫MySql資料庫