I try to update my sqlite database using flask webhook.
It seems commands line work fine if I type manually in the python console but my flask webhook didn't update my SQLite database. It seems the apps fail at the "cursor.execute()" line.
here is my webhook code:
#app.route('/trendanalyser', methods=['POST'])
def trendanalyser():
data = json.loads(request.data)
if data['passphrase'] == config.WEBHOOK_PASSPHRASE:
#Init update variables
tastate = data['TrendAnalyser']
date_format = datetime.today()
date_update = date_format.strftime("%d/%m/%Y %H:%M:%S")
update_data = ((tastate), (date_update))
#Database connection
connection = sqlite3.connect('TAState15min.db')
cursor = connection.cursor()
#Database Update
update_query = """Update TrendAnalyser set state = ?, date = ? where id = 1"""
cursor.execute(update_query, update_data)
connection.commit()
return("Record Updated successfully")
cursor.close()
else:
return {"invalide passphrase"}
Can you please tell me what's wrong with my code ?
if it's can help, here is my database structure (my db creation):
#Database connection
conn = sqlite3.connect("TAState15min.db")
cursor = conn.cursor()
#Create table
sql_query = """ CREATE TABLE TrendAnalyser (
id integer PRIMARY KEY,
state text,
date text
)"""
cursor.execute(sql_query)
#Create empty row with ID at 1
insert_query = """INSERT INTO TrendAnalyser
(id, state, date)
VALUES (1, 'Null', 'Null');"""
cursor.execute(insert_query)
conn.commit()
#Close database connexion
cursor.close()
**I finally found the issue, webhooks need the full path to the SQLite database to work fine. I just start to code in python, it was a noob issue... **
I finally found the issue, webhooks need the full path to the SQLite database to work fine. I just start to code in python, it was a noob issue...
Related
I am trying to just create a temporary table in my SQL database, where I then want to insert data (from a Pandas DataFrame), and via this temporary table insert the data into a 'permanent' table within the database.
So far I have something like
""" Database specific... """
import sqlalchemy
from sqlalchemy.sql import text
dsn = 'dsn-sql-acc'
database = "MY_DATABASE"
connection_str = """
Driver={SQL Server Native Client 11.0};
Server=%s;
Database=%s;
Trusted_Connection=yes;
""" % (dsn,database)
connection_str_url = urllib.quote_plus(connection_str)
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % connection_str_url, encoding='utf8', echo=True)
# Open connection
db_connection = engine.connect()
sql_create_table = text("""
IF OBJECT_ID('[MY_DATABASE].[SCHEMA_1].[TEMP_TABLE]', 'U') IS NOT NULL
DROP TABLE [MY_DATABASE].[SCHEMA_1].[TEMP_TABLE];
CREATE TABLE [MY_DATABASE].[SCHEMA_1].[TEMP_TABLE] (
[Date] Date,
[TYPE_ID] nvarchar(50),
[VALUE] nvarchar(50)
);
""")
db_connection.execute("commit")
db_connection.execute(sql_create_table)
db_connection.close()
The "raw" SQL-snippet within sql_create_table works fine when executed in SQL Server, but when running the above in Python, nothing happens in my database...
What seems to be the issue here?
Later on I would of course want to execute
BULK INSERT [MY_DATABASE].[SCHEMA_1].[TEMP_TABLE]
FROM '//temp_files/temp_file_data.csv'
WITH (FIRSTROW = 2, FIELDTERMINATOR = ',', ROWTERMINATOR='\n');
in Python as well...
Thanks
These statements are out of order:
db_connection.execute("commit")
db_connection.execute(sql_create_table)
Commit after creating your table and your table will persist.
I am inserting a couple thousand records into a table via the python code below:
values = ''
for row in cursor:
values = values + "(" + self.quoted_comma_separate(row) + "),"
values = values[:-1]
insert_statement = "INSERT INTO t1 ({0}) VALUES {1};".format(
self.comma_separate(members), values)
db = Database()
conn = db.get_db()
cursor = conn.cursor()
cursor.execute(insert_statement)
conn.commit()
conn.close()
When I check the database after it runs none of the records show up in the database. If I go into an MySQL editor and manually commit the transaction all of the records appear. Why is my conn.commit() not working?
The insert statements were fine. Turns out I had another database connection open and it was getting confused and committing to the wrong connection or something like that. Sorry for the pointless question :)
This is just a small bite of my code but I hope it will be enough so solve my problem. Allow me to explain first.
So I am attempting to store information in a database using python and sqlite3. I can store stuff in the database but the file size of the database never increases and after a restart the database is cleared. I know that .commit works because I have used it in the past but it is not working now. My assumption is that I am out of scope of the database and I don't have the ability to write. Once again, my code runs and provides no errors, but it will not actually write to the database.
My Connection and Init Code:
def connect_db():
conn = sqlite3.connect(app.config['DATABASE'])
conn.row_factory = sqlite3.Row
return conn
def init_db():
conn = connect_db()
cursor = conn.cursor()
sql = 'create table if not exists users (id integer primary key autoincrement, username text not null, password text not null, admin boolean not null)'
cursor.execute(sql)
conn.commit()
So this code connects to the database and gets everything setup.
Here is a small portion of my code to add an item to the database. It works and it will add items to the "database" but the file size of the database does not increase and if I restart it wont see the new items. But as long as the application is open I have access to the items.
#app.route('/user/', methods=['GET', 'POST'])
def users():
conn = connect_db()
cursor = conn.cursor()
isAdmin = False
if (request.form.get('adminuser') != None):
isAdmin = True
cursor.execute('insert into users (username, password, admin) values (?, ?, ?)',
[request.form['username'], request.form['password'], isAdmin])
conn.commit()
return redirect(url_for('index'))
Edit I left This Out
DATABASE = '/tmp/database.db'
Edit A Crazy Simple Mistake.
Change
DATABASE = '/tmp/database.db'
To
DATABASE = './tmp/database.db'
There is an error in this line:
DATABASE = '/tmp/database.db'
Use this instead:
DATABASE = './tmp/database.db'
I am trying to add all words of a text file into a column such that one row has one word. my code is as :
import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root", db = "pcorpora")
c = conn.cursor()
file = open('C:\Users\Admin\Desktop\english.txt', 'r')
words = list(file.read())
i=0
for value in words:
c.execute("""INSERT INTO tenglish (`english words`) VALUES (%s)""" % (words[i]) i=i+1)`
The code run without error but table is still empty.
You should use commit
c.execute("""INSERT INTO tenglish (`english words`) VALUES (%s)""" % (value))
con.commit()
This method sends a COMMIT statement to the MySQL server, committing
the current transaction. Since by default Connector/Python does not
autocommit, it is important to call this method after every
transaction that modifies data for tables that use transactional
storage engines.
I'm using flask to build a simple web app but for whatever reason the conn.commit() is not committing the data into the database. I know this because when I manually add something to the database the data doesn't change but the ID section increases each time I test it (because its using auto increment). So basically my current table has ID 1, Username test, Password test and the next entry that I inserted manually (after trying to use my application) was ID 5, Username blah, Password blah. Is there any specific reason that the commit isn't working?
EDIT: I had to change cursor = mysql.connect().cursor() to conn.cursor()
#app.route('/add_data/')
def add_tv_to_database():
conn = mysql.connect()
cursor = mysql.connect().cursor()
cursor.execute("INSERT INTO _accounts VALUES (null, 'test','test')")
conn.commit()
return render_template('index.html')
In the fourth line of your code, change it from cursor = mysql.connect().cursor() to cursor = conn.cursor(). This will ensure that the cursor uses the existing connection to database (from the previous line of code), instead of creating a new MySQL connection.