【问题标题】:Python - Import CSV file and save it into Database SQLAlchemyPython - 导入 CSV 文件并将其保存到数据库 SQLAlchemy
【发布时间】:2016-08-12 04:46:48
【问题描述】:

我在将 CSV 文件导入数据库时​​遇到问题... 我在 Python 中使用 SQLAlchemy 并希望打开一个 CSV 文件而不是在 QTableWidget 中显示它以更改值并在将其写入 DB(新表)之后。

def setinTable(self):

    colcnt = len(self.title)
    rowcnt = len(self.data)
    self.tabel_model = QtGui.QTableWidget(rowcnt, colcnt)
    vheader = QtGui.QHeaderView(QtCore.Qt.Orientation.Vertical)
    self.tabel_model.setVerticalHeader(vheader)
    hheader = QtGui.QHeaderView(QtCore.Qt.Orientation.Horizontal)
    self.tabel_model.setHorizontalHeader(hheader)
    self.tabel_model.setHorizontalHeaderLabels(self.title)
    for i in range(rowcnt):
        for j in range(len(self.data[0])):
            item = QtGui.QTableWidgetItem(str(self.data[i][j]))
            self.tabel_model.setItem(i, j, item)
    self.tabel_model.horizontalHeader().sectionDoubleClicked.connect(self.changeHorizontalHeader)
    self.setCentralWidget(self.tabel_model)

获取 CSV 数据

def getdata(filepath):
    with open(filepath, 'r') as csvfile:
        sample = csvfile.read(1024)
        dialect = csv.Sniffer().sniff(sample, [';',',','|'])
        csvfile.seek(0)

        reader = csv.reader(csvfile,dialect=dialect)
        header = next(reader)
        lines = []
        for line in reader:
            lines.append(line)
        return lines

在 QTableWidget 中读取和显示 CSV 文件数据正在工作.. 但我不知道如何将其保存到 MySQL 数据库

【问题讨论】:

    标签: python mysql csv


    【解决方案1】:

    要更简单地将 csv 加载到数据库表中,请查看“odo”python 项目 - https://pypi.python.org/pypi/odo/0.3.2

    --

    要通过 SQL Alchemy 使用表,一种方法是使用 session 并调用“更新”:

    myRow = myTable(
              column_a = 'foo',
              column_b = 'bar')
    
    myRow.column_c = 1 + 2
    
    mySession.update(myRow)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2017-05-09
      • 2018-09-11
      • 1970-01-01
      • 2015-10-12
      • 2012-07-11
      • 1970-01-01
      相关资源
      最近更新 更多