在Python中更新文件数据库通常指的是更新数据库中的数据。以下是使用不同方法更新数据库数据的示例:
方法一:使用MySQLdb模块
import MySQLdb
HOST = '127.0.0.1'
USER = 'root'
PASSWD = ''
DB = 'db_name'
db = MySQLdb.connect(HOST, USER, PASSWD, DB)
cursor = db.cursor()
if __name__ == '__main__':
command_a = 'update tables_one set status=5 where status=0'
cursor.execute(command_a)
db.commit()
command2 = 'select field from tables_one where id =12'
ret2 = cursor.execute(command2)
ret2 = cursor.fetchall()
for item in ret2:
command3 = 'insert into tables_two(name) values (%s)' % (item)
cursor.execute(command3)
db.close()
方法二:使用SQLAlchemy库
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
engine = create_engine('sqlite:///example.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
更新数据
session.execute("update users set name='吴老师' where age=26")
session.commit()
session.close()
方法三:使用pymysql库
import pymysql
def update(sql):
con = pymysql.connect(host='localhost', port=3306, user='root', password='', db='test', charset='utf8')
cur = con.cursor()
cur.execute(sql)
con.commit()
cur.close()
con.close()
if __name__ == '__main__':
sql = 'update test.user set name=\'吴老师\' where age=26'
update(sql)
方法四:使用paramiko库进行远程服务器文件更新
import paramiko
import os
host = 'xxx.65.9.191'
port = 22
username = 'root'
password = 'root'
def judgeFileExist():
global currentIndex
currentIndex = os.getcwd() + '/Index.php'
if not os.path.isfile(currentIndex):
print('Index文件不存在')
exit()
print('文件检测成功,准备连接服务器...')
def creatConnect():
try:
print('开始连接服务器...')
s = paramiko.Transport((host, port))
s.connect(username=username, password=password)
except Exception as e:
print(e)
s.close()
creatConnect()
以上示例展示了如何使用不同的Python库来更新数据库中的数据。请根据您的具体需求选择合适的方法。