Unable to see table after creation in Flask-sqlalchemy [duplicate] - python

When I make a MySQL table order, it is created successfully but, when I execute any query against it, it says "error 1064 , syntax error".
When I change the name to orders, it works fine.
But I don't want to change the name. How can I execute our query against the order table?

can you use something like?
select * from `order`

The word order is actually an SQL keyword. You would have the same problem if you tried to use a table called group or select. You can fix it is MySQL by using quotes around it, along the lines of:
select f1, f2 from `order` where blah blah blah ...
However, unless your table will only ever hold a single order (in which case it won't do so for long since the underlying business will soon be bankrupt), you should probably call your table orders.
That solves both your problems, the one you found and the one you didn't :-)

I got here because I was searching for similar solution for SQL CE. There using
order
'order'
"order"
doesn't work.
What worked was:
[order]
Maybe it'll help someone else also.

This should fix the problem:
e.g
mysql>
Create table order(
ID char(5),
QTY(3)
)
;

Related

How to insert user variable into an SQL Update/Select statement using python [duplicate]

This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 2 months ago.
def update_inv_quant():
new_quant = int(input("Enter the updated quantity in stock: "))
Hello! I'm wondering how to insert a user variable into an sql statement so that a record is updated to said variable. Also, it'd be really helpful if you could also help me figure out how to print records of the database into the actual python console. Thank you!
I tried doing soemthing like ("INSERT INTO Inv(ItemName) Value {user_iname)") but i'm not surprised it didnt work
It would have been more helpful if you specified an actual database.
First method (Bad)
The usual way (which is highly discouraged as Graybeard said in the comments) is using python's f-string. You can google what it is and how to use it more in-depth.
but basically, say you have two variables user_id = 1 and user_name = 'fish', f-string turns something like f"INSERT INTO mytable(id, name) values({user_id},'{user_name}')" into the string INSERT INTO mytable(id,name) values(1,'fish').
As we mentioned before, this causes something called SQL injection. There are many good youtube videos that demonstrate what that is and why it's dangerous.
Second method
The second method is dependent on what database you are using. For example, in Psycopg2 (Driver for PostgreSQL database), the cursor.execute method uses the following syntax to pass variables cur.execute('SELECT id FROM users WHERE cookie_id = %s',(cookieid,)), notice that the variables are passed in a tuple as a second argument.
All databases use similar methods, with minor differences. For example, I believe SQLite3 uses ? instead of psycopg2's %s. That's why I said that specifying the actual database would have been more helpful.
Fetching records
I am most familiar with PostgreSQL and psycopg2, so you will have to read the docs of your database of choice.
To fetch records, you send the query with cursor.execute() like we said before, and then call cursor.fetchone() which returns a single row, or cursor.fetchall() which returns all rows in an iterable that you can directly print.
Execute didn't update the database?
Statements executing from drivers are transactional, which is a whole topic by itself that I am sure will find people on the internet who can explain it better than I can. To keep things short, for the statement to physically change the database, you call connection.commit() after cursor.execute()
So finally to answer both of your questions, read the documentation of the database's driver and look for the execute method.
This is what I do (which is for sqlite3 and would be similar for other SQL type databases):
Assuming that you have connected to the database and the table exists (otherwise you need to create the table). For the purpose of the example, i have used a table called trades.
new_quant = 1000
# insert one record (row)
command = f"""INSERT INTO trades VALUES (
'some_ticker', {new_quant}, other_values, ...
) """
cur.execute(command)
con.commit()
print('trade inserted !!')
You can then wrap the above into your function accordingly.

Django filter has_key generates wrong SQL

I need to filter some objects that have no specific value in the field. I tried to do it like this:
MyModel.objects\
.filter(<some filters>)\
.exclude(json_field__has_key='some_field', json_field__some_field=True)
But this code generates wrong SQL query:
...
AND NOT (
"my_model"."json_field" ? some_field AND
("my_model"."json_field" -> 'some_field') = 'true' AND
"my_model"."json_field" IS NOT NULL)
)
...
On the first line some_field used without qoutes. I fixed it by adding single qoutes to the string like this: json_field__has_key="'some_field'" but I dont think it's a good solution.
Does anyone have an idea why it works this way and how I should fix it?
Well, my bad...
I just logged my queries as queryset.query that has really wrong representation of the SQL query. When I logged real queries using connector I saw correct query (see this answer for more details).

Python mysql.connector insert does not work

I work with the Python mysql.connector for the first time and I am not able to create a working insert statement.
This is the table:
'CREATE TABLE IF NOT EXISTS products (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255));'
I am trying to insert a variable as title while the id should be auto incremented. I have tried multiple solutions but it simply won't work.
def insert_product(title: str):
insert_product_query = 'INSERT INTO products (title) VALUES (%s);'
cursor.execute(insert_product_query, (title,))
This runs without any error, but the insert is not working. It does nothing. I tried multiple versions of this, with '?' instead of '%s' and without a tuple but it won't work.
Another solution I tried is this:
def insert_product(title: str):
insert_product_query = f'INSERT INTO products (title) VALUES (\'{title}\')'
print(insert_product_query)
cursor.execute(insert_product_query)
I printed the insert statement and when I copy paste it directly into the database it works perfectly, so I don't have any idea why it is not working out of the python code as it is not producing any errors.
I found many similar problems but none of the solution worked for me.
I hope someone can help me as I might overlook something obvious.
Thanks in advance!
Python's connector disables autocommit by default (as a reasonable library would do!). You need to explicitly commit after you perform a DML statement:
con.commit() # Assuming con is the name of the connection variable

Entering data into specific field using "WHERE" in "INSERT" command in SQL? (Python)

I'm currently writing a program for a parents evening system. I have two tables, a bookings table and a teacher table - set up with the following column headings: TeacherSubject | 15:30 | 15:35 | 15:40 etc... When people make a booking, they select a teacher from a drop-down menu and also a time. Therefore, I need the bookingID added into the booking table where the teacher selected = to the same teacher in the table and where time selected = time in the database.
At the moment, my code only attempts to match the teacher, but this doesn't work as I'm getting the error of: (line 5)
TypeError: 'str' object is not callable
Am I doing the whole thing wrong and is this actually possible with the way I have set the table up?
def insert(parent_name, parent_email, student_name,student_form,teacher,app_time,comments):
conn=sqlite3.connect("parentsevening.db")
cur=conn.cursor()
cur.execute("INSERT INTO bookings VALUES (NULL,?,?,?,?,?,?,?)",(parent_name,parent_email,student_name,student_form,teacher,app_time,comments))
cur.execute("INSERT INTO teachers VALUES (?) WHERE teachers = (?)" (id,teacherName,))
conn.commit()
conn.close()
This SQL Query is invalid.
INSERT INTO teachers VALUES (?) WHERE teachers = (?)
It should be
INSERT INTO teachers (id, name) VALUES(?, ?)
Note that I'm guessing the teachers columns (id, name) WHERE on the insert isn't valid because it's used to find data (SELECT, UPDATE, DELETE)
OK, let's take out the comments and make this into an answer.
Python error
I think your error comes from WHERE teachers = (?) have you tried WHERE teachers = ? instead.
But...
bad sql syntax
Also that command as a whole doesnt make much sense, SQL syntax wise - you seem to be trying to insert where a teacher that doesn't exist (if you are inserting them) and values on an insert does not go with where and where needs a from. i.e. once you've solved your python error, sqlite is going to have a fit as well.
That's already covered by another answer.
But...
probably not what you should be doing
If you have an existing teacher, you only need to insert their teacherid into table bookings. You don't have to, and in fact, you can't insert into table teachers at this point, you'd get a duplicate data error.
So, rather than fixing your second query, just get rid of it entirely.
If you can get a command line or GUI SQL tool up, try running these queries by hardcoding them by hand before coding them in Python. the sqlite command should be able to do that for you.
(recommendation) don't use insert table values
Try being explicit with insert into table (<column list>) values .... The reason is that, as soon as the table changes in some way that affects column order (possibly an alter column) the values won't line up with the implied insert list. hard to debug, hard to know what was intended at time of writing. Been there, done that. And had to debug buncha folks' code who took this shortcut, it's never fun

Creating single query with subquery, essentially a insert query with select query

I've created a login function with flask, it consists of a code that opens a connection to the database then selecting a username based on the inputed username. To be more precise, here's the query:
cursor.execute("""
SELECT username FROM user_tbl
WHERE username = %s""",
(self.username))
After that, I check the length of the fetched data, if length is 0 then I open up another connection then perform an insert query, like so:
cursor.execute("""
INSERT INTO
user_tbl(username,password,email,user_type)
VALUES(%s,%s,%s,%s)""",
(self.username,self.password,self.email,self.user_type))
I've been doing this process since coding with PHP and would like to confirm if there is any way to combine these two queries. I've been researching like crazy and can't seem to find the answer... or atleast answers that work.
MySQL direct INSERT INTO with WHERE clause based on the accepted answer there, INSERT INTO...SELECT is the way to go, however after looking into it its mostly about transferring data from another table to another, I am targeting one table (my apologies if I'm missing something ).
I can't find the link, however I found another answer that mentioned that the only time you'll see a WHERE clause in an INSERT query(aside from the answer I posted above) is when you're checking if nothing 'EXISTS' (which makes sense and based on that answer I made the conclusion that having a where clause in an insert query is ok).
After checking up subquerying on a WHERE clause and following examples in this link: https://www.essentialsql.com/get-ready-to-learn-sql-server-21-using-subqueries-in-the-where-clause/ I've created my own query:
INSERT INTO user_tbl(username,password,email,user_type)
VALUES("test.test","test","test","test")
WHERE username IN
(SELECT username FROM user_tbl WHERE username="test.test");
Reason why I chose IN is because, as mentioned in the link, once a subquery returns NULL, IN returns false for the WHERE clause (at least that's how I interpreted it).
Unfortunately, each time I run this code on my terminal I get this syntax error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE username IN (SELECT username FROM user_tbl WHERE username="test.test")'
Hence the title, Can you guys please explain how exactly is my code syntactically wrong? Also, can you perchance pinpoint me to the right direction as I am very lost on this.
Thanks in advance,
Inno
I understand that you want to INSERT a new record in user_tbl only if it does not yet exist.
MysQL has a special syntax for that, called INSERT ... ON DUPLICATE KEY UPDATE.
For this to work, you need column username to be the primary key in your table (or to have a UNIQUE constraint).
Then you can simply do:
cursor.execute(
"""
INSERT INTO user_tbl(username,password,email,user_type)
VALUES(%s,%s,%s,%s)
ON DUPLICATE KEY UPDATE username = VALUES(username)
""",
(self.username,self.password,self.email,self.user_type)
)
If no record aleady exists for the given username, a new record is created. Else, the UPDATE clause is invoked (here, that would simply reassign the same value to the username , which is basically a no-op).
you cant use the same table, but you can "hide" the SELECT then MySQL did not see this like:
INSERT INTO user_tbl(username,password,email,user_type)
VALUES("test.test","test","test","test")
WHERE username IN
(SELECT * FROM (
SELECT username FROM user_tbl WHERE username="test.test"
) as myuser
);

Categories