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:
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.
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]


