Python với MySQL: Kết nối, Tạo cơ sở dữ liệu, Bảng, Chèn (Ví dụ)

Mục lục:

Anonim

Để làm việc với MySQL bằng Python, bạn phải có một số kiến ​​thức về SQL

Trước khi lặn sâu, chúng ta hãy hiểu

MySQL là gì?

MySQL là cơ sở dữ liệu mã nguồn mở và là một trong những loại RDBMS (Hệ quản trị cơ sở dữ liệu quan hệ) tốt nhất. Người đồng sáng lập MySQLdb là Michael Widenius, và tên MySQL cũng bắt nguồn từ con gái của Michael.

Cách cài đặt MySQL

Cài đặt MySQL trong Linux / Unix:

Tải xuống gói RPM cho Linux / Unix từ trang web chính thức: https://www.mysql.com/downloads/

Trong thiết bị đầu cuối sử dụng lệnh sau

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

Để đăng ký Linux

mysql --version

Cài đặt MySQL trong Windows

Tải xuống cơ sở dữ liệu MySQL exe từ trang web chính thức và cài đặt như cài đặt bình thường thông thường của phần mềm trong Windows. Tham khảo hướng dẫn này để biết hướng dẫn từng bước

Cài đặt Thư viện trình kết nối MySQL cho Python

Đối với Python 2.7 hoặc thấp hơn, hãy cài đặt bằng cách sử dụng pip như sau:

pip install mysql-connector

Đối với phiên bản Python 3 trở lên, cài đặt bằng pip3 như:

pip3 install mysql-connector 

Kiểm tra kết nối Cơ sở dữ liệu MySQL với Python

Để kiểm tra kết nối cơ sở dữ liệu ở đây, chúng tôi sử dụng trình kết nối MySQL được cài đặt sẵn và chuyển thông tin đăng nhập vào hàm connect () như máy chủ lưu trữ, tên người dùng và mật khẩu.

Cú pháp để truy cập MySQL bằng Python:

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

Thí dụ,

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

Đầu ra:

Ở đây đầu ra hiển thị kết nối được tạo thành công.

Tạo cơ sở dữ liệu trong MySQL bằng Python

Cú pháp để tạo cơ sở dữ liệu mới trong SQL là

CREATE DATABASE "database_name"

Bây giờ chúng ta tạo cơ sở dữ liệu bằng Python trong 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)

Đầu ra:

Đây là hình ảnh trên cho thấy cơ sở dữ liệu my_first_db đã được tạo

Tạo bảng trong MySQL bằng Python

Hãy tạo một bảng đơn giản "sinh viên" có hai cột.

Cú pháp SQL:

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

Thí dụ:

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)

Đầu ra:

 ('student',) 

Tạo bảng bằng khóa chính

Hãy tạo một bảng Nhân viên với ba cột khác nhau. Chúng tôi sẽ thêm khóa chính trong cột id với ràng buộc AUTO_INCREMENT

Cú pháp SQL,

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

Thí dụ,

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)

Đầu ra:

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

Bảng ALTER trong MySQL với Python

Lệnh Alter được sử dụng để sửa đổi cấu trúc Bảng trong SQL. Ở đây chúng tôi sẽ thay đổi bảng Sinh viên và thêm khóa chính vào trường id .

Cú pháp SQL,

ALTER TABLE student MODIFY id INT PRIMARY KEY

Thí dụ,

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")

Đầu ra:

Ở đây bên dưới bạn có thể thấy cột id đã được sửa đổi.

Chèn hoạt động với MySQL bằng Python:

Hãy thực hiện thao tác chèn trong bảng Cơ sở dữ liệu MySQL mà chúng ta đã tạo. Chúng ta sẽ chèn dữ liệu oi bảng SINH VIÊN và bảng NHÂN VIÊN.

Cú pháp SQL,

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

Thí dụ,

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")

Đầu ra:

 2 Record Inserted