Not properly inserting simple Varchar? Generating string

0

Running into an odd error and I just can't figure out what is going wrong. So I have a MySQL server I am running with a table setup using this script:

CREATE TABLE Cases (
systemSN VARCHAR(15),
caseID int PRIMARY KEY AUTO_INCREMENT);

In Python 3.8.6, I am currently trying to implement a large form with some 19 fields into one table on a database, but I was running into problems so I have narrowed it down field by field, and this is the current basic INSERT I am unable to implement.

To generate the variable I am trying to insert into the MySQL database, I have users choose either line edits or comboboxes to select text strings, then I try, and have them upload those values into the table.

The combobox is displaying a list of strings like:

systemSNs = ['----------------------', 'S129', '2342', 'a;sld']
for x in systemSNs:
    self.ncw_SystemSN_CB.addItem(x)

The function I use to pass the combobox value into the MySQL function is:

def submitNewCase_call(self):
    print(self.ncw_SystemSN_CB.currentText())
    print(type(self.ncw_SystemSN_CB.currentText()))
    inputNewCaseintoDB(
        self.ncw_SystemSN_CB.currentText()
        )

And then I use this function to attempt to load the information into the database:

def inputNewCaseintoDB(systemSN):

    db = dbConnect()  #connects to my database
    mycursor = db.cursor()
    addCase = ("INSERT INTO Cases "
               "(systemSN) "
               "VALUES (%s)")
    mycursor.execute(addCase, systemSN)
    
    print(systemSN)
    db.commit()
    db.close()

The Python error code I get in my pycharm terminal is: Process finished with exit code -1073740791 (0xC0000409)

If I substitute the variable systemSN for a int, I am able to do the insert fine, but for some reason I can't seem to input strings and I don't understand why not.

edit1:

Ex:

testFormMain.py

from testForm import Ui_MainWindow
from PyQt5 import QtWidgets
import sys
import mysql.connector

def dbConnect():
    db = mysql.connector.connect(
        host="localhost",
        user="root",
        passwd="password!",
        database="mysqldb"
    )
    return db

def inputNewCaseintoDB(systemSN):
    print(systemSN)
    db = dbConnect()
    mycursor = db.cursor()

    mycursor.execute("INSERT INTO Cases "
                     "(systemSN)"
                     "VALUES (%s)",
                     (systemSN))
    db.commit()
    db.close()

class testFormMain(QtWidgets.QMainWindow,
                      Ui_MainWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setupUi(self)

        self.ncw_Submit_PB.clicked.connect(self.submitNewCase_call)

        systemSNs = ['----------------------', 'S129', '2342', 'a;sld']
        for x in systemSNs:
            self.ncw_SystemSN_CB.addItem(x)



    def submitNewCase_call(self):
        inputNewCaseintoDB(self.ncw_SystemSN_CB.currentText())

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    widget = testFormMain()
    widget.show()

    app.exec_()

testForm.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'testForm.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(393, 307)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.ncw_Submit_PB = QtWidgets.QPushButton(self.centralwidget)
        self.ncw_Submit_PB.setGeometry(QtCore.QRect(150, 210, 75, 23))
        self.ncw_Submit_PB.setObjectName("ncw_Submit_PB")
        self.ncw_SystemSN_CB = QtWidgets.QComboBox(self.centralwidget)
        self.ncw_SystemSN_CB.setGeometry(QtCore.QRect(90, 70, 231, 81))
        self.ncw_SystemSN_CB.setObjectName("ncw_SystemSN_CB")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 393, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.ncw_Submit_PB.setText(_translate("MainWindow", "Submit"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


edit2: An example of a function from elsewhere in my code that is trying to do a similar task (putting line edit fields into a database table) for James. This one had no problems working as intended regardless of the characters I try to fill the VARCHAR with.

def addCompany(companyName, businessPhone, faxPhone, streetAddress, city, state, zipCode, country):
    print(companyName, businessPhone, faxPhone, streetAddress, city, state, zipCode, country)
    db = dbConnect()
    mycursor = db.cursor()

    mycursor.execute("INSERT INTO Company "
                     "(companyName,"
                     "businessPhone,"
                     "faxPhone,"
                     "streetAddress,"
                     "city,"
                     "state,"
                     "zipCode,"
                     "country)"
                     "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
                     (companyName, businessPhone, faxPhone, streetAddress, city, state, zipCode, country))
    db.commit()
    db.close()
python
mysql
pyqt5
varchar
qcombobox
asked on Stack Overflow Nov 18, 2020 by Gus • edited Nov 18, 2020 by Gus

1 Answer

0

It looks like the reason I was having so many problems is there is some non-intuitive formatting that happens when using python to insert single variables into a mysql database.

When I wrote the statement:

mycursor.execute("INSERT INTO Cases (systemSN) VALUES (%s)", (systemSN))

I was getting 1064 errors that didn't like my formatting. The problem is the variable name needed to be passed in a tuple. The statement:

mycursor.execute("INSERT INTO Cases (systemSN) VALUES (%s)", (systemSN,))

works fine.

I thought I was being smart trying to whiddle my insert down to a single variable at a time, but really I was just discovering a new problem!

Thanks for the tip on executing from console. Much more useful error messaging! Appreciate all the help.

answered on Stack Overflow Nov 19, 2020 by Gus • edited Nov 19, 2020 by eyllanesc

User contributions licensed under CC BY-SA 3.0