Can't insert more than two data's in the mysql database i'm running the code in python using raspberry pi.
the code i used is
query="INSERT INTO import(customer,package) VALUES('%s','%s')"
cursor.execute(query,(name,data))
it gives an error to check the syntax.
You also need to add connection.commit() after your insert/update queries.
Example
connection = MySQLdb.connect(*data)
cursor = connection.cursor()
cursor.execute(<query>)
connection.commit()
When using parameters, you should not quote your parameters. That is, your query should be;
query="INSERT INTO import(customer,package) VALUES(%s, %s)"
Related
I'm working in a Jupyter Notebook and using pymysql. I can read off that database, so the connection must be established, but I can't send any INSERT statements.
connection = pymysql.connect(endpoint, user, passwd, db)
insert = [('Popowice',363000),('Wroclaw',389991),('Biskupin',359000)]
sql = "INSERT INTO housing_wroclaw (`District`, `Price`) VALUES (%s, %s)"
cursor = connection.cursor()
cursor.executemany(sql,insert)
This piece of code with my credentials returns 3 - the number of insert tuples and no errors. But the database just doesn't have those records. I tried also looping through values using execute() rather than executemany(), but neither worked and the latter is apparently better.
Below is my working SELECT statement:
cursor = connection.cursor()
cursor.execute('SELECT * from housing_wroclaw')
rows = cursor.fetchall()
How can I INSERT? Why it doesn't work?
You must call connection.commit() after inserting data to make it persistent.
I'm trying to insert variables as data into a database
I'm using this (part of it)
query = "INSERT INTO table_name (name) VALUES (%S)"
aa="naam"
cursor.execute(query,aa)
and everytime, I get the following error message:
"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 '%S)' at line 1"
no matter what I try to do, I'm getting this message (put it in """, put () around it, ...)
Hope someone can help me
The format needs to be lowercase, so change the query into: query = "INSERT INTO table_name (name) VALUES (%s)".
Similar to Brunonono in Create MySQL Database in Python using the %s operator (even using the same packages) I'm trying to add columns from an excel table to a mysql table using the %s operator in Python. The error is the same:
mysql.connector.errors.ProgrammingError: 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 '%s %s)' at line 1
The code is as follows
mydb=mysql.connector.connect(host="localhost",user="root")
#init cursor
mycursor=mydb.cursor()
column_title="ID"
cell_type="INT(10)"
mycursor.execute("ALTER TABLE Test ADD (%s %s)"),(column_title, cell_type)
Sadly, I wouldn't know how to apply the solution provided in the post above, where
mycursor.execute("CREATE DATABASE (%s)", (db_name))
was replaced with
create_statement = "CREATE DATABASE {:s}".format(db_name)
mycursor.execute(create_statement)
mycursor.execute("ALTER TABLE Test ADD (%s %s)"),(column_title, cell_type) is what you are doing currently
Instead do,
mycursor.execute("ALTER TABLE Test ADD (%s %s)" % (column_title, cell_type))
Which would work unless I don't know MySQL syntax properly
Try this:
mycursor.execute('ALTER TABLE Test ADD (?, ?)',(column_title, cell_type))
But this doesn't use the %s operator.
Sorry, this works for SQLite and not MySQL.
I am confused while inserting data to my Postgres Database in heroku.
Here's the thing,
I have created connection to database, then
cursor = conn.cursor()
cursor.execute("INSERT INTO users(username, useremail, userpass) VALUES ('"+_name+"','"+_email+"','"+_password+"')")
After executing, I checked the sql status by
print(cursor.statusmessage)
it returns,
INSERT 0 1
but on executing, data =
cursor.fetchall()
it throws me error
File "/Users/abc/PycharmProjects/testSkillNetwork/app.py",
line 75, in signUp
data = cursor.fetchall().
ProgrammingError: no results to fetch
So, i am unable to understand why 'no results' when insertion is successful.
Any help will be appreciated. Thanks.
You need to issue a SELECT query in order to retrieve data from the database.
cursor.execute("SELECT * FROM users")
cursor.fetchall()
This should give you some results.
Also, you should commit the transaction once you have finished inserting data, otherwise it will be lost. Use:
conn.commit()
Another, bigger, issue is that the way that you construct your queries is vulnerable to SQL injection. Rather than using string concatenation you should use parameterised queries:
cursor.execute("INSERT INTO users(username, useremail, userpass) VALUES (%s, %s, %s)", (_name,_email,_password))
With this style the database adapter will substitute the place holders (%s) with the values from the tuple of arguments passed to cursor.execute(). Not only is this safer, it's a lot easier to read and maintain.
I am not sure what driver are you using to connect to the database, assuming you're using psycopg2, which is one of the most famous, what you're observing is a normal behaviour. Reading from here:
A ProgrammingError is raised if the previous call to execute*() did not produce any result set or no call was issued yet.
An insert statement produces no result, other that an error in case of failure. If you want to obtain the rows that you've just inserted, query the database again:
cur.execute("SELECT * FROM users;")
cur.fetchall()
and this will give you the rows.
Aside from this, if you read the basic usage and the section of parametrized queries, never use python string concatenation when executing your queries, because it makes it vulnerable to SQL injection attacks.
I am using python 2.7 and MySQL as database. In my python program have an INSERT query like this:
cursor.execute("insert into login(username,passw)values('"+i.username+"','"+i.password+"')")
result=cursor.execute("select * from login")
print cursor.fetchall()
When I check in the database, there is no entry. But after the select in my python code, when I print the results it is showing the inserted data. I am not using any transaction statement either.
You need to commit your transaction for the database to make your insert permanent, and you need to use SQL parameters to prevent SQL injection attacks and general quoting bugs:
cursor.execute("insert into login (username, passw) values (%s, %s)", (i.username, i.password))
connection.commit()
Until you commit, the data you inserted will only be visible to your python program; if you do not commit at all, then the changes will be discarded again by the database.
Alternatively, you could switch on auto-commit mode:
connection.autocommit()
After switching on auto-commit, your insertions will be committed instantly. Be careful with this as this could lead to inconsistent data if you need to insert data into multiple rows and / or tables that is interdependent.
You also need to commit the data after your execution statement. It is important to call this method after you are done inserting, or updating data, as the Python connector does not auto commit by default.
# Execute & Commit
cursor.execute("insert into login(username,passw) values('%s','%s')",
i.username, i.password)
# Commit the insert query!
conn.commit()
# Fetch Result
result=cursor.execute("select * from login")
print cursor.fetchall()
If you use mysql-python, you can set connection options to enable autocommit feature.
conn = mysql.connection(host, port, autocommit=True)
# or
conn = mysql.connection(host, port)
conn.autocommit(True)
You can see more details here