Hướng dẫn insert into sql python
Câu lệnh INSERT INTO được sử dụng để thêm một bản ghi vào bảng. Trong python, chúng ta có thể sử dụng (%s) thay cho các giá trị. Phương thức cursor.execute() được sử dụng để insert 1 bản ghi vào table. Chúng ta cung cấp các giá trị thực tế trong một tuple trong phương thức cursor.execute(). Kết quả: INSERT nhiều bản ghiPhương thức cursor.executemany() được sử dụng để insert 1 bản ghi vào table. 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() sql = ("insert into Employee(name, id, salary, dept_id, branch_name) " "values (%s, %s, %s, %s, %s)") #giá trị của một row được cung cấp dưới dạng tuple val = [("Vinh", 10002, 26000.00, 101, "Hanoi"), ("Trung", 10003, 26000.00, 102, "Danang")] try: #inserting the values into the table cur.executemany(sql, val) #commit the transaction myconn.commit() except: myconn.rollback() print(cur.rowcount,"record inserted!") myconn.close() Kết quả: Insert Into TableTo fill a table in MySQL, use the "INSERT INTO" statement. ExampleInsert a record in the "customers" table: import mysql.connector mydb = mysql.connector.connect( mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address) VALUES (%s,
%s)" Run example » Important!: Notice the statement: Insert Multiple RowsTo insert multiple
rows into a table, use the The second parameter of the ExampleFill the "customers" table with data: import mysql.connector mydb = mysql.connector.connect( mycursor = mydb.cursor() sql = "INSERT INTO
customers (name, address) VALUES (%s, %s)" mycursor.executemany(sql, val) mydb.commit() print(mycursor.rowcount, "was inserted.") Run example » Get Inserted IDYou can get the id of the row you just inserted by asking the cursor object. Note: If you insert more than one row, the id of the last inserted row is returned. ExampleInsert one row, and return the ID: import mysql.connector mydb = mysql.connector.connect( mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" mydb.commit() print("1 record inserted, ID:", mycursor.lastrowid) Run example » |