PHP & MySQL - 插入記錄示例



Python 使用 c.execute(q) 函式在表中插入一條或多條記錄,其中 c 是遊標,q 是要執行的插入查詢。

語法

# execute SQL query using execute() method.
cursor.execute(sql)

# commit the record
db.commit()

# get the row id for inserted record
print("ID:", cursor.lastrowid)

# print the number of records inserted
print(mycursor.rowcount, "records inserted.")

序號 引數 & 說明
1

$sql

必需 - 在表中插入記錄的 SQL 查詢。

示例

嘗試下列示例在表中插入記錄 -

複製並貼上下列示例為 mysql_example.ty -

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS")

# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = """INSERT INTO tutorials_tbl
         (tutorial_title,tutorial_author, submission_date) 
         VALUES ('HTML 5', 'Robert', '2010-02-10'),
         ('Java', 'Julie', '2020-12-10'),
         ('JQuery', 'Julie', '2020-05-10')
         """

# execute SQL query using execute() method.
cursor.execute(sql)

# commit the record
db.commit()

# get the row id for inserted record
print("ID:", cursor.lastrowid)

# print the number of records inserted
print(cursor.rowcount, "records inserted.")

# disconnect from server
db.close()

輸出

使用 Python 執行 mysql_example.py 指令碼並驗證輸出。

ID: 5
3 records inserted.
廣告
© . All rights reserved.