Làm thế nào để bạn chèn một hàng trong sql bằng python?

(Nhà tài trợ) Bắt đầu học Python với hướng dẫn Giới thiệu về Python miễn phí của DataCamp. Tìm hiểu Khoa học dữ liệu bằng cách hoàn thành các thử thách mã hóa tương tác và xem video của các chuyên gia hướng dẫn. Bắt đầu bây giờ


Cập nhật ngày 07 tháng 1 năm 2020


Câu lệnh Insert được sử dụng để chèn các bản ghi trong mysql

cú pháp. ________số 8

ví dụ 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20

from __future__ import print_function

import MySQLdb as my

db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)

cursor = db.cursor()

sql = "insert into city VALUES(null, 'Mars City', 'MAC', 'MARC', 1233)"

number_of_rows = cursor.execute(sql)
db.commit()   # you need to call commit() method to save 
              # your changes to the database


db.close()

Chương trình này chèn một thành phố mới vào bảng thành phố, chú ý sử dụng tới db.commit(), phương pháp này lưu các thay đổi của bạn vào cơ sở dữ liệu

ví dụ 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

from __future__ import print_function

import MySQLdb as my

db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)

cursor = db.cursor()

name = "Some new city"
country_code = 'PSE'
district = 'Someyork'
population = 10008

sql = "insert into city VALUES(null, '%s', '%s', '%s', %d)" % \
 (name, country_code , district, population)

number_of_rows = cursor.execute(sql)
db.commit()

db.close()

Lưu ý việc sử dụng ký tự dấu gạch chéo ngược (

from __future__ import print_function

import MySQLdb as my

db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)

cursor = db.cursor()

sql = "insert into city VALUES(null, 'Mars City', 'MAC', 'MARC', 1233)"

number_of_rows = cursor.execute(sql)
db.commit()   # you need to call commit() method to save 
              # your changes to the database


db.close()
0) trong dòng 18. Ký tự
from __future__ import print_function

import MySQLdb as my

db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)

cursor = db.cursor()

sql = "insert into city VALUES(null, 'Mars City', 'MAC', 'MARC', 1233)"

number_of_rows = cursor.execute(sql)
db.commit()   # you need to call commit() method to save 
              # your changes to the database


db.close()
0 dùng để chia câu lệnh python thành nhiều dòng

Chèn nhiều hàng


Để chèn nhiều hàng vào bảng, hãy sử dụng phương thức

from __future__ import print_function

import MySQLdb as my

db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)

cursor = db.cursor()

sql = "insert into city VALUES(null, 'Mars City', 'MAC', 'MARC', 1233)"

number_of_rows = cursor.execute(sql)
db.commit()   # you need to call commit() method to save 
              # your changes to the database


db.close()
0 của đối tượng con trỏ

cú pháp.

from __future__ import print_function

import MySQLdb as my

db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)

cursor = db.cursor()

sql = "insert into city VALUES(null, 'Mars City', 'MAC', 'MARC', 1233)"

number_of_rows = cursor.execute(sql)
db.commit()   # you need to call commit() method to save 
              # your changes to the database


db.close()
1

bản tường trình. chuỗi chứa truy vấn để thực thi

tranh luận. một chuỗi chứa các giá trị để sử dụng trong câu lệnh chèn

Hãy lấy một ví dụ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

from __future__ import print_function

import MySQLdb as my

db = my.connect(host="127.0.0.1",
user="root",
passwd="",
db="world"
)

cursor = db.cursor()
name = "Some new city"

country_code = 'SNC'

district = 'Someyork'

population = 10008

data = [
('city 1', 'MAC', 'distrct 1', 16822),
('city 2', 'PSE', 'distrct 2', 15642),
('city 3', 'ZWE', 'distrct 3', 11642),
('city 4', 'USA', 'distrct 4', 14612),
('city 5', 'USA', 'distrct 5', 17672),
]

sql = "insert into city(name, countrycode, district, population) 
VALUES(%s, %s, %s, %s)"

number_of_rows = cursor.executemany(sql, data)
db.commit()

db.close()

Trong bài tiếp theo, chúng tôi thảo luận về cách xử lý lỗi


Hướng dẫn khác (Nhà tài trợ)

Trang web này được hỗ trợ rộng rãi bởi DataCamp. DataCamp cung cấp Hướng dẫn Python tương tác trực tuyến cho Khoa học dữ liệu. Tham gia cùng hơn một triệu người học khác và bắt đầu học Python cho khoa học dữ liệu ngay hôm nay

# Ví dụ chương trình Python để chèn hàng vào bảng cơ sở dữ liệu MySQL

# nhập ứng dụng khách mysql cho python
nhập pymysql

# Tạo đối tượng kết nối
dbServerName    = "127. 0. 0. 1"
dbUser          = "root"
dbPassword      = ""
dbName          = "test"
charSet         = "utf8mb4"

connectionObject   = pymysql. kết nối(host=dbServerName, user=dbUser, password=dbPassword,
                                    db=dbName, charset=charSet)

thử.
    # Tạo đối tượng con trỏ
    cursorObject          = connectionObject. con trỏ()                                 

    # Chuỗi SQL để tạo bảng MySQL
    sqlCreateTableCommand     = "CREATE TABLE Employee(id int(11) AUTO_INCREMENT PRIMARY KEY, LastName varchar(32), FirstName varchar(32),

    # Thực thi sqlQuery
    cursorObject. thực thi(sqlCreateTableCommand)

    # Liệt kê bảng bằng lệnh SQL
    sqlShowTablesCommand    = "hiển thị bảng"   

    # Thực thi lệnh SQL
    cursorObject. thực thi(sqlShowTablesCommand)

    #Tìm nạp tất cả các hàng - từ đầu ra lệnh
    hàng              = cursorObject. fetchall()
  cho hàng trong hàng.
      in(hàng)

    # Chèn hàng vào Bảng MySQL
    insertStatement = "INSERT INTO Employee (id, LastName, FirstName, Department Code) VALUES (1,\"Albert\",\"Einstein\ . thực thi(insertStatement)
    cursorObject.execute(insertStatement)

    # Lấy giá trị khóa chính của hàng được chèn vào cuối cùng
    print("Id khóa chính của hàng được chèn vào cuối cùng. ")
    print(cursorObject. cuối cùng)

    # Truy vấn SQL để truy xuất các hàng
    Truy vấn sql     = "select * from Employee"   

    #Tìm nạp tất cả các hàng - cho Truy vấn SQL
    cursorObject. thực thi(sqlQuery)
    rows = cursorObject. tìm nạp ()

    cho hàng trong hàng.
        in(hàng)

ngoại trừ Ngoại lệ như e.
    print("Đã xảy ra ngoại lệ. {}". định dạng(e))

cuối cùng.
    connectionObject. đóng()