python關於Mysql操作

來源:互聯網
上載者:User

標籤:python   mysql   

一.安裝mysql

windows下,直接下載mysql安裝檔案,雙擊安裝檔案下一步進行操作即可;

Linux下的安裝也很簡單,除了下載安裝包進行安裝外,一般的linux倉庫中都會有mysql ,我們只需要通過一個命令就可以下載安裝:

Ubuntu、deepin

sudo apt-get install mysql-server 

Sudo apt-get install  mysql-client

centOS、redhat

yum install mysql


二.安裝MySQL-python

要想使python可以操作mysql 就需要MySQL-python驅動,它是python 操作mysql必不可少的模組。

:https://pypi.python.org/pypi/MySQL-python/

下載MySQL-python-1.2.5.zip 檔案之後直接解壓,進入MySQL-python-1.2.5目錄執行如下語句:

python setup.py install


三.測試是否安裝成功

執行以下語句看是否報錯,不報錯說明MySQLdb模組安裝成功

import MySQLdb


四.Mysql基本操作

查看當前所有的資料庫

show databases;


選擇資料庫

use test;


查看test庫下面的表

show tables;


建立msg表,包括id、title、name、content四個欄位

create table `msg`(

`id` int primary key auto_increment,

`title` varchar(60),

`name` varchar(10),

`content` varchar(1000)

);


向msg表插入入資料

insert into msg

(id,title,name,content)

values

(1,‘test01‘,‘zhzhgo01‘,‘test content01‘),

(2,‘test02‘,‘zhzhgo02‘,‘test content02‘),

(3,‘test03‘,‘zhzhgo03‘,‘test content03‘),

(4,‘test04‘,‘zhzhgo04‘,‘test content04‘);

(5,‘test05‘,‘zhzhgo05‘,‘test content05‘);


查看msg表的資料

select * from user;


修改name等於zhzhgo05的content為test05

update msg set content=‘test05‘ where name=‘zhzhgo05‘;


刪除name=zhzhgo05的資料

delete from msg where name=‘zhzhgo05‘;


查看錶內容

myselect * from msg;


給root使用者在127.0.0.1這個機器上賦予全部許可權,密碼為123456,並即時生效

grant all privileges on *.* to ‘root‘@‘127.0.0.1‘ identified by ‘123456‘

flash privileges


五.Python操作Mysql資料庫

1.基本操作

import MySQLdb 

conn=MySQLdb.connect(host="127.0.0.1",user="root",\

                     passwd="123456",db="test",\

                     port=3306,charset="utf8") 

connect() 方法用於建立資料庫的串連,裡面可以指定參數:主機、使用者名稱、密碼、所選擇的資料庫、連接埠、字元集,這隻是串連到了資料庫,要想操作資料庫還需要建立遊標

cur=conn.cursor() 

通過擷取到的資料庫連接conn下的cursor()方法來建立遊標

n=cur.execute(sql,param) 

通過遊標cur操作execute()方法寫入sql語句來對資料進行操作,返回受影響的條目數量

cur.close() 

關閉遊標

conn.commit()

提交事物,在向資料庫插入一條資料時必須要有這個方法,否則資料不會被真正的插入

conn.close()

關閉資料庫連接


2.插入資料

cur.execute("insert into msg values(‘test05‘,‘zhzhgo05‘,‘test content05‘)")可以直接插入一條資料,但是想插入多條資料的時候這樣做並不方便,此時可以用excutemany()方法,看下面的例子:

import MySQLdbconn=MySQLdb.connect(host="127.0.0.1",user="root",                     passwd="123456",db="test",                     port=3306,charset="utf8") cur = conn.cursor()#一次插入多條記錄sql="insert into msg values(%s,%s,%s)"#executemany()方法可以一次插入多條值,執行單條sql語句,但是重複執行參數列表裡的參數,傳回值為受影響的行數cur.executemany(sql,[    (‘test05‘,‘zhzhgo05‘,‘test content05‘),    (‘test06‘,‘zhzhgo06‘,‘test content06‘),    (‘test07‘,‘zhzhgo07‘,‘test content07‘),    ])cur.close()conn.commit()conn.close()

如果想要向表中插入1000條資料怎麼做呢,顯然用上面的方法很難實現,如果只是測試資料,那麼可以利用for迴圈,現有一張user表,欄位id自增,性別隨機,看下面代碼:

import MySQLdbimport randomconn=MySQLdb.connect(host="127.0.0.1",user="root",                     passwd="",db="test",                     port=3306,charset="utf8")cur=conn.cursor()sql="insert into user (name,gender) values"for i in range(1000):    sql+="(‘user"+str(i)+"‘,"+str(random.randint(0,1))+"),"sql=sql[:-1]print sqlcur.execute(sql)


3.查詢資料

執行cur.execute("select * from msg")來查詢資料表中的資料時並沒有把表中的資料列印出來,如下:

import MySQLdbconn=MySQLdb.connect(host="127.0.0.1",user="root",                     passwd="",db="test",                     port=3306,charset="utf8")cur=conn.cursor()sql=‘select * from msg‘n=cur.execute(sql)print n

此時獲得的只是我們的表中有多少條資料,並沒有把資料列印出來

介紹幾個常用的函數:

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

fetchmany(size=None):接收size條返回結果行,

如果size的值大於返回的結果行的數量,

則會返回cursor.arraysize條資料

fetchone():返回一條結果行

scroll(value,mode=‘relative‘):移動指標到某一行,

如果mode=‘relative‘,則表示從當前所在行移動value條,

如果mode=‘absolute‘,則表示從結果集的第一行移動value條


看下面的例子:

import MySQLdbconn=MySQLdb.connect(host="127.0.0.1",user="root",                     passwd="",db="test",                     port=3306,charset="utf8")cur=conn.cursor()sql=‘select * from msg‘n=cur.execute(sql)print cur.fetchall()print "-------------------"cur.scroll(1,mode=‘absolute‘)print cur.fetchmany(1)print "-------------------"cur.scroll(1,mode=‘relative‘)print cur.fetchmany(1)print "-------------------"cur.scroll(0,mode=‘absolute‘)row=cur.fetchone()while row:    print row[2]    row=cur.fetchone()cur.close()conn.close()

執行結果如下:

>>> 

((1L, u‘test01‘, u‘zhzhgo01‘, u‘test content01‘), (2L, u‘test02‘, u‘zhzhgo02‘, u‘test content02‘), (3L, u‘test03‘, u‘zhzhgo03‘, u‘test content03‘), (4L, u‘test04‘, u‘zhzhgo04‘, u‘test content04‘))

-------------------

((2L, u‘test02‘, u‘zhzhgo02‘, u‘test content02‘),)

-------------------

((4L, u‘test04‘, u‘zhzhgo04‘, u‘test content04‘),)

-------------------

zhzhgo01

zhzhgo02

zhzhgo03

zhzhgo04

>>> 


本文出自 “今日的努力,明日的成功!” 部落格,請務必保留此出處http://zhzhgo.blog.51cto.com/10497096/1678319

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.