在python中使用mysql Connector插入数据 [英] inserting data using mysql Connector in python
问题描述
我遇到了一个有线问题,即当我要向数据库中插入数据时,它也不会插入并且也不会失败(抛出异常)! ,如果数据重复或提供的表错误,则会引发异常!
i've faced an wired problem that's when i'am about to insert data into my database it's not inserting and not failing (throwing exception) either ! ,, when data is duplicated or wrong table provided it's throws exceptions !!
这是我的代码!
from mysql import connector
con = connector.Connect(user='root',password='root',database='test',host='localhost')
cur=con.cursor()
cur.execute("""insert into user values ('userName', 'passWord')""")
数据库test
仅包含一个表users
,并包含3个字段,分别是id
和username
和password
,用户名是唯一的,id是A_I
the database test
include only one table which is users
and include 3 fields which is id
and username
and password
, username is unique and id is A_I
注释 我也用过这个查询! :
note i've used this query also ! :
"插入用户(
username
,password
)值('userName', 'passWord');""
"""insert into user (
username
,password
) values ('userName', 'passWord');"""
尝试了很多方法,但是什么也没发生(未插入,也没有抛出异常!)
and tried so many ways , but nothing happend (not inserted and no exceptions throwed either !)
推荐答案
from mysql import connector
con = connector.Connect(user='root',password='root',database='test',host='localhost')
cur=con.cursor()
cur.execute("""insert into user values ('userName', 'passWord')""")
**con.commit()**
con.close()
您可能忘记使用con.commit将更改提交到数据库.
You probably forget to use con.commit, to commit your changes to database.
不要对每个INSERT/UPDATE操作使用con.commit(),而是将其用于按SQL规则进行逻辑组合的一组操作
这篇关于在python中使用mysql Connector插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!