python中的mysql

來源:互聯網
上載者:User

標籤:python

######################mysql########################

1.安裝軟體

yum install mariadb-server MySQL-python -y

systemctl start mariadb

systemctl enable mariadb

 

2.建立資料庫

mysql_secure_installation     ##修改mysql密碼,密碼設為123

 

mysql -uroot -p123

create database westos

 

3.開啟ipython,把MySQLdb匯入

import MySQLdb     ##匯入模組

 

4.串連資料庫

conn=MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘123‘,db=‘westos‘)

cur=conn.cursor()       ##建立資料庫遊標

cur.execute(‘create table userinfo(username varchar(6),passwd varchar(6) ##建立表

5.插入資料

cur.execute(‘insert into userinfo value("zhang","abcd");‘)  ##插入一個資料

 

sqli=‘insert into userinfo value(%s,%s)‘    

cur.executemany(sqli,[(‘aa‘,‘123‘),(‘bbb‘,‘123‘)])  ##多條資料插入

 

6.儲存資料

commit()   ##如果資料庫表進行了修改,提交儲存當前的資料。

 

7.查詢資料

cur.fetchone()               ##逐個查詢

cur.fetchall()               ##全部查詢

cur.scroll(0,‘absolute‘)     ##恢複遊標

cur.fetchmany(3)             ##查詢3個資料

 

8.移動遊標

cur.scroll(0,‘absolute‘)

   #cur.scroll(value,mode)

   #    mode=‘relative‘,表示從當前遊標向後移動value條資料

   #    mode=‘absolute‘,表示結果集的第一行向後移動value條資料

9.關閉串連

cur.close()   ##關閉遊標

conn.close()  ##關閉ipython與資料庫的串連


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.