mysql python官方手册_Python MySQL插入操作

插入操作

向表中添加记录

该INTO INSERT语句用来记录添加到表。在python中,我们可以提到格式说明符(%s)来代替值。

我们在游标的execute()方法中以元组的形式提供实际值。

请考虑以下示例。

例import mysql.connector

#Create the connection object

myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")

#creating the cursor object

cur = myconn.cursor()

sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"

#The row values are provided in the form of tuple

val = ("John", 110, 25000.00, 201, "Newyork")

try:

#inserting the values into the table

cur.execute(sql,val)

#commit the transaction

myconn.commit()

except:

myconn.rollback()

print(cur.rowcount,"record inserted!")

myconn.close()

输出:1 record inserted!

4ba9ac6574f1f6b3368a520b7a270b2b.png

插入操作

插入多行

我们也可以使用python脚本一次插入多行。提到多行作为各种元组的列表。

列表的每个元素都被视为一个特定的行,而元组的每个元素都被视为一个特定的列值(属性)。

请考虑以下示例。

例import mysql.connector

#Create the connection object

myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")

#creating the cursor object

cur = myconn.cursor()

sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"

val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of spain"),("Nick",104,90000.00,201,"Newyork")]

try:

#inserting the values into the table

cur.executemany(sql,val)

#commit the transaction

myconn.commit()

print(cur.rowcount,"records inserted!")

except:

myconn.rollback()

myconn.close()

输出:3 records inserted!

d58d8fc821b55c73ad98887ce8268e8c.png

插入操作

行ID

在SQL中,特定行由插入标识表示,该标识称为行标识。我们可以使用游标对象的属性lastrowid来获取最后插入的行id。

请考虑以下示例。

例import mysql.connector

#Create the connection object

myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")

#creating the cursor object

cur = myconn.cursor()

sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"

val = ("Mike",105,28000,202,"Guyana")

try:

#inserting the values into the table

cur.execute(sql,val)

#commit the transaction

myconn.commit()

#getting rowid

print(cur.rowcount,"record inserted! id:",cur.lastrowid)

except:

myconn.rollback()

myconn.close()

输出:1 record inserted! Id: 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值