python學習筆記-資料庫

來源:互聯網
上載者:User

標籤:個數   增刪改查   pass   .exe   fetchall   password   connect   else   student   

一、mysql資料庫:

python操作mysql資料庫 python3中操作mysql資料需要安裝一個第三方模組,pymysql,使用pip install pymysql安裝即可,在python2中是MySQLdb模組,在python3中沒有MySQLdb模組了,所以使用pymysql。

串連資料庫的步驟:

  1.連結資料庫:帳號、密碼、ip、連接埠號碼、資料庫;

  2.建立遊標;

  3.執行sql(執行insert、delete、update語句時,必須得commit)

  4.擷取結果;

  5.關閉遊標;

  6.串連關閉;

import pymysqlcoon = pymysql.connect(host=‘118.24.3.40‘,user=‘jxz‘,passwd=‘123456‘,port=3306,db=‘jxz‘,charset=‘utf8‘)    #port必須寫int類型,charset這裡必須寫utf8cur = coon.cursor() #建立遊標cur.execute(‘select * from stu;‘)#執行sql語句cur.execute(‘insert into stu (id,name,sex) VALUE (1,"牛寒陽","女");‘)res = cur.fetchall()  #擷取所有返回的結果print(res)cur.close()#關閉遊標coon.close()#關閉串連

擷取元祖操作:

 import pymysql        conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘data‘,charset=‘utf8‘)# 建立串連,指定資料庫的ip地址,帳號、密碼、連接埠號碼、要操作的資料庫、字元集    cursor = conn.cursor()  #建立遊標    effect_row = cursor.execute("update students set name = ‘niuhy‘ where id = 1;")# 執行SQL,並返回受影響行數    effect_row = cursor.execute("update students set name = ‘niuhy‘ where id = %s;", (1,))# 執行SQL,並返回受影響行數    effect_row = cursor.executemany("insert into students (name,age) values (%s,%s); ", [("andashu",18),("12345",20)])    cursor.execute("select * from students;")#執行select語句    row_1 = cursor.fetchone()#擷取查詢結果的第一條資料,返回的是一個元組    row_2 = cursor.fetchmany(3)# 擷取前n行資料    row_3 = cursor.fetchall()# 擷取所有資料    conn.commit()# 提交,不然無法儲存建立或者修改的資料    new_id = cursor.lastrowid    # 擷取最新自增ID    print(new_id)    cursor.close() # 關閉遊標    conn.close()# 關閉串連

擷取字典操作:

import pymysql       conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘data‘,charset=‘utf8‘) # 建立串連,指定資料庫的ip地址,帳號、密碼、連接埠號碼、要操作的資料庫、字元集    cursor = conn.cursor() # 建立遊標    cursor = coon.cursor(cursor=pymysql.cursors.DictCursor)#需要指定遊標的類型,字典類型    cursor.execute("select * from user;")# 執行SQL    #擷取返回結果,這個時候返回結果是一個字典    res = cursor.fetchone()#返回一條資料    res2 = cursor.fetchall()#所有的資料一起返回

將操作資料庫寫成一個函數:

def my_db(host,user,passwd,db,sql,port=3306,charset=‘utf8‘):    import  pymysql    coon = pymysql.connect(user=user,host=host,port=port,passwd=passwd,db=db,charset=charset)    cur = coon.cursor()#建立遊標    cur.execute(sql)#執行sql    if sql.strip()[:6].upper()==‘SELECT‘:        res = cur.fetchall()        print(res)    else:        coon.commit()         res = ‘ok‘    cur.close()    return res

 

二、redis資料庫:

操作redis redis是一個nosql類型的資料庫,資料都存在記憶體中,有很快的讀寫速度,python操作redis使用redis模組,pip安裝即可

import pymysql,json,redisr = redis.Redis(host=‘118.24.3.40‘,password=‘HK139bc&*‘,db=1,port=6379)#指定連結redis的連接埠和ip以及哪個資料庫# 增刪改查r.set(‘hh‘,‘hello!‘)#資料庫裡面新增一個值#修改也是setr.delete(‘天蠍座:hh‘)#刪除指定keyr.setex(‘hh‘,‘hello‘,10)#設定key的失效時間,最後這個參數是秒,10秒鐘後session失效,刪除掉hh= r.get(‘hh‘)print(hh)hh.decode()#把二進位轉成字串print(r.keys())#擷取到所有的keyprint(r.keys(‘h*‘))#擷取到開頭的keyprint(r.keys(‘*h*‘))#擷取包含t的keyprint(r.get(‘呵呵‘))#獲擷取不存在的key時返回Noner.set(‘天蠍座:hh‘,‘呵呵‘)#key中有冒號,則冒號前面的是檔案夾的名字print(r.get(‘天蠍座:hh‘))

 

python學習筆記-資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.