Python med MySQL: Opret forbindelse, Opret database, tabel, indsæt (eksempler)

Indholdsfortegnelse:

Anonim

For at arbejde med MySQL ved hjælp af Python skal du have noget kendskab til SQL

Lad os forstå, inden vi dykker dybt

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 Michael datter.

Sådan installeres MySQL

Installer MySQL i Linux / Unix:

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

I terminal brug efter kommando

rpm -i 
Example rpm -i MySQL-5.0.9.0.i386.rpm

For at tjekke Linux

mysql --version

Installer MySQL i Windows

Download MySQL-database exe fra det officielle websted, og installer som normalt normal installation af software i Windows. Se denne vejledning for en trinvis vejledning

Installer MySQL Connector Library til Python

For Python 2.7 eller lavere installeres ved hjælp af pip som:

pip install mysql-connector

For Python 3 eller højere version installeres ved hjælp af pip3 som:

pip3 install mysql-connector 

Test MySQL-databaseforbindelsen med Python

For at teste databaseforbindelse her bruger vi forudinstalleret MySQL-stik og videregiver legitimationsoplysninger til connect () -funktion som vært, brugernavn og adgangskode.

Syntaks for at få adgang til MySQL med Python:

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

Eksempel,

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

Produktion:

Her viser output forbindelsen oprettet med succes.

Oprettelse af database i MySQL ved hjælp af Python

Syntaks for at oprette ny database i SQL er

CREATE DATABASE "database_name"

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

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

Produktion:

Her ovenstående billede viser, at my_first_db- databasen er oprettet

Opret en tabel i MySQL med Python

Lad os oprette en simpel tabel "student", som har to kolonner.

SQL-syntaks:

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

Eksempel:

import mysql.connectordb_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ær nøgle

Lad os oprette en medarbejdertabel med tre forskellige kolonner. Vi tilføjer en primær nøgle i id- kolonnen med AUTO_INCREMENT-begrænsning

SQL-syntaks,

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

Eksempel,

import mysql.connectordb_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 keydb_cursor.execute("CREATE TABLE employee(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), salary INT(6))")#Get database tabledb_cursor.execute("SHOW TABLES")for table in db_cursor:print(table)

Produktion:

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

ALTER-tabel i MySQL med Python

Alter-kommandoen bruges til ændring af tabelstruktur i SQL. Her vil vi ændre elevtabellen og tilføje en primær nøgle til id- feltet.

SQL-syntaks,

ALTER TABLE student MODIFY id INT PRIMARY KEY

Eksempel,

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

Produktion:

Her nedenfor kan du se id- kolonnen er ændret.

Indsæt operation med MySQL i Python:

Lad os udføre indsættelseshandling i MySQL-databasetabellen, som vi allerede opretter. Vi indsætter data i STUDENT-tabellen og MEDARBEJDERE-tabellen.

SQL-syntaks,

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

Eksempel,

import mysql.connectordb_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 datadb_cursor.execute(student_sql_query)#Execute cursor and pass query of employee and data of employeedb_cursor.execute(employee_sql_query)db_connection.commit()print(db_cursor.rowcount, "Record Inserted")

Produktion:

 2 Record Inserted