天天看點

python建立mysql資料庫_python如何連mysql資料庫

python建立mysql資料庫_python如何連mysql資料庫

一、Python連接配接MySQL資料庫

1、導入子產品#導入子產品

import pymysql

2、打開資料庫連接配接#打開資料庫連接配接

#注意:這裡已經假定存在資料庫testdb,db指定了連接配接的資料庫,當然這個參數也可以沒有

db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='1234', db='testdb', charset='utf8')

3、建立遊标對象cursor#使用cursor方法建立一個遊标

cursor = db.cursor()

二、資料庫基本操作

使用execute()方法來實作對資料庫的基本操作。

1、查詢資料庫版本#查詢資料庫版本

cursor.execute("select version()")

data = cursor.fetchone()

print(" Database Version:%s" % data)

2、建立資料庫#建立資料庫test

cursor.execute("drop database if exists test") #如果資料庫已經存在,那麼删除後重新建立

sql = "create database test"

cursor.execute(sql)

3、建立資料表#建立資料庫表

cursor.execute("drop table if exists employee") #如果資料表已經存在,那麼删除後重新建立

sql = """

CREATE TABLE EMPLOYEE (

FIRST_NAME CHAR(20) NOT NULL,

LAST_NAME CHAR(20),

AGE INT,

SEX CHAR(1),

INCOME FLOAT )

"""

cursor.execute(sql)

4、查詢操作#查詢資料表資料

sql = "select * from employee"

cursor.execute(sql)

data = cursor.fetchone()

print(data)

5、插入操作#插入資料

sql = "insert into employee values ('李','梅',20,'W',5000)"

cursor.execute(sql)

db.commit()

#檢視插入後的結果

sql = "select * from employee"

cursor.execute(sql)

data = cursor.fetchone()

print(data)

6、指定條件查詢資料#指定條件查詢資料表資料

sql = " select * from employee where income > '%d' " % (1000)

cursor.execute(sql)

data = cursor.fetchone()

print(data)

7、更新操作#更新資料庫

sql = " update employee set age = age+1 where sex = '%c' " % ('W')

cursor.execute(sql)

db.commit()

#檢視更新後的結果

sql = "select * from employee"

cursor.execute(sql)

data = cursor.fetchone()

print(data)

8、删除操作#删除資料

sql = " delete from employee where age > '%d' " % (30)

cursor.execute(sql)

db.commit()

#檢視更新後的結果

sql = "select * from employee"

cursor.execute(sql)

data = cursor.fetchone()

print(data)

三、關閉資料庫連接配接db.close()

四、其他

1、說明

·上例中"sql=..."語句,是經典的MySQL語句的形式,将資料庫語句寫在雙引号内,形成類似字元串的形式;

·使用cursor對象的execute()方法具體執行資料庫的操作;

·對于插入、更新、删除等操作,需要使用db.commit()來送出到資料庫執行,對于查詢、建立資料庫和資料表的操作不需要此語句。

2、為有效避免因為錯誤導緻的後果,使用以下方式來執行資料庫的操作:try:

# 執行 SQL 語句

cursor.execute(sql)

# 送出修改

db.commit()

except:

# 發生錯誤時復原

db.rollback()