Hướng dẫn python sql create table - python sql tạo bảng

Create table

Trong bài này, chúng ta sẽ tạo ra một bảng MySQL mới có tên là Employee. Chúng ta có thể tạo bảng mới bằng cách sử dụng câu lệnh CREATE TABLE của SQL. Bảng Empoyee sẽ có bốn cột bao gồm name, id, salary và department_id.

Câu lệnh SQL sau được sử dụng để tạo bảng Employee:

create table Employee ( name varchar(20) not null, id int primary key, salary float not null, dept_Id int not null )

Ví dụ:

import mysql.connector # tạo đối tượng connection myconn = mysql.connector.connect(host = "localhost", user = "root", passwd = "1234567890", database = "PythonDB") # tạo đối tượng cursor cur = myconn.cursor() try: # tạo bảng Employee gồm 4 cột name, id, salary, và department id dbs = cur.execute("create table Employee(name varchar(20) not null, " + "id int(20) not null primary key, salary float not null, " + "dept_id int not null)") except: myconn.rollback() myconn.close()

Kết quả:


Alter table

Đôi khi, chúng ta có thể quên tạo một số cột hoặc chúng tôi có thể cần cập nhật table schema. Câu lệnh ALTER được sử dụng trong trường hợp này. Ở đây, chúng ta sẽ thêm cột tên_bảng vào bảng Employee như sau.

alter table Employee add branch_name varchar(20) not null

Ví dụ:

import mysql.connector # tạo đối tượng connection myconn = mysql.connector.connect(host = "localhost", user = "root", passwd = "1234567890", database = "PythonDB") # tạo đối tượng cursor cur = myconn.cursor() try: # thêm cột branch name vào bảng Employee cur.execute("alter table Employee add branch_name varchar(20) not null") except: myconn.rollback() myconn.close()

Kết quả:

Creating a Table

To create a table in MySQL, use the "CREATE TABLE" statement.

Make sure you define the name of the database when you create the connection

Example

Create a table named "customers":

import mysql.connector

mydb = mysql.connector.connect(  host="localhost",   user="yourusername",  password="yourpassword",   database="mydatabase")
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

Run example »

If the above code was executed with no errors, you have now successfully created a table.

Check if Table Exists

You can check if a table exist by listing all tables in your database with the "SHOW TABLES" statement:

Example

Create a table named "customers":

import mysql.connector

mydb = mysql.connector.connect(  host="localhost",   user="yourusername",  password="yourpassword",   database="mydatabase")
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

Run example »
  print(x)

Run example »

If the above code was executed with no errors, you have now successfully created a table.

Check if Table Exists

You can check if a table exist by listing all tables in your database with the "SHOW TABLES" statement:

Return a list of your system's databases:

Example

Create a table named "customers":

import mysql.connector

mydb = mysql.connector.connect(  host="localhost",   user="yourusername",  password="yourpassword",   database="mydatabase")
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

Run example »

If the above code was executed with no errors, you have now successfully created a table.

Example

Create a table named "customers":

import mysql.connector

mydb = mysql.connector.connect(  host="localhost",   user="yourusername",  password="yourpassword",   database="mydatabase")
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

Run example »


Như chúng ta biết, trong mỗi cơ sở dữ liệu thường có nhiều bảng dùng để chứa dữ liệu và để tạo bảng bằng câu lệnh SQL sẽ như sau: CREATE TABLE và để không tạo bảng trùng tên với các bảng đã có trong cơ sở dữ liệu chúng ta sẽ hiển thị toàn bộ bảng đã có bằng câu lệnh SQL như sau: SHOW TABLESCREATE TABLE và để không tạo bảng trùng tên với các bảng đã có trong cơ sở dữ liệu chúng ta sẽ hiển thị toàn bộ bảng đã có bằng câu lệnh SQL như sau: SHOW TABLES

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

Hiển thị toàn bộ bảng đã có trong cơ sở dữ liệu

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("SHOW TABLES") for x in mycursor: print(x)

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

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() try: mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))") except: mydb.rollback()

Tạo bảng có chứa khóa chính Primary Key, dữ liệu của khóa chính không được giống nhau giữa các bản ghi. Chúng ta sẽ sử dụng cú pháp “INT AUTO_INCREMENT PRIMARY KEY” thì dữ liệu của khóa chính sẽ tự động được điền các giá trị duy nhất từ 1 đến số bản ghi cuối cùng.“INT AUTO_INCREMENT PRIMARY KEY” thì dữ liệu của khóa chính sẽ tự động được điền các giá trị duy nhất từ 1 đến số bản ghi cuối cùng.

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() try: mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))") except: mydb.rollback()

Thêm cột cho bảng đã có trong cơ sở dữ liệu

Trong quá trình chúng ta tạo ra bảng, có thể chưa có cột nào đó, do đó chúng ta có thể bổ sung cột đó vào bảng bằng câu lệnh ALTER TABLE, ví dụ thêm cột id như sau:ALTER TABLE, ví dụ thêm cột id như sau:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() try: mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY") except: mydb.rollback()

Chủ đề