Python với MySQL Kết nối: Cơ sở dữ liệu & Bảng [Ví dụ]

⚡ Tóm tắt thông minh

Python kết nối với một MySQL database using the mysql-connector library. Here you will learn to install the connector, connect to MySQL, create databases and tables, add primary keys, alter tables, and insert records with examples.

  • 🔌 Kết nối: mysql.connector.connect() links Python đến MySQL with host and credentials.
  • 🗄️ Tạo nên: Run CREATE DATABASE and CREATE TABLE through a cursor.
  • Chèn: execute() an INSERT query, then commit() to save records.
  • 🤖 Hỗ trợ từ AI: Các công cụ AI như Copilot tạo ra MySQL connector code instantly.

Python với MySQL Kết nối

Để sử dụng MySQL kết nối với Python, bạn phải có một số kiến ​​thức về SQL

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

Là gì MySQL?

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

Làm thế nào để cài đặt MySQL của DINTEK Python on Windows, Linux/Unix

đặ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 terminal sử dụng lệnh sau

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

Để kiểm tra Linux

mysql --version

đặt MySQL in Windows

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

Làm thế nào để cài đặt MySQL Thư viện kết nối cho Python

Đây là cách kết nối MySQL với Python:

Trong cáp Python 2.7 hoặc thấp hơn cài đặt bằng pip như:

pip install mysql-connector

Trong cáp Python Cài đặt phiên bản 3 trở lên bằng pip3 như:

pip3 install mysql-connector

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

Để kiểm tra MySQL kết nối cơ sở dữ liệu trong Python ở đây, chúng tôi sẽ sử dụng cài đặt sẵn MySQL kết nối và chuyển thông tin đăng nhập vào kết nối() chức năng như máy chủ, tên người dùng và mật khẩu như dưới đây Python MySQL ví dụ về đầu nối.

Cú pháp truy cập MySQL với Python:

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

Ví dụ:

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

Đầu ra:

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

Ở đâ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 sử dụ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 lập trình cơ sở dữ liệu trong 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)

Đầu ra:

Tạo cơ sở dữ liệu trong MySQL

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

Tạo một bảng trong MySQL với Python

Hãy tạo một bảng đơn giản “student” có hai cột như bên dưới MySQL kết nối Python thí dụ.

Cú pháp SQL:

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

Ví dụ:

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)

Đầu ra:

 ('student',)

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

Hãy tạo một Công nhân bảng có ba cột khác nhau. Chúng tôi sẽ thêm khóa chính vào id cột có ràng buộc AUTO_INCREMENT như hiển thị bên dưới Python dự án có kết nối cơ sở dữ liệu.

Cú pháp SQL:

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

Ví dụ:

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)

Đầu ra:

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

bảng ALTER trong MySQL với Python

Lệnh thay đổi được sử dụng để sửa đổi cấu trúc Bảng trong SQL. Ở đây chúng ta sẽ thay đổi Học Sinh bảng và thêm một khóa chính đến id trường như minh họa bên dưới Python MySQL dự án kết nối.

Cú pháp SQL:

ALTER TABLE student MODIFY id INT PRIMARY KEY

Ví dụ:

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

Đầu ra:

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

bảng ALTER trong MySQL

Chèn Operaquan hệ với MySQL in Python:

Hãy thực hiện thao tác chèn vào MySQL Bảng cơ sở dữ liệu mà chúng tôi đã tạo. Chúng ta sẽ chèn dữ liệu vào 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)

Ví dụ:

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

Đầu ra:

 2 Record Inserted

Câu Hỏi Thường Gặp

Install mysql-connector with pip, then call mysql.connector.connect() with your host, user, and password to get a connection object.

Create a cursor, then run cursor.execute(‘CREATE DATABASE name’). Use SHOW DATABASES to confirm it was created.

Connect, create a cursor, and execute a CREATE TABLE statement. Add AUTO_INCREMENT PRIMARY KEY to auto-number the id column.

Execute a SELECT query with the cursor, then call fetchall() for all rows or fetchone() for a single row.

Run an UPDATE or DELETE statement with cursor.execute(), then commit(). Always add a WHERE clause to target specific rows.

AI assistants like GitHub Copilot autocomplete connector code, generate CRUD queries, and suggest parameterized statements that prevent SQL injection.

Yes. AI-powered tools write connection and CRUD functions, map tables to classes, and add error handling for failed queries.

commit() saves changes permanently. Without it, INSERT, UPDATE, and DELETE operations roll back when the connection closes, losing data.

Tóm tắt bài viết này với: