I am creating a table to add data to a database but I am not sure where to create the column for 'emails'. My final aim for this is to be able to enter a username (email) and password and for it to be saved into a database but I am not sure how to do this. Here is my code currently:
import sqlite3
def save_to_database(my_stack, filename = 'stack_database.db'):
conn = sqlite3.connect(filename)
c = conn.cursor()
for row in c.execute('SELECT email FROM sqlite_master WHERE type="table"'):
if row != None:
c.execute("DROP TABLE emails")
c.execute("CREATE TABLE emails(email text,login_date text)")
...
The sqlite_master table does not have a column named email; the entire table structure is contained in the text in the sql column.
You could check for the table name itself (but note that if no row is found, no row is returned, not even an empty one, so it does not make sense to try to handle this with a for loop):
c.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'emails'")
if not c.fetchall():
c.execute('DROP TABLE emails')
However, there is an easier method to ensure that a table is removed, regardless of its previous state:
c.execute('DROP TABLE IF EXISTS emails')
Related
I have a SQLite table that I wanted to update. This table ('abc') already has a row inserted through some other process for id and useremail. Now, I want my query to lookup this record based on where condition (on useremail) and update the value of column logintime. I am pretty new to Sqlite so need some help in figuring it out. Code below -
creating a new table (works OK)
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS abc (
id INTEGER PRIMARY KEY,
useremail TEXT,
logintime TEXT,
logouttime TEXT
);
""")
conn.commit()
conn.close()
code for inserting a record (works OK)
email = ['jojo#jojo.com']
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
c.execute('insert into abc (useremail) values(?)', email)
code for updating column logintime where value in column useremail = email:
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
now = datetime.now()
c.execute('UPDATE abc SET logintime = ? WHERE useremail = ?', (now, email))
I am having trouble with this c.execute statement.
I am trying to clean raw json data by parsing and inserting it into a table of an sqlite db.
I have 22 columns in my table and want to find a way of looping through them so I don't need to write 22 loops which insert the data or a single column.
I have simplified the approach I am trying with the following:
import sqlite3
conn = sqlite3.connect('cdata.sqlite')
cur = conn.cursor()
column = 'name'
value = 'test'
cur.execute('''INSERT INTO COMPANY (?)
VALUES (?)''',(column,),(value,))
conn.commit()
conn.close()
This doesn't work at the moment and return the error TypeError: function takes at most 2 arguments (3 given).
Does anyone know if it is possible to write an SQLite insert statement using 2 parameters like this or another way I might be able to iterate through the columns?
Sample as below:
import sqlite3
conn = sqlite3.connect("cdata.sqlite")
cur = conn.cursor()
column = ("name", "age")
table = f"CREATE TABLE IF NOT EXISTS COMPANY ({column[0]} text, {column[1]} text);"
cur.execute(table)
name = "hello"
age = "1"
sql_stmt = f"INSERT INTO COMPANY({column[0]},{column[1]}) VALUES ('{name}', '{age}')"
cur.execute(sql_stmt)
with conn:
cur.execute("SELECT * FROM COMPANY")
print(cur.fetchall())
conn.commit()
conn.close()
i want to ask for a little help about my problem. I have sql query that get all the tables from some schema and put those tables in a list in Python. For example:
tablesList = ['TABLE1','TABLE2',...]
After i get this list of tables that i want i go one more time through each table in a for loop for example:
for t in range(len(tables)):
table = tables[t]
...
#here i want to check if this table exist in some db2 schema and if exist delete content
#of this table, otherwise go with next table check and don't delete content
Query for checking will be:
sql = """SELECT COUNT(*) FROM SYSIBM.SYSTABLES
WHERE TYPE = 'T'
AND CREATOR = 'MY_SCHEMA'
AND NAME = '{table}';""".format(table = table)
cursor.execute(sql)
rows_count = cursor.fetchone()
if rows_count is None:
pass
else:
delete...
I am new to psycopg2. I have to insert data into the table with no duplicates. So, first I created a temporary table where I dumped all the data. And then, I check and add the data to the actual table.
Here is the code till now:
for eachline in content:
pmid ,first_name, last_name,initial,article_title,journal,language = eachline.split("\t")
cur.execute ("INSERT INTO AUTHOR_PMID(pmid, Author_lastname, Author_firstname, Author_initial,Article_title)
SELECT DISTINCT (pmid, Author_lastname, Author_firstname, Author_initial,Article_title)
FROM AUTHOR_PMID WHERE NOT EXISTS (SELECT "X" FROM AUTHOR_pmid_temp
WHERE
AUTHOR_pmid_temp.pmid = AUTHOR_PMID.pmid
AND AUTHOR_pmid_temp.Author_lastname = AUTHOR_PMID.Author_lastname
AND AUTHOR_pmid_temp.Author_firstname = AUTHOR_PMID.Author_firstname
AND AUTHOR_pmid_temp.Author_initial = AUTHOR_PMID.Author_initial
AND AUTHOR_pmid_temp.Article_title = AUTHOR_PMID.Article_title);")
con.commit()
error: syntax error.
Where am i going wrong?
Try inserting query with triple quotes instead of single like below
for eachline in content:
pmid ,first_name, last_name,initial,article_title,journal,language = eachline.split("\t")
cur.execute ("""INSERT INTO AUTHOR_PMID(pmid, Author_lastname, Author_firstname, Author_initial,Article_title)
SELECT DISTINCT (pmid, Author_lastname, Author_firstname, Author_initial,Article_title)
FROM AUTHOR_PMID WHERE NOT EXISTS (SELECT "X" FROM AUTHOR_pmid_temp
WHERE
AUTHOR_pmid_temp.pmid = AUTHOR_PMID.pmid
AND AUTHOR_pmid_temp.Author_lastname = AUTHOR_PMID.Author_lastname
AND AUTHOR_pmid_temp.Author_firstname = AUTHOR_PMID.Author_firstname
AND AUTHOR_pmid_temp.Author_initial = AUTHOR_PMID.Author_initial
AND AUTHOR_pmid_temp.Article_title = AUTHOR_PMID.Article_title);""")
con.commit()
For more info, please check here !!!
I am using python to copy one table (dictionary) to another (origin_dictionary) in SQLite, and here is my code to this part:
def copyDictionaryToOrigin(self):
dropTableQueryStr = "DROP TABLE IF EXISTS origin_dictionary"
createTableQueryStr = "CREATE TABLE origin_dictionary (id INTEGER PRIMARY KEY AUTOINCREMENT, word TEXT, type TEXT)"
syncTableQueryStr = "INSERT INTO origin_dictionary (word, type) SELECT word, type FROM dictionary"
self.cur.execute(dropTableQueryStr)
self.cur.fetchone()
self.cur.execute(createTableQueryStr)
result = self.cur.fetchone()
self.cur.execute(syncTableQueryStr)
result = self.cur.fetchone()
With running this code, I can see a origin_dictionary table is created, but there is no data in the table. I could not find out the reason why the data didn't copy over to the new table. can someone please help me with this?
If you need to simply copy one table to another, why don't you use CREATE TABLE ... AS SELECT? Also, you need to commit() your statements.
Simply use code below, and it should work:
import sqlite3
conn = sqlite3.connect(example.db")
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS origin_dictionary")
cur.execute("CREATE TABLE origin_dictionary AS SELECT * FROM dictionary")
conn.commit()
conn.close()