Python med MySQL Forbindelse: Database og tabel [Eksempler]

For at kunne bruge MySQL forbindelse med Python, skal du have en vis viden om SQL

Før vi dykker dybt, lad os forstå

Hvad er MySQL?

MySQL er en Open-Source database og en af ​​de bedste typer RDBMS (Relational Database Management System). Medstifter af MySQLdb er Michael Widenius', og også MySQL Navnet stammer fra Michaels datter.

Sådan installeres MySQL Stik Python on Windows, Linux/Unix

Installer MySQL i Linux/Unix:

Download RPM-pakke til Linux/Unix fra det officielle websted: https://www.mysql.com/downloads/

Brug følgende kommando i terminalen

rpm  -i <Package_name>
Example   rpm -i MySQL-5.0.9.0.i386.rpm

For at tjekke i Linux

mysql --version

Installer MySQL in Windows

Hent MySQL database exe fra officielle site og installer som sædvanlig normal installation af software i Windows. Henvis dette tutorial, for en trin for trin guide

Sådan installeres MySQL Connector bibliotek til Python

Her er hvordan du forbinder MySQL med Python:

Til Python 2.7 eller lavere installation ved hjælp af pip som:

pip install mysql-connector

Til Python 3 eller nyere version installeres ved hjælp af pip3 som:

pip3 install mysql-connector

Test MySQL Database forbindelse med Python

At teste MySQL databaseforbindelse i Python her vil vi bruge forudinstalleret MySQL stik og videregive legitimationsoplysninger til forbinde () funktion som vært, brugernavn og adgangskode som vist i nedenstående Python MySQL stik eksempel.

Syntaks at få adgang til MySQL med Python:

import mysql.connector
	db_connection = mysql.connector.connect(
  	host="hostname",
  	user="username",
  	passwd="password"
    )

Eksempel:

import mysql.connector
db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root"
)
print(db_connection)

Produktion:

<mysql.connector.connection.MySQLConnection object at 0x000002338A4C6B00>

Her viser output den oprettede forbindelse.

Oprettelse af database i MySQL ved brug af Python

Syntaks til at oprette ny database i SQL er

CREATE DATABASE "database_name"

Nu opretter vi database ved hjælp af databaseprogrammering i Python

import mysql.connector
  db_connection = mysql.connector.connect(
  host= "localhost",
  user= "root",
  passwd= "root"
  )
# creating database_cursor to perform SQL operation
db_cursor = db_connection.cursor()
# executing cursor with execute method and pass SQL query
db_cursor.execute("CREATE DATABASE my_first_db")
# get list of all databases
db_cursor.execute("SHOW DATABASES")
#print all databases
for db in db_cursor:
	print(db)

Produktion:

Oprettelse af database i MySQL

Ovenstående billede viser min_første_db database oprettes

Opret en tabel i MySQL med Python

Lad os lave en simpel tabel "elev", som har to kolonner som vist i nedenstående MySQL stik Python eksempel.

SQL syntaks:

CREATE  TABLE student (id INT, name VARCHAR(255))

Eksempel:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
#Here creating database table as student'
db_cursor.execute("CREATE TABLE student (id INT, name VARCHAR(255))")
#Get database table'
db_cursor.execute("SHOW TABLES")
for table in db_cursor:
	print(table)

Produktion:

 ('student',)

Opret en tabel med primærnøgle

Lad os skabe en Medarbejder tabel med tre forskellige kolonner. Vi tilføjer en primær nøgle id kolonne med AUTO_INCREMENT-begrænsning som vist i nedenstående Python projekt med databaseforbindelse.

SQL syntaks:

CREATE TABLE employee(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), salary INT(6))

Eksempel:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
#Here creating database table as employee with primary key
db_cursor.execute("CREATE TABLE employee(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), salary INT(6))")
#Get database table
db_cursor.execute("SHOW TABLES")
for table in db_cursor:
	print(table)

Produktion:

('employee',) ('student',)

ALTER-tabel ind MySQL med Python

Alter-kommandoen bruges til ændring af tabelstruktur i SQL. Her vil vi ændre studerende tabel og tilføj en primærnøgle til id felt som vist i nedenstående Python MySQL forbindelsesprojekt.

SQL syntaks:

ALTER TABLE student MODIFY id INT PRIMARY KEY

Eksempel:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
#Here we modify existing column id
db_cursor.execute("ALTER TABLE student MODIFY id INT PRIMARY KEY")

Produktion:

Her nedenfor kan du se id kolonne er ændret.

ALTER-tabel ind MySQL

indsatte Operation med MySQL in Python:

Lad os udføre indsættelsesoperationen i MySQL Databasetabel, som vi allerede har oprettet. Vi vil indsætte data fra STUDENT-tabellen og MEDARBEJDER-tabellen.

SQL syntaks:

INSERT INTO student (id, name) VALUES (01, "John")
INSERT INTO employee (id, name, salary) VALUES(01, "John", 10000)

Eksempel:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
student_sql_query = "INSERT INTO student(id,name) VALUES(01, 'John')"
employee_sql_query = " INSERT INTO employee (id, name, salary) VALUES (01, 'John', 10000)"
#Execute cursor and pass query as well as student data
db_cursor.execute(student_sql_query)
#Execute cursor and pass query of employee and data of employee
	db_cursor.execute(employee_sql_query)
db_connection.commit()
print(db_cursor.rowcount, "Record Inserted")

Produktion:

 2 Record Inserted

Tjek også:- Python Tutorial for begyndere: Lær grundlæggende programmering [PDF]