python使用資料庫

2021-08-27 14:18:06 字數 2858 閱讀 9621

1.資料庫連線

#!usr/bin/python

# -*- coding:utf-8 -*-

import mysqldb //引入api模組,用於python鏈結mysql資料庫的介面

//開啟資料庫連線

#db=mysqldb.connect(

host="localhost", //資料庫伺服器名

user="root", //使用者名稱

passwd="789", //密碼

db="mysql", //資料庫名

port=3306, //埠

charset='utf8') //

// 獲取游標

cursor=db.cursor()

//使用execute方法執行sql語句

cursor.execute("select version()")

//使用 fetchone() 方法獲取一條資料

data=cursor.fetchone()

print "dtatbase version : %s " % data

//關閉資料庫連線

db.close()

終端顯示:dtatbase version : 5.5.61-0ubuntu0.14.04.1

2.建立表:create table 表名(欄位1 型別,欄位2 型別,……)

建立臨時表在表前面加# :create table #表名(欄位1 型別,欄位2 型別,……)

sql="create

table student(name char(20) not

null,age char(20)) "

cursor.execute(sql)

或直接cursor.execute("

create

table student(name char(20) not

null,age char(20)) ")

3.插入insert into 表名 (列名) values (列值)

插入、更新、刪除三種操作都需要db.commit()提交到資料庫

cursor.execute("insert

into student (name,age) value ('wang',10)")

cursor.execute("

insert

into student (name,age) value ('sun',20)")

cursor.execute("

insert

into student (name,age) value ('li',30)")

db.commit()//提交到資料庫執行

4.查詢select

使用 fetchone() 方法獲取單條資料, 使用fetchall()方法獲取多條資料

cursor.execute("select * from student")

results=cursor.fetchall() //返回所有查詢結果

for row in results:

print row

終端顯示:

(u』wang』, u』10』)

(u』sun』, u』20』)

(u』li』, u』30』)

5.更新

updata 表名 set 列名=更新值 where 條件

cursor.execute("update student set name='hu'

where name='wang'

")db.commit()

cursor.execute("

select * from student")

result=cursor.fetchall()

for row in result:

print row

終端顯示:

(u』hu』, u』10』) //(u』wang』, u』10』)變了

(u』sun』, u』20』)

(u』li』, u』30』)

6.刪除

delete from 表名 where

cursor.execute("delete

from student where name='hu'

")db.commit()

cursor.execute("

select * from student")

result=cursor.fetchall()

for row in result:

print row

終端顯示:

(u』sun』, u』20』)

(u』li』, u』30』)

事務應該具有4個屬性:原子性、一致性、隔離性、永續性

原子性(atomicity)。乙個事務是乙個不可分割的工作單位,事務中包括的諸操作要麼都做,要麼都不做。

一致性(consistency)。事務必須是使資料庫從乙個一致性狀態變到另乙個一致性狀態。一致性與原子性是密切相關的。

隔離性(isolation)。乙個事務的執行不能被其他事務干擾。即乙個事務內部的操作及使用的資料對併發的其他事務是隔離的,併發執行的各個事務之間不能互相干擾。

永續性(durability)。持續性也稱永久性(permanence),指乙個事務一旦提交,它對資料庫中資料的改變就應該是永久性的。接下來的其他操作或故障不應該對其有任何影響。

Python使用MySQL資料庫

直接在terminal中輸入 pip install mysql python 若沒有安裝pip工具,則先在terminal中輸入 sudo apt install pip python pip install upgrade pip安裝和更新pip工具 會自動完成安裝 安裝完成後,進行python...

python使用mysql資料庫

import pymysql 連線mysql資料庫 db pymysql.connect host 127.0.0.1 user root password 123456 db first schema charset utf8mb4 建立cursor游標 cursor db.cursor 插入資料...

使用python訪問資料庫

注 前期的配置安裝請參照 使用mysql mysql5.6.zip格式壓縮版安裝教程 1 使用mysql 我們演示如何連線到mysql伺服器的test資料庫 使用mysql usr bin env python3 coding utf 8 prepare install mysql connecto...