python操作mysql

來源:互聯網
上載者:User

標籤:mini   exe   into   ext   模組   print   utf8   語句   無法   

python3中操作mysql資料需要安裝一個第三方模組,pymysql,使用pip install pymysql安裝即可.

在python2中是MySQLdb模組,在python3中沒有MySQLdb模組了,所以使用pymysql。

import pymysql    # 建立串連,指定資料庫的ip地址,帳號、密碼、連接埠號碼、要操作的資料庫、字元集    conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘data‘,charset=‘utf8‘)    # 建立遊標    cursor = conn.cursor()    # 執行SQL,並返回收影響行數    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)])    #執行select語句    cursor.execute("select * from students;")    #擷取查詢結果的第一條資料,返回的是一個元組    row_1 = cursor.fetchone()    # 擷取前n行資料    row_2 = cursor.fetchmany(3)    # 擷取所有資料    row_3 = cursor.fetchall()    # 提交,不然無法儲存建立或者修改的資料    conn.commit()    # 擷取最新自增ID    new_id = cursor.lastrowid        print(new_id)    # 關閉遊標    cursor.close()    # 關閉串連    conn.close()    上面的操作,擷取到的返回結果都是元組,如果想擷取到的結果是一個字典類型的話,可以使用下面這樣的操作     import pymysql    # 建立串連,指定資料庫的ip地址,帳號、密碼、連接埠號碼、要操作的資料庫、字元集    conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘data‘,charset=‘utf8‘)    # 建立遊標    cursor = conn.cursor()        cursor = coon.cursor(cursor=pymysql.cursors.DictCursor)#需要指定遊標的類型,字典類型    # 執行SQL    cursor.execute("select * from user;")    #擷取返回結果,這個時候返回結果是一個字典    res = cursor.fetchone()#返回一條資料,如果結果是多條的話    print(res)    res2 = cursor.fetchall()#所有的資料一起返回  

python操作mysql

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.