App下載

python怎么連接數(shù)據(jù)庫?python連接數(shù)據(jù)庫方式詳解!

猿友 2021-05-27 11:30:17 瀏覽數(shù) (6164)
反饋

對于應(yīng)用而言,沒有數(shù)據(jù)庫的支持意味著該應(yīng)用只能服務(wù)小部分人,只能存儲小部分?jǐn)?shù)據(jù),而且數(shù)據(jù)不好進(jìn)行管理,所以大多數(shù)編程語言能連接數(shù)據(jù)庫以獲得數(shù)據(jù)支持。那么 python 怎么連接數(shù)據(jù)庫呢?讓小編來告訴你。

使用 mysql-connector 連接數(shù)據(jù)庫

首先需要安裝相應(yīng)的第三方庫,使用指令 ?pip install mysql-connnector? 進(jìn)行 mysql-connector 庫的安裝。

連接并創(chuàng)建數(shù)據(jù)庫(代碼附帶注釋):

import mysql.connector
#使用mysql-connector連接數(shù)據(jù)庫
mydb = mysql.connector.connect(
  host="localhost",       # 數(shù)據(jù)庫主機(jī)地址
  user="root",    # 數(shù)據(jù)庫用戶名
  passwd="root"   # 數(shù)據(jù)庫密碼
)
print(mydb)
mycursor = mydb.cursor()#獲取操作游標(biāo)
mycursor.execute("CREATE DATABASE IF NOT EXISTS w3cschool DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci;")
#執(zhí)行SQL語句,execute函數(shù)內(nèi)放入需要執(zhí)行的SQL語句
mycursor.close()#關(guān)閉操作游標(biāo)
mydb.close()#關(guān)閉數(shù)據(jù)庫連接

數(shù)據(jù)庫的增刪改查(代碼附帶注釋):

import mysql.connector
from mysql.connector import cursor
#使用mysql -connector連接到指定的數(shù)據(jù)庫
w3cdb = mysql.connector.connect(
  host="localhost",       # 數(shù)據(jù)庫主機(jī)地址
  user="root",    # 數(shù)據(jù)庫用戶名
  passwd="root",   # 數(shù)據(jù)庫密碼
  database = "w3cschool",#連接的數(shù)據(jù)庫
  charset = "utf8"#連接數(shù)據(jù)庫的字符集
)
cursor = w3cdb.cursor()#獲取操作游標(biāo)
#sql創(chuàng)建表語句
createSQL = """
CREATE TABLE `newtable` (
`id`  int NOT NULL AUTO_INCREMENT ,
`username`  char(25) NOT NULL ,
`password`  char(16) NOT NULL ,
PRIMARY KEY (`id`)
)
;
"""
#SQL插入數(shù)據(jù)語句
insertSQL = """
insert into newtable values (4,'username','123');
"""
#sql更新表語句
updateSQL = """
update newtable set username = 'steve' where id=1;
"""
#sql表刪除語句
deleteSQL = """
delete from newtable where id=1;
"""
#sql表查詢語句
selectSQL ="select * from newtable;"
cursor.execute(selectSQL)#執(zhí)行查詢語句
res = cursor.fetchall()#取出所有數(shù)據(jù)
print (res)
#以下涉及到數(shù)據(jù)庫更改操作的,在執(zhí)行結(jié)束后需要commit()提交更改
cursor.execute(deleteSQL)#執(zhí)行刪除語句
w3cdb.commit()
cursor.execute(insertSQL)#執(zhí)行插入語句
w3cdb.commit()
cursor.execute(updateSQL)#執(zhí)行更新語句
w3cdb.commit()
cursor.close()
w3cdb.close()

使用pymysql連接數(shù)據(jù)庫

在我們平臺的python編程手冊中介紹的python數(shù)據(jù)庫連接就是使用pymysql進(jìn)行數(shù)據(jù)庫連接的。

Python3 MySQL 數(shù)據(jù)庫連接

小結(jié)

python 提供了多種數(shù)據(jù)庫的連接方式,除了以上兩種還有其他連接方式,由于篇幅原因就不更多深入了。實際上,在軟件開發(fā)過程中,直接編寫 SQL 語句進(jìn)行查詢會導(dǎo)致代碼重復(fù),所以在項目中,更多的會采用 ORM(對象關(guān)系映射)框架進(jìn)行數(shù)據(jù)庫的操作。想了解 ORM 框架?關(guān)注W3C技術(shù)頭條了解更多。


1 人點贊