Im new to flask and flask-sqlalchemy
Im currently working on website with checkboxes; but im getting an error. Here is the part of the code.
bodygoal= request.form.get('BodyGoal')
workouttype= request.form.getlist('WorkoutType')
slevel= request.form.get('SkillLevel')
new_workout=Workout(bodygoalDB=bodygoal, workouttypeDB=workouttype, slevelDB=slevel, user_id=current_user.id)
db.session.add(new_workout)
db.session.commit()
as for the database model; here is also the part of the part of the code
class Workout(db.Model):
id = db.Column(db.Integer, primary_key=True)
bodygoalDB=db.Column(db.Integer)
workouttypeDB=db.Column(db.String())
slevelDB=db.Column(db.Integer)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
this is the error im getting:
sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 1 - probably unsupported type.
[SQL: INSERT INTO workout ("bodygoalDB", "workouttypeDB", "slevelDB", user_id) VALUES (?, ?, ?, ?)]
[parameters: ('Shredded', ['on', 'Dumbell', 'Barbell'], 'Beginner', 1)]
(Background on this error at: https://sqlalche.me/e/14/rvf5)
the workouttype variables gets all the checkbox values from the website; currently, im planning to store them in 1 cell but Im also accepting suggestions on how to deal with checkbox values with sqlalchemy. thanks :)
request.form.getlist('WorkoutType') is returning a list of strings, e.g. ['on', 'Dumbell', 'Barbell'], but you are trying to assign the list to column of data type string.
You could convert the string array to a comma delimited string:
# Get the string array
workout_types = request.form.getlist('WorkoutType')
# Convert to comma delimited string
workout_csv = ','.join(workout_types)
# etc
new_workout = Workout(bodygoalDB=bodygoal, workouttypeDB=workout_csv, slevelDB=slevel, user_id=current_user.id)
Related
I have a C++ program that inserts values into a database table. I can't directly hardcode the values in because the data is constantly being updated, but I'm really confused about the syntax.
When I try to do this:
l.exec("INSERT INTO course VALUES(cid, term, 'subj',crse, sec, 'units', 'instructors');");
l.exec("INSERT INTO meeting VALUES(cid, term, 'type', 'days', 'time', 'build', room);");
l.exec("INSERT INTO enrolledin VALUES(cid, term, sid, 'major', 'classlevel', 'level', 'status', seat, numunits, 'grade');");
l.exec("INSERT INTO student VALUES(sid, 'surname', 'prefname', 'email');");
I get this error:
terminate called after throwing an instance of 'pqxx::undefined_column'
what(): ERROR: column "cid" does not exist
LINE 1: INSERT INTO course VALUES(cid, term, 'subj',crse, se...
^
HINT: There is a column named "cid" in table "course", but it cannot be referenced from this part of the query.
--
I was told that it's because I was inserting the literal string name instead of the values inside the string, and I'm confused as to how to insert the values inside the string via C++ while still using variable names.
Syntax of the used SQL INSERT query is incorrect. It should be:
INSERT INTO course (cid, subj) VALUES(1, 'subj');
You should specify table name together with columns to insert into and values after that. I reduced number of columns for simplicity. For a complete syntax of INSERT query check the PostgreSQL documentation.
To insert values from your variables you can do the following:
int cidValue = 1;
std::string subjValue = "subj";
l.exec("INSERT INTO course (cid, subj) VALUES(" + std::to_string(cidValue) + ", '" + l.esc(subjValue) + "')");
esc() function helps to prevent SQL injection attack.
So after my research on stackoverflow didn't bring me any further here ist my code (I cannot post the exact code , because this is a problem I have at work) and problem:
import mysql.connector
.
.
.
cnx = mysql.connector.connect(user, password, host, database)
cursor = cnx.cursor()
for-loop:
if condition:
cursor.execute("INSERT INTO table (the_columns) VALUES (%s)", (my_values))
cnx.commit()
I tried to insert manually already and it worked, but somehow my python code won't do the insert.
The manual insert:
INSERT INTO table (column1,...,column7) VALUES (string1,....,string6, now())
I have no error message, I can only look into the database and see that the new valiues aren't there.
Did anyone else face this problem? Can anyone suggest what could be the problem?
Might be because you dont have to put your variable between "(" ")" ?
Did you tried to put the value directly inside the sql, then instead of the variable containing it?
What do you mean by "manually"?
Anyway, you should put all your variables in an array, before passing this array as the second argument:
query = (
"INSERT INTO employees (emp_no, first_name, last_name, hire_date) VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)
EDIT: I just checked, thats the main exemple if you google your problem... wait did you searched for this a little bit? That's the best wait to learn dude: search by yourself before asking for help.
Try turning your format variables into a tuple. If this does not work. Try creating the query as a variable seperately and printing it out and running it in your sql console directly. You might get more meaningful errors.
cnx = mysql.connector.connect(user, password, host, database)
cursor = cnx.cursor()
for-loop:
if condition:
cursor.execute("INSERT INTO table (the_columns) VALUES (%s)", (my_values,))
cnx.commit()
OR
cnx = mysql.connector.connect(user, password, host, database)
cursor = cnx.cursor()
for-loop:
if condition:
sql = "INSERT INTO table ({}) VALUES ({})".format(the_columns,my_values)
print(sql)
cursor.execute(sql)
cnx.commit()
I have a 2nd query where the column names are appearing and I want to insert the data in the main query. I have managed to bring all the columns of 2nd query to the main query, but the data is empty for all newly added columns.
Now I am trying to loop over the first query and trying to find the uuid which exists to insert the specific data at the specific column it finds and at the specific row based upon the uuid search. This is my try as of now:
<cfset lstusers = '51840915-e570-430d-9911-7247d076f6e7,5200915-g675-430d-9911-7247d076f6e7,56674915-e570-430d-9911-7247d076f6e7,2134563-e570-430d-9911-7247d076f6e7'>
<cfloop query="quserList">
<cfdump var="#quserList.uuid[currentRow]#">
<cfif ListContainsNoCase(lstusers,quserList.uuid[currentRow])>
<cfset QuerySetCell(quserList,"BUFFEREDRANGENOTES","name",quserList[uuid][currentRow])>
<cfset QuerySetCell(quserList,"BufferNotes","name2",quserList[uuid][currentRow])>
</cfif>
</cfloop>
</cfif>
However, it is giving me an error on the quserList[uuid][currentRow] line that says not indexable by the data:
coldfusion.sql.QueryColumn#276249a2] ] is not indexable by
51840915-e570-430d-9911-7247d076f6e7
If I try it in other way:
quserList.uuid[currentRow]
I still get an error, but it says "cannot convert to int ...". How do I fix it?
Update:
In image 1, I am doing a create column for all the above 1st query product_types into the main query and based upon the userid of 1st query and uuid of second query. I want to insert data in correct location and correct row for the user based upon uuid and userid match. Image 2 is the uuid in the second table:
In both the queries, the userid you see in the first section is common. Meaning that the same usedid exists below that tells us that this user has completed these trainings. Now I want the first query to get merged in second one so it should add correct data to the correct row and that is what messing me up.
SQL:
Query #1:
SELECT ct.trainingid,
ct.userid,
ct.trainingtype,
ct.trainingstatus,
ct.trainingscore,
ct.trainingdate,
dbo.Fn_stripcharacters(ctt.product_type, '^a-z0-9') AS product_type,
ctt.product_type AS oldName
FROM clienttraining AS ct
INNER JOIN clienttraningtypes AS ctt ON ct.trainingtype = ctt.typeid
WHERE 1 = 1
AND userid IN (
'51840915-e570-430d-9911-7247d076f6e7'
, '51927ada-6370-4433-8a06-30d2d076f6e7'
)
AND trainingtype IN (
SELECT typeid
FROM complaincetestlinks
WHERE pid = 1039
AND isactive = 1
AND isdeleted = 0
)
Query 2:
SELECT id,
NAME,
username,
email,
password,
first_name,
last_name,
usertype,
block,
sendemail,
registerdate,
lastvisitdate,
activation,
params,
uuid
FROM users
WHERE uuid IN (
'51840915-e570-430d-9911-7247d076f6e7'
, '51912193-6694-4ca5-94c9-9f31d076f6e7'
, '51927ada-6370-4433-8a06-30d2d076f6e7'
, '51c05ad7-d1d0-4eb6-bc6b-424bd076f6e7'
, 'd047adf1-a6af-891e-94a2d0b225dcd1b6'
, '2aba38f2-d7a7-0a7a-eff2be3440e3b763'
)
Update:
Looking at it again with fresh eyes, it still seems like maybe you are over-complicating things? A simple JOIN should return the information needed, ie All users and the completed training info (if any).
Runnable SQLFiddle
SELECT u.id
, u.first_name
, u.last_name
, ct.trainingid
, ct.userid
, ct.trainingtype
, ct.trainingstatus
, ct.trainingscore
, ct.trainingdate
, ctt.product_type
, ctt.product_type AS oldName
FROM users u
LEFT JOIN clientTraining AS ct ON ct.UserID = u.UUID
LEFT JOIN clientTraningTypes AS ctt ON ct.trainingtype = ctt.typeid
LEFT JOIN (
SELECT typeID
FROM complainceTestLinks
WHERE parent_client_id = 1039
AND isactive = 1
AND isdeleted = 0
) ctl ON ctl.TypeID = ct.trainingType
WHERE u.uuid IN
(
'51840915-e570-430d-9911-7247d076f6e7'
, '51912193-6694-4ca5-94c9-9f31d076f6e7'
, '51927ada-6370-4433-8a06-30d2d076f6e7'
, '51c05ad7-d1d0-4eb6-bc6b-424bd076f6e7'
, 'd047adf1-a6af-891e-94a2d0b225dcd1b6'
, '2aba38f2-d7a7-0a7a-eff2be3440e3b763'
)
ORDER BY last_name, first_name, product_type
;
How you want to present the information, on the front end, is different question. For example, you could use a <cfoutput group="..."> to only display each user's name once, and a list of completed training courses beneath it (see below). If you need more specific advice, please post an example of the desired output.
Smith, John
Course 1
Course 2
Allen, Mark
Course 2
Course 3
...
coldfusion.sql.QueryColumn#276249a2] ] is not indexable by
51840915-e570-430d-9911-7247d076f6e7
That just means you are referencing a column name that does not exist. By omitting the quotes around uuid here quserList[uuid][currentRow], you are actually passing in the variable value as the column name, NOT the literal string "UUID". Obviously the query does not contain a column named "51840915-e570-430d-9911-7247d076f6e7". Hence the error.
it says cannot convert to int
That is pretty self explanatory. You are trying to populate a numeric column with a non-numeric value. Clearly the UUID string, ie "51840915-e570-430d-9911-7247d076f6e7" is not an integer. Either you are using the wrong value or need to change the column type.
It may be related to the fact that your QuerySetCell call is passing in the wrong parameters. The third and fourth parameter should be the "value" and query "row number". However, your code is passing in a hard coded string for "value" and the UUID string instead of a row number
QuerySetCell(quserList,"BUFFEREDRANGENOTES","name",quserList[uuid][currentRow])
That said, technically you do not even need that function. Just use associative array notation to "set" the values, ie <cfset queryName["columnName"][currentRow] = "some value here">
<cfif ListContainsNoCase(lstusers,quserList.uuid[currentRow])>
Nothing to do with the error, but ListContainsNoCase is the wrong function here, as it searches for partial matches. To match whole elements only, use ListFindNoCase.
I'm having difficulty getting my pyodbc inserted hyperlinks to work in my Access 2003 database. It appears to look like a hyperlink but does nothing when clicked on. For it to work, I have to edit it in Access and only then does it recognize that, "oh yeah that is a hyperlink".
import pyodbc
cnxn = pyodbc.connect("DRIVER={Microsoft Access Driver (*.mdb)};DBQ= C:\\Users\\multidata\\Documents\\db1.mdb;")
cur = cnxn.cursor()
#hyperlink is the text file. table1 is hyperlink column in ms access
cur.execute("INSERT INTO test(table1, table2) values ('C:\\Users\\multidata\\Desktop\\MC1\\7-31-14_711_EX_2153.txt ', 'y')")
cnxn.commit()
cnxn.close()
A Hyperlink field in Access is a text field containing a number of "parts" separated by hash marks (#). Those various parts are described in the MSDN article here.
If we want to insert a bare URL or file_path into a Hyperlink field we need to enclose it in hash marks, e.g.
import pyodbc
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb)};'
r'DBQ=C:\Users\Public\a2003test.mdb;'
)
cnxn = pyodbc.connect(conn_str)
crsr = cnxn.cursor()
hyperlink = r'C:\Users\Gord\Desktop\foo.txt'
sql = "UPDATE Table1 SET docLink=? WHERE ID=1"
crsr.execute(sql, ['#'+hyperlink+'#'])
cnxn.commit()
crsr.close()
cnxn.close()
i am using sqlite3 to store data to database. I have created lineedits through which i extract the data and insert it to database. But now the problem is when i run the program,once i click on add data button the above error shown. Please help me where am i going wrong.....Another thing is that if i run the same code in windows platform its runs without any problem, but if in ubuntu 13.4 it is not working..........here is the code:
queryCurs.execute('''CREATE TABLE IF NOT EXISTS PATIENT
(NAME VARCHAR(30) NOT NULL,ID INTEGER PRIMARY KEY,AGE INTEGER NOT NULL,GENDER VARCHAR(10) NOT NULL,EYE_TYPE VARCHAR(20) NOT NULL)''')
self.pName = self.patientEdit.text()
self.pAge = self.ageEdit.text()
self.pGender = self.patientgend.text()
self.pEye_type = self.eyeTypeEdit.text()
queryCurs.execute('''INSERT INTO PATIENT(NAME,AGE,GENDER,EYE_TYPE)
VALUES(?, ?, ?, ?)''',(self.pName,self.pAge,self.pGender,self.pEye_type))
print ('Inserted row')
createDb.commit()
this what i have tried in my code...i get error as
VALUES(?, ?, ?, ?)''',(self.pName,self.pAge,self.pGender,self.pEye_type))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.