PythonMySQL插入操作

PythonMySQL插入操作

2023年7月7日发(作者:)

PythonMySQL插⼊操作Python MySQL插⼊操作1、向表中添加记录1. 该 INTO INSERT 语句⽤来记录添加到表。在python中,我们可以提到格式说明符(%s)来代替值。2.我们在游标的 execute() ⽅法中以元组的形式提供实际值2. 案例import tor

# 创建⼀个连接对象

myconn = t(host="192.168.126.20", user="root", passwd="mysql", database="PythonDB")# 创建游标对象cur = ()

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:

# 向表中插⼊数据

e(sql,val)

# 提交事务处理

()

except:

ck()

print(nt,"record inserted!")

()输出1 record inserted!2、插⼊(添加)多⾏记录1. 插⼊多⾏,我们也可以使⽤python脚本⼀次插⼊多⾏。多⾏作为各种元组的列表2. 列表的每个元素都被视为⼀个特定的⾏,⽽元组的每个元素都被视为⼀个特定的列值(属性)3. ⽰例import tor

myconn = t(host="192.168.126.20", user="root", passwd="mysql", database="PythonDB")

cur = ()

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:

emany(sql,val)

()

except:

ck()

print(nt,"records inserted!")

()输出3 records inserted!3、⾏ID1. 在SQL中,特定⾏由插⼊标识表⽰,该标识称为⾏标识。2. 我们可以使⽤游标对象的属性 lastrowid 来获取最后插⼊的⾏id。3. 案例import tor

myconn = t(host="192.168.126.20", user="root", passwd="mysql", database="PythonDB")

cur = ()

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

e(sql,val)

#commit the transaction

()

#getting rowid

print(nt,"record inserted! id:",wid)

except:

ck()

()输出1 record inserted! id: 0

发布者:admin,转转请注明出处:http://www.yc00.com/news/1688701099a163684.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信