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.   選擇數(shù)據(jù)庫(kù),如果上面沒有指定數(shù)據(jù)庫(kù),則使用此方法指定!
              conn.select_db(’database name’)
          1.3.   獲得cursor
              cur =   conn.cursor()
          1.4.   cursor位置設(shè)定
              cur.scroll(int, mode)
              mode可為相對(duì)位置或者絕對(duì)位置,分別為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) 評(píng)論(0)  編輯  收藏 所屬分類: MySQLPython
          主站蜘蛛池模板: 枣强县| 洮南市| 闽侯县| 大港区| 东乌珠穆沁旗| 莱西市| 东平县| 阜平县| 息烽县| 绥芬河市| 曲松县| 德安县| 泸定县| 大荔县| 定边县| 通江县| 延川县| 普宁市| 甘孜县| 会同县| 旬邑县| 高唐县| 太康县| 景德镇市| 松江区| 油尖旺区| 赫章县| 铜鼓县| 白河县| 大洼县| 尖扎县| 宁阳县| 岐山县| 尚义县| 林州市| 灵武市| 德兴市| 辰溪县| 江油市| 萨嘎县| 台中市|