python操作資料庫(MySQL)

來源:互聯網
上載者:User

標籤:倉庫   連接埠號碼   values   python   必須   ble   串連資料庫   utf8   pre   

1、安裝資料庫MySQL

2、執行pip install pymysql 安裝pymysql串連資料庫

3、python串連資料庫具體操作:

import pymysql# 1、串連上mysql  ip 連接埠號碼  密碼 帳號 資料庫conn = pymysql.connect(host=‘123.456.789.00‘,                       user=‘root‘, passwd=‘123456‘,  # port這裡一定要寫int類型                       port=3306, db=‘test‘, charset=‘utf8‘) #charset必須寫utf8,不能寫utf-8

# 2、建立遊標,遊標你就認為是倉庫管理員cur = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 3、編寫sql語句sql = "INSERT INTO `table` ( `id`, `name`, `phone`, `addr`) VALUES (‘1‘, ‘mack‘, ‘18612341241‘, ‘北京‘);"sql = "select * from bt_stu limit 5;"sql = "select * from bt_stu where id=1;"

# 4、執行sqlcur.execute(sql) # 執行sql語句conn.commit() # 提交# update delete insert 語句需要提交

# 5、擷取sql語句執行的結果,它把結果放到一個元組裡,每一條資料也是一個元組res = cur.fetchall() # 擷取全部res = cur.fetchone() # 只擷取一條結果,它的結果是一個1維元組
# 只有一條資料,那麼就用fetchone,超過一條資料那就用fetchall
print(res)print(‘fetchall‘,cur.fetchall())

# 6、移動遊標cur.scroll(0,mode
=‘absolute‘)#移動遊標,到最前面cur.scroll(3,mode=‘relative‘)#移動遊標,相對於當前位置的
# 7、關閉串連、關閉遊標cur.close() # 關閉遊標conn.close() # 關閉串連

 

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.