简体   繁体   中英

Python - Import CSV file and save it into Database SQLAlchemy

i have a prblem with importing CSV-file into Database... Im using SQLAlchemy in Python and wanted to open a CSV-File than show it in QTableWidget to maybe change the values and after write it to DB (New Table).

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)

Get CSV-Data

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

Reading and showing the CSV-File data in a QTableWidget is working .. but i dont know how to save it to a MySQL Database

For an easier way to load a csv into a database table, check out the 'odo' python project - https://pypi.python.org/pypi/odo/0.3.2

--

To use a table via SQL Alchemy one approach is to use a session and call "update":

myRow = myTable(
          column_a = 'foo',
          column_b = 'bar')

myRow.column_c = 1 + 2

mySession.update(myRow)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM