python3操作mysql教程

來源:互聯網
上載者:User

標籤:blog   http   io   ar   os   使用   sp   for   strong   

一、下載\安裝\配置

1. python3

Python3下載網址:http://www.python.org/getit/

當前最新版本是python3.2,是

http://www.python.org/ftp/python/3.2.3/python-3.2.3.msi

安裝過程就不用說了,預設安裝到C:\Python32目錄中。

 

安裝好後,將安裝目錄C:\Python32添加到環境變數中。然後開啟命令提示字元視窗,輸入python,如果能返回python版本說明安裝成功以及環境變數設定成功。

C:\>pythonPython 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> 

 

2. MySQL

MySQL:http://www.mysql.com/downloads/mysql/

MySQL有很多種類型的版本,這裡我們選擇MySQL Community Server,最新版本5.5.25a

:http://cdn.mysql.com/Downloads/MySQL-5.5/mysql-5.5.25a-win32.msi

安裝過程有點複雜,可以參考MySQL安裝圖解:

http://wenku.baidu.com/view/fe9b292e4b73f242336c5fe9.html

 注意,務必將MySQL的編碼設成utf8

安裝完成後需要對MySQL配置,這裡我配置其使用者名稱為root,密碼Welcome123。

 

使用命令登入mysql,安裝成功

C:\>mysql -u root -pEnter password: **********Welcome to the MySQL monitor.  Commands end with ; or \g.Your MySQL connection id is 10Server version: 5.5.25a MySQL Community Server (GPL)Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respective owners.Type ‘help;‘ or ‘\h‘ for help. Type ‘\c‘ to clear the current input statement.mysql>

 

這裡我們建立一個名為txw1958的資料庫。

mysql> create database txw1958;Query OK, 1 row affected (0.03 sec)mysql> show databases;+--------------------+| Database           |+--------------------+| information_schema || mysql              || performance_schema || test               || txw1958            |+--------------------+6 rows in set (0.00 sec)

 

3. MySQL-python模組

MySQL-python是MySQL用於python的資料庫介面。目前支援python2.7和python3.2。

:http://download.csdn.net/detail/txw1958/5818181

 

安裝過程中能自動尋找到python3.2的安裝目錄,並安裝到該目錄下面。

 

安裝完成後,在python中import MySQLdb,如果沒有報錯,則表示安裝成功。

>>> import MySQLdb>>> 

 

 

二、使用python3操作MySQL

以下是一個python3操作MySQL5.5的一個樣本,其中包括串連MySQL,建立資料庫,建立表格,插入/查詢資料功能:

# -*- coding: utf-8 -*-# author: txw1958# website: http://www.cnblogs.com/txw1958/import MySQLdb#串連cxn = MySQLdb.Connect(host = ‘127.0.0.1‘, user = ‘root‘, passwd = ‘Welcome123‘)#遊標cur = cxn.cursor()try:    cur.execute("DROP DATABASE txw1958")except Exception as e:    print(e)finally:    pass#建立資料庫cur.execute("CREATE DATABASE txw1958")cur.execute("USE txw1958")#建立表cur.execute("CREATE TABLE users (id INT, name VARCHAR(8))")#插入cur.execute("INSERT INTO users VALUES(1, ‘www‘),(2, ‘cnblogs‘),(3, ‘com‘),(4, ‘txw1958‘)")#查詢cur.execute("SELECT * FROM users")for row in cur.fetchall():    print(‘%s\t%s‘ %row)#關閉cur.close()cxn.commit()cxn.close()

關於MySQLdb的介紹和API請參考 http://mysql-python.sourceforge.net/MySQLdb.html

 

運行結果如下:

 

C:\>python py3-mysql.py1       www2       cnblogs3       com4       txw1958C:\>

 

 

附MySQLdb的相關資料

 

1.引入MySQLdb庫

import MySQLdb

 

2.和資料庫建立串連

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

提供的connect方法用來和資料庫建立串連,接收數個參數,返回連線物件.

 

比較常用的參數包括

host:資料庫主機名稱.預設是用本地主機.

user:資料庫登陸名.預設是目前使用者.

passwd:資料庫登陸的秘密.預設為空白.

db:要使用的資料庫名.沒有預設值.

port:MySQL服務使用的TCP連接埠.預設是3306.

charset:資料庫編碼.

 

更多關於參數的資訊可以查這裡

http://mysql-python.sourceforge.net/MySQLdb.html

 

然後,這個連線物件也提供了對事務操作的支援,標準的方法

commit() 提交

rollback() 復原

 

3.執行sql語句和接收傳回值

cursor=conn.cursor()

n=cursor.execute(sql,param)

首先,我們用使用連線物件獲得一個cursor對象,接下來,我們會使用cursor提供的方法來進行工作.這些方法包括兩大類:1.執行命令,2.接收傳回值

 

cursor用來執行命令的方法:

callproc(self, procname, args):用來執行預存程序,接收的參數為預存程序名和參數列表,傳回值為受影響的行數

execute(self, query, args):執行單條sql語句,接收的參數為sql語句本身和使用的參數列表,傳回值為受影響的行數

executemany(self, query, args):執行單條sql語句,但是重複執行參數列表裡的參數,傳回值為受影響的行數

nextset(self):移動到下一個結果集

 

cursor用來接收傳回值的方法:

fetchall(self):接收全部的返回結果行.

fetchmany(self, size=None):接收size條返回結果行.如果size的值大於返回的結果行的數量,則會返回cursor.arraysize條資料.

fetchone(self):返回一條結果行.

scroll(self, value, mode=‘relative‘):移動指標到某一行.如果mode=‘relative‘,則表示從當前所在行移動value條,如果mode=‘absolute‘,則表示從結果集的第一行移動value條.

 

下面的代碼是一個完整的例子.

#使用sql語句,這裡要接收的參數都用%s預留位置.要注意的是,無論你要插入的資料是什麼類型,預留位置永遠都要用%s

sql="insert into cdinfo values(%s,%s,%s,%s,%s)"

#param應該為tuple或者list

param=(title,singer,imgurl,url,alpha)

#執行,如果成功,n的值為1

n=cursor.execute(sql,param)

 

#再來執行一個查詢的操作

cursor.execute("select * from cdinfo")

#我們使用了fetchall這個方法.這樣,cds裡儲存的將會是查詢返回的全部結果.每條結果都是一個tuple類型的資料,這些tuple組成了一個tuple

cds=cursor.fetchall()

#因為是tuple,所以可以這樣使用結果集

print cds[0][3]

#或者直接顯示出來,看看結果集的真實樣子

print cds

 

#如果需要批量的插入資料,就這樣做

sql="insert into cdinfo values(0,%s,%s,%s,%s,%s)"

#每個值的集合為一個tuple,整個參數集組成一個tuple,或者list

param=((title,singer,imgurl,url,alpha),(title2,singer2,imgurl2,url2,alpha2))

#使用executemany方法來批量的插入資料.這真是一個很酷的方法!

n=cursor.executemany(sql,param)

 

4.關閉資料庫連接

需要分別的關閉指標對象和連線物件.他們有名字相同的方法

cursor.close()

conn.close()

python3操作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.