SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage.
Sqlite can be used by first creating a connection object that represents the database. The connection can be obtained using “connect” keyword as follows.
Import sqlite3all the datas will be stored in .db file in the directory where the python script in located and the db file will contain the details as given in query which is specified as follows.
db=sqlite3.connect(“data.db”)
def init_db():after creating a connection object we have to create the cursor object to call the execute script command to create the table as specified in the query.
db=sqlite3.connect('image.db')
db.cursor().executescript("""drop table if exists entries;
create table entries(
filename string not null,
imagedata string not null);""")
db.commit()
c.execute('SELECT * FROM stocks WHERE symbol=?', t)we can use “?” placeholder to provide values in python variable to execute script. The reason for using
“?” in order to avoid the program vulnerable the SQL injection attack.To retrieve data after executing a
SELECT statement, you can either treat the cursor as an iterator, call the cursor’s call fetchall() to get a list of the matching rows.
for row in cur.fetchall(): print row[index]
cursor may be a pointer to a row or a list of rows which depends upon the script that is
provided to execute.
Flask....
We use route() decorator to tell Flask what URL should trigger our function. The function is
given a name which is also used to generate URLs for that particular function, and returns
the message we want to display in the user’s browser.@app.route("/h/",methods=['POST'])The code explains the function to execute for the url “/h/” for the method “POST” form the javascript file that runs on browser. The values that are been passed for the post request parameter can be accessed simply
by
request.form['POST PARAMETER']
These values can be stored into database byfname=request.form['f'] imagedata=request.form['parameter'] imagedata=pickle.dumps(imagedata) db=sqlite3.connect('image.db') db.cursor().execute('insert into entries (filename,imagedata) values (?,?)', [fname,imagedata]) db.commit()
'f' and 'parameter' are the request parameters. The pickle is used to convert the data to an equal string representation to store into database and later can be fetched back using pickle.loads(). Commit funtion is called to save the changes that have made to the database.
if __name__=="__main__": init_db() app.debug=True app.run()the init_db function that defined earlier is been called when the program starts to execute.This is done because to setup database before the database operation is executed. If it is not done then the browser will give operational error “not found table named ”....” ”.
No comments:
Post a Comment