I want to create a table in SQLite with Python where the column names will be stored in a variable.
import sqlite3 as lite<br>
con = lite.connect('MyData.db')
name = raw_input() # I am taking values from user here
id1 = raw_input()
a=con.execute("CREATE TABLE PROD_SA_U_1(
name TEXT,
ids INT")
Instead of the column being named as "name","id" , I want what the user inputs.
You could simply substitute the names the user provides in the query string.
Example:
import sqlite3 as lite
con = lite.connect('MyData.db')
field_1 = raw_input()
field_2 = raw_input()
query = "CREATE TABLE PROD_SA_U_1( %s TEXT, %s INT)"
a = con.execute(query % (field_1, field_2))
However, note that this approach is vulnurable to running incorrect queries if the fields are not validated, so you should sanitise the fields before passing them further. For example, a malicious user might pass a Drop database query within your arguments.
Related
I have created a flask application and using mysql as DB backend and this is used by multiple users simultaneously.
The problem I'm having is,In my homepage a select query is performed and data is displayed to the user but same data is showing to all users.it should be unique. I have tried to lock the row by using FOR UPDATE while selecting the row. I know that I'm not updating the row,so the transaction will be closed when the function ends and the row will be released from lock.
How to overcome this problem?
Expected output: Each user should get different data from the table.(Even when they refresh)
#is_logged_in
#app.route('/')
def index():
conn = mysql.connection
cur = conn.cursor()
cur.execute("select mylist ,myurl ,swatch,parent from image_links where status =%s LIMIT 1 FOR UPDATE",("fetched",))
parent = cur.fetchall()
for row in parent:
mylistitems = row[0].split(",")
swatches = row[2].split(",")
myurlsitems = row[1].split(",")
pid = row[3]
if asinlist != ['']:
merged = tuple(zip(mylistitems ,myurlsitems ,swatches))
return render_template('home.html',firstimage= myurlsitems[0],merged=merged)
else:
cur.execute("UPDATE asin_links SET status = %s WHERE pid= %s", ("invalid",pid,))
conn.commit()
return redirect(url_for('index'))
I can't see any "current user" specific parameters used in your sql query or any data filtering decided on some user ID.
Basically, if you are running the same code, same query for all requests on this endpoint, it will never be really unique. You need to add some user specific checks so you can differentiate the output for the current requesting user.
Depending on your use-case and database models, if the data in the table image_links is also created/inserted by some user action you might want additionally save some user ID alongside these values, eg. by extending the table model with another "user_id" column and on insert also add the id of the current user.
You are using some auth decorator #is_logged_in, if you are already handling users in some table then the another user_id column could be a reference to the respective user's primary key. Then, in your example, you would just add additional where user_id = check with the current user's primary key.
As I see in this SQL query:
SELECT mylist, myurl, swatch, parent FROM image_links WHERE status
perhaps you did specify the related user to get its own specific data, try to replace that last "where" with:
WHERE id = (user.id) --> user object
or you could use the AND keyword, something like
WHERE status = (x) AND id = (y)
I have this current sqlite3 code in my python file:
Data = Cursor.execute("""
SELECT Username, Password
FROM PatientTable
WHERE Username = '{}'
""".format(Username))
Data = Data.fetchall()
There are multiple tables in the database: PatientTable, DoctorTable, ManagerTable. Each one has attributes of Username and Password in the second and third column respectively.
Q: My current code only selects data from PatientTable but I need to select data from all three tables and identify which table each item of data came from.
Now, I think I can do this using multiple SQL statements but this seems excessive. I have thought about using JOIN but there are no foreign keys - keys relating the databases to each other.
Thanks in advance.
You seem to be looking for UNION. You can add a fixed column to each query to distinguish from which table each record in the resultset comes from :
SELECT 'PatientTable' source_table, Username, Password
FROM PatientTable
WHERE Username = '{}'
UNION ALL SELECT 'DoctorTable' , Username, Password
FROM DoctorTable
WHERE Username = '{}'
UNION ALL SELECT 'ManagerTable', Username, Password
FROM ManagerTable
WHERE Username = '{}'
I am importing a CSV file to postgres and there is no unique column in the dataset. I want to add a serial ID field to uniquely identify each record as its inserted into the table.
I have created a sequence and added an ID field to the table structure before triggering the import:
CREATE SEQUENCE IF NOT EXISTS serial;
CREATE TABLE my_tbl (
fname varchar(100),
lname varchar(100),
company varchar(200),
id integer PRIMARY KEY DEFAULT nextval('serial')
);
I run this code to import the CSV which has data for fname, lname and company:
conn = psycopg2.connect(dbname=dbname, host=host, port=port, user=user, password=pwd)
cur = conn.cursor()
cur.copy_expert("copy {} from STDIN CSV HEADER QUOTE '\"'".format(table_name), file)
cur.execute("commit;")
However, I get an error saying I'm missing data for field "id". I assume under the hood psycopg2 is matching the schemas of the CSV and PG table to validate the COPY before it attempts the insert. A regular insert would succeed as the id field would be populated with a value from the SEQ.
How can I add a unique id field to each record that's copied from the CSV to the PG table?
You have two options. You can specify columns of the target table in the COPY command, e.g.:
COPY my_tbl(fname, lname, company) FROM STDIN CSV HEADER QUOTE '"'
Alternatively, create the table without the id primary key, import the csv data and only then add the primary key:
ALTER TABLE my_tbl ADD id serial PRIMARY KEY;
Not related. You do not have to create a sequence for a serial column, let Postgres do this for you:
CREATE TABLE my_tbl (
fname varchar(100),
lname varchar(100),
company varchar(200),
id serial PRIMARY KEY
);
Then the system knows the relationship between the table and the sequence. (Also, serial is not the best name for a sequence, how do you name the next one when you need it?)
My constrains method not working for id_number. can't figure it out why.
from odoo import models, fields, api
from odoo.exceptions import ValidationError
class KindeGarden(models.Model):
_inherits = {'res.partner': 'partner_id'}
_name = 'kindergarten.model'
_description = 'Kindergarten'
age = fields.Integer(string="Amžius", required=False, default="1")
group = fields.Char(string="Grupė", compute="_compute_group", store=True)
height = fields.Float(string="Ūgis", required=False)
weight = fields.Float(string="Svoris", required=False)
id_number = fields.Integer(string="Registravimo Nr", required=True)
#api.constrains('id_number')
def _check_id_number_field(self):
for i in self:
if i.id_number < 10:
raise ValidationError("Number is to small")
and i'm also having this
WARNING -Kindegarden odoo.models.schema: Table 'kindergarten_model': unable to set a NOT NULL constraint on column 'id_number' !
If you want to have it, you should update the records and execute manually:
ALTER TABLE kindergarten_model ALTER COLUMN id_number SET NOT NULL
Like mentioned above, it looks like it is some data are null already before you set required parameter to true.
odoo has a shell you can use to access your DB if you are not familiar with SQL.
odoo-bin -d <database_name> shell
inside the shell, do as follow so you will see.
>> records = env['kindergarten.model'].search([('id_number','=',False)])
>> len(records)
if it returns a number aside from 0, it means that those are NULL value. so do like.
>> for record in records:
record.write({'id_number': 0.0})
>>env.cr.commit()
Then update your module again.
If this doesn't work you will need to do it manually with SQL.
Did you add constraint after few records were added ?
The error you got generally comes when postgres is unable to set "NOT NULL" to the column because it already has null values
I want to do a Django Python MySQL query with WHERE (in sql) being a link generated from a previous query.
Hereby I paste my actual code:
def population(request):
db = MySQLdb.connect(user='xxxx', db='xxxxdb', passwd='xxxxpwd', host='localhost')
cursor = db.cursor()
cursor.execute("SELECT last_name FROM a_population WHERE country='Denmark' ORDER BY last_name")
denominazione_comune = cursor.fetchall();
rows_count = cursor.rowcount
db.close()
counter = 0
return render_to_response('list_last_name.html', {'lastname': last_name}, context_instance=RequestContext(request))
So from this code I get an (un)ordered list of family names. By clicking one of these family names I would like to create another query with the family name clicked as a parameter but I don't have a clue of how to do that.
Thanks a million to whom will give me some input.