闽公网安备 35020302035485号
语言: python v3.9.1
pip install pymysql or pip3 install pymysql代码
import pymysql
// 堆代码 duidaima.com
def init(host,user,password,db):
db = pymysql.connect(host,user,password,db)
return db
"""
查询操作
"""
def query(sql,db):
"""
创建一个对数据库进行查询的方法
"""
cursor = db.cursor() # 获取游标窗口
try:
cursor.execute(sql) # 执行sql语句
res = cursor.fetchall() # 获取返回值
db.close() # 关闭数据库
print(res)
except:
print("sql语句错误")
def commit(sql,db):
"""
对表进行增加,删除,修改都可以
"""
cursor = db.cursor()
try:
cursor.execute(sql) # 执行sql语句
db.commit() # 对数据进行保存
except:
print("sql语句错误")
db = init("192.168.1.102","root","root","raxianch") # 初始化数据库句柄
commit("update cxy_nct_m_t set drug_id = 2 where id = nct123",db)
query("select * from cxy_nct_m_t",db)
注意...
sql = "update cxy_nct_m_t set drug_id = '%s' where id = '%s' %" ("2", "nct123")
...
# 使用execute方法执行时会直接报错
cursor.execute(sql)
正确示范...
sql = "update cxy_nct_m_t set drug_id = %s where id = %s %"
...
# 去除掉%s旁边的单引号,然后使用元组或列表往execute方法传参,让execute方法自己转义特殊符号。
cursor.execute(sql,("2", "nct123"))