Python MySQL Insert Into Table

Insert Into Table – Хүснэгтэд Мэдээлэл Оруулах #

To fill a table in MySQL, use the “INSERT INTO” statement.

MySQL хүснэгтэд мөр нэмэх дээ “INSERT INTO” командыг ашиглана.

Example – Жишээ #

Insert a record in the “customers” table:

“customers” хүснэгтэд мөр нэмэх:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John""Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount"record inserted.")

Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise no changes are made to the table.

Чухал!: mydb.commit() үйлдлийг хэрэгжүүлж байгаа эсэхийг шалгана уу. Энэ нь хүснэгтэд өөрчлөлт оруулахад зайлшгүй шаардлагатай.

Insert Multiple Rows – Олон мөр оруулах  #

To insert multiple rows into a table, use the executemany() method.

Олон мөрийг хүснэгтэд оруулахын тулд executemany() аргыг ашиглана.

The second parameter of the executemany() method is a list of tuples, containing the data you want to insert:

executemany() аргын хоёр дахь параметр нь таны оруулахыг хүсэж буй өгөгдлийг агуулсан tuples жагсаалт юм:

Example – Жишээ #

Fill the “customers” table with data:

“customers” хүснэгтэд олон мөр нэмэх:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
  ('Peter''Lowstreet 4'),
  ('Amy''Apple st 652'),
  ('Hannah''Mountain 21'),
  ('Michael''Valley 345'),
  ('Sandy''Ocean blvd 2'),
  ('Betty''Green Grass 1'),
  ('Richard''Sky st 331'),
  ('Susan''One way 98'),
  ('Vicky''Yellow Garden 2'),
  ('Ben''Park Lane 38'),
  ('William''Central st 954'),
  ('Chuck''Main Road 989'),
  ('Viola''Sideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")

Get Inserted ID – Оруулсан Мөрийн ID-г Авах #

You can get the id of the row you just inserted by asking the cursor object.

Сүүлд оруулсан мөрийн id-г авахын тулд курсор объектыг ашиглана.

Note: If you insert more than one row, the id of the last inserted row is returned.

Тэмдэглэл: Хэрвээ нэгээс их мөр оруулсан бол, хамгийн сүүлд оруулсан мөрийн ID-г буцаана.

Example – Жишээ #

Insert one row, and return the ID:

Нэг мөр нэмээд ID-г авах:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Michelle""Blue Village")
mycursor.execute(sql, val)
mydb.commit()
print("1 record inserted, ID:", mycursor.lastrowid)

Powered by BetterDocs

Leave a Reply