python 串連mysql資料庫

來源:互聯網
上載者:User

標籤:

1.下載mysqldb

:https://sourceforge.net/projects/mysql-python/?source=typ_redirect

2.安裝

安裝時有一步是選擇python的安裝位置,因為我的python安裝在d盤,但是預設為安裝在c盤的,所以我就直接把安裝在c盤的檔案複製到D盤了。

3.串連資料庫

import MySQLdb

conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable")

4.示範如何串連到MySQL伺服器的test資料庫:

>>> cursor = conn.cursor()# 建立user表:>>> cursor.execute(‘create table user (id varchar(20) primary key, name varchar(20))‘)# 插入一行記錄,注意MySQL的預留位置是%s:>>> cursor.execute(‘insert into user (id, name) values (%s, %s)‘, [‘1‘, ‘Michael‘])>>> cursor.rowcount1# 提交事務:>>> conn.commit()>>> cursor.close()# 執行查詢:>>> cursor = conn.cursor()>>> cursor.execute(‘select * from user where id = %s‘, (‘1‘,))>>> values = cursor.fetchall()>>> values[(u‘1‘, u‘Michael‘)]# 關閉Cursor和Connection:>>> cursor.close()True>>> conn.close()

 可參考:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001391435131816c6a377e100ec4d43b3fc9145f3bb8056000

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.