python使用mysql数据库,增删改查

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32716885/article/details/83856037

需要注意的是:

mysql数据建立的表中,字段名中不能出现key当字段名。

因为使用python中调用插入语句时,不能成功插入。

导入库

import MySQLdb

连接数据库

#打开数据库连接
db = MySQLdb.connect(localhost_name, user_name , password ,database_name,charset='utf8')
#使用cursor()方法获取操作游标
cursor = db.cursor()

增加一条数据

#Add    添加数据
def insert( word , wordpart):
    sql = "INSERT INTO stopword(word,wordPart)VALUES('" + word + "','" + wordpart + "')"
    print("插入数据:" , sql)

删除一条数据

sql = "DELETE FROM stopword WHERE word = '" + word + "';"

更新一条数据

sql = "UPDATE stopword set word='" + word + "',wordPart='" + new_wordpart + "' WHERE word='" + word +"',wordPart='" + wordpart+"';"
扫描二维码关注公众号,回复: 3981253 查看本文章

以上三种操作是针对数据库直接进行的,所以,当操作完成后,需要保存操作的内容,否则不能存储成功!

try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 发生错误时回滚
    db.rollback()
    print('保存数据失败!')

查找数据

sql = "SELECT id,word,wordPart FROM stopword WHERE word='" + word + "';"
cursor.execute(sql)
results = cursor.fetchall()
#results表示搜索出来的结果

#显示查询的结果
for row in results:
    fid = row[0]
    fword = row[1]
    fwordPart = row[2]
    print('id =%s, 词 = %s , 词性 = %s'%(fid , fword , fwordPart))

猜你喜欢

转载自blog.csdn.net/qq_32716885/article/details/83856037
今日推荐