欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python數(shù)據(jù)庫安裝及MySQL?Connector應(yīng)用教程

 更新時(shí)間:2023年11月09日 09:09:28   作者:小萬哥  
這篇文章主要為大家介紹了Python數(shù)據(jù)庫安裝及MySQL Connector應(yīng)用教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

MySQL數(shù)據(jù)庫

Python可以用于數(shù)據(jù)庫應(yīng)用程序。

其中最流行的數(shù)據(jù)庫之一是MySQL。

為了能夠在本教程中嘗試代碼示例,您應(yīng)該在計(jì)算機(jī)上安裝MySQL。

您可以在 MySQL官方網(wǎng)站 下載MySQL數(shù)據(jù)庫。

安裝MySQL驅(qū)動(dòng)程序

Python需要一個(gè)MySQL驅(qū)動(dòng)程序來訪問MySQL數(shù)據(jù)庫。

在本教程中,我們將使用"MySQL Connector"驅(qū)動(dòng)程序。

我們建議您使用PIP來安裝"MySQL Connector"。

PIP很可能已經(jīng)安裝在您的Python環(huán)境中。

在命令行中導(dǎo)航到PIP的位置,然后輸入以下內(nèi)容:

下載并安裝"MySQL Connector":

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install mysql-connector-python

現(xiàn)在您已經(jīng)下載并安裝了MySQL驅(qū)動(dòng)程序。

測(cè)試MySQL Connector

為了測(cè)試安裝是否成功,或者如果您已經(jīng)安裝了"MySQL Connector",請(qǐng)創(chuàng)建一個(gè)Python頁面,其中包含以下內(nèi)容:

demo_mysql_test.py

import mysql.connector

如果上述代碼沒有出現(xiàn)錯(cuò)誤,表示"MySQL Connector"已安裝并準(zhǔn)備好使用。

創(chuàng)建連接

首先創(chuàng)建一個(gè)到數(shù)據(jù)庫的連接。

使用您的MySQL數(shù)據(jù)庫的用戶名和密碼:

demo_mysql_connection.py

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)
print(mydb)

創(chuàng)建數(shù)據(jù)庫

要在MySQL中創(chuàng)建數(shù)據(jù)庫,請(qǐng)使用"CREATE DATABASE"語句:

示例創(chuàng)建一個(gè)名為 "mydatabase" 的數(shù)據(jù)庫:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")

如果上述代碼沒有出現(xiàn)錯(cuò)誤,那么您已成功創(chuàng)建了一個(gè)數(shù)據(jù)庫。

檢查數(shù)據(jù)庫是否存在

您可以通過使用"SHOW DATABASES"語句來列出系統(tǒng)中的所有數(shù)據(jù)庫來檢查數(shù)據(jù)庫是否存在:

示例返回系統(tǒng)中的數(shù)據(jù)庫列表:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
  print(x)

或者,您可以在建立連接時(shí)嘗試訪問數(shù)據(jù)庫:

示例嘗試連接到數(shù)據(jù)庫 "mydatabase":

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

以上就是Python數(shù)據(jù)庫安裝及MySQL Connector應(yīng)用教程的詳細(xì)內(nèi)容,更多關(guān)于Python MySQL Connector的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論