Python MySQLdb模块连接操作mysql数据库实例_python
生活随笔
收集整理的這篇文章主要介紹了
Python MySQLdb模块连接操作mysql数据库实例_python
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
mysql是一個優秀的開源數據庫,它現在的應用非常的廣泛,因此很有必要簡單的介紹一下用python操作mysql數據庫的方法。python操作數據庫需要安裝一個第三方的模塊,在http://mysql-python.sourceforge.net/有下載和文檔。
由于python的數據庫模塊有專門的數據庫模塊的規范,所以,其實不管使用哪種數據庫的方法都大同小異的,這里就給出一段示范的代碼:
#-*- encoding: gb2312 -*- import os, sys, string import MySQLdb# 連接數據庫 try:conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1') except Exception, e:print esys.exit()# 獲取cursor對象來進行操作cursor = conn.cursor() # 創建表 sql = "create table if not exists test1(name varchar(128) primary key, age int(4))" cursor.execute(sql) # 插入數據 sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23) try:cursor.execute(sql) except Exception, e:print esql = "insert into test1(name, age) values ('%s', %d)" % ("張三", 21) try:cursor.execute(sql) except Exception, e:print e # 插入多條sql = "insert into test1(name, age) values (%s, %s)" val = (("李四", 24), ("王五", 25), ("洪六", 26)) try:cursor.executemany(sql, val) except Exception, e:print e#查詢出數據 sql = "select * from test1" cursor.execute(sql) alldata = cursor.fetchall() # 如果有數據返回,就循環輸出, alldata是有個二維的列表 if alldata:for rec in alldata:print rec[0], rec[1]cursor.close()conn.close()?
以上是云棲社區小編為您精心準備的的內容,在云棲社區的博客、問答、公眾號、人物、課程等欄目也有的相關內容,歡迎繼續使用右上角搜索按鈕進行搜索python MySQLdb模塊 mysqldb mysql python、mysql數據庫設計實例、mysql數據庫實例、mysql數據庫開發實例、mysql數據庫實例下載,以便于您獲取更多的相關知識。
轉載于:https://www.cnblogs.com/adolfmc/p/7461304.html
總結
以上是生活随笔為你收集整理的Python MySQLdb模块连接操作mysql数据库实例_python的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python的引用计数分析(二)
- 下一篇: linux软件管理(Vim编辑器使用)