posts - 431,  comments - 344,  trackbacks - 0
          首先下載MySQLdb,地址:http://sourceforge.net/projects/mysql-python/

          1.   使用
              import MySQLdb
          1.1.   連接
              conn =   MySQLdb.Connection(host, user, password, dbname)
          1.2.   選擇數據庫,如果上面沒有指定數據庫,則使用此方法指定!
              conn.select_db(’database name’)
          1.3.   獲得cursor
              cur =   conn.cursor()
          1.4.   cursor位置設定
              cur.scroll(int, mode)
              mode可為相對位置或者絕對位置,分別為relative和absolute。
          1.5.   select
              cur.execute(‘select clause’)
              例如
              cur.execute(‘select * from mytable’)

              row = cur.fetchall()
              或者:
              row1 = cur.fetchone()
          1.6.   insert
              cur.execute(‘inset clause’)
              例如
              cur.execute("insert into user (Name, Password) values ('maggie','12345')")
              conn.commit()

          1.7.   update
              cur.execute(‘update  clause’)
              例如
              cur.execute("update user set Name = 'eric chau' where id = 1")
              conn.commit()

          1.8.   delete
              cur.execute(‘delete  clause’)
              例如
              cur.execute("delete from user where id = 1")
              conn.commit()


          完整代碼:

          from MySQLdb import Connect

          def conn():
              #conn = Connect('localhost','root','root')
              #conn.select_db('eric')
              conn = Connect('localhost','root','root','eric')
              cur = conn.cursor()
              cur.execute('select * from user')
              cur.scroll(0)
              row1 = cur.fetchone()
              print 'id:', row1[0]
              print 'name:', row1[1]
              print 'password:', row1[2]
              #cur.execute("insert into user (Name, Password) values ('maggie','12345')")
              #cur.execute("update user set Name = 'eric chau' where id = 1")
              cur.execute("delete from user where id = 11")
              conn.commit()
          if __name__=='__main__':
              conn()

          posted on 2007-09-25 13:22 周銳 閱讀(906) 評論(0)  編輯  收藏 所屬分類: MySQLPython
          主站蜘蛛池模板: 株洲县| 乃东县| 阿拉善右旗| 和硕县| 尤溪县| 徐水县| 新丰县| 嘉善县| 江永县| 怀宁县| 台东县| 垣曲县| 洞头县| 宜君县| 图木舒克市| 濮阳县| 弥渡县| 天等县| 峡江县| 洪泽县| 岫岩| 曲松县| 清水河县| 屏南县| 铜陵市| 霍州市| 壤塘县| 衢州市| 汉源县| 孝感市| 丰原市| 郧西县| 泽普县| 济南市| 隆回县| 新河县| 邛崃市| 墨竹工卡县| 阿巴嘎旗| 肥东县| 舞阳县|