Can I insert data in column right after reading another column? - python

current state
table name: mytable
before after
I am a boy.
I am a girl.
expected state
table name: mytable
before after
I am a boy. I/Pronoun+am/verb+a/adjective+boy/noun+./mark.
I am a girl. I/Pronoun+am/verb+a/adjective+girl/noun+./mark
to get data which will be inserted in 'after' column,
i have to use function outside sql query,
like analysis("I am a boy") which returns "I/Pronoun+am/verb+a/adjective+boy/noun+./mark".
I just got how to use conn.cursor() on conn=sqlite3.connect('database.db')
or
method like this link:
inserting added column values in another column
but i want to read a column -> insert it as parameter on python function -> insert it into adjacent column.
Thank you for your help.

you need UDF(User Define Function) of SQLite
first, you make(write/define) your own function itself
register(declare) it, just like;
https://www.sqlite.org/c3ref/create_function.html
and finally, use(call) it in your Column adding query.
Could be VERY hard job to do.
Good Luck To You (포스가 함께 하시기를...)

Related

Add table columns to select without adding it to select_from

I have a prepared function in the database, which I want to call using Gino. This function has a return type equal to one of the tables, that is created using declarative. What I try to do is:
select(MyModel).select_from(func.my_function);
The problem is, that SQLAlchemy automatically detects the table in my select and adds it implicitly to select_from. The resulting SQL contains both my function and the table name in the FROM clause and the result is a cartesian of the function result and the whole table (not what I want really).
My question is – can I somehow specify that I want to select all the columns for a model without having the corresponding class in the FROM?
You have to specify the columns (as an array) if you don't want SA to automatically add MyModel to the FROM clause.
You have to either do this:
select([your_model_table.c.column1, your_model_table.c.column2]).select_from(func.my_function);
Your if you want all columns:
select(your_model_table.columns).select_from(func.my_function);

Update a row with a specific id

id is the first column of my Sqlite table.
row is a list or tuple with the updated content, with the columns in the same order than in the database.
How can I do an update command with:
c.execute('update mytable set * = ? where id = ?', row)
without hardcoding all the column names? (I'm in prototyping phase, and this is often subject to change, that's why I don't want to hardcode the column names now).
Obviously * = ? is probably incorrect, how to modify this?
Also, having where id = ? at the end of the query should expect having id as the last element of row, however, it's the first element of row (because, still, row elements use the same column order as the database itself, and id is first column).
You could extract the column names using the table_info PRAGMA. this will have the column names in order. You could then build the statement in parts and finally combine them.
e.g. for a table defined with :-
CREATE TABLE "DATA" ("idx" TEXT,"status" INTEGER,"unit_val" TEXT DEFAULT (null) );
Then
PRAGMA table_info (data);
returns :-
i.e. you want to extract the name column.
You may be interested in - PRAGMA Statements
An alternative approach would be to extract the create sql from sqlite_master. However that would require more complex code to extract the column names.

Variable column name in SQL lite and Python

my question is, as the title says, how I can create a variable column in SQL lite used in Pyhton.
Here's my code, to show you what exactly I mean:
#Table with variables
def dynamic_data_entry(list_name, num, column):
element_name = list_name[num]
cur.execute("INSERT INTO myliltable (column) VALUES (?)", element_name)
con.commit()
I want to insert the column name, when I call the function, so I can use the function for more than one column, but I keep getting an error, that the column 'column' doesn't exist.
Is there another way to do this, so I can change set the column name when I call the function, or just change the SQL part.
If there is a thread about this already, I would appreciate it, if you could link it, so I can read it myself (I couldn't find anything similar to this topic yet, which worked).
Thanks in advance, I appreciate your help
You need to use the string's format() method to insert the column name into the SQL string:
cur.execute("INSERT INTO myliltable ({}) VALUES (?)".format(column),
element_name)
You can find more information in the Python docs.

Python psycopg2 multiple columns in INSERT query

I want to execute an INSERT query via psycopg2, for this question let's simplify it to just:
query = """ INSERT INTO %s("%s") VALUES(%s); """
This works just fine when I do:
params = [AsIs(table_name), AsIs(column_name), value]
cursor.execute(query, params)
Now, my Pandas dataframe has about 90+ columns, I want to know what the best way to extend the query above to be able to execute it for multiple columns.
I have tried joining every column and value together as a single string and passing that in. I have also tried creating a string with 90+ "\"%s\"" and I have also tried creating a format string ie. """INSERT INTO {0} ({1}...{n}) VALUES ({n+1...n+n})""".format(...). There are unrelated issues that prevent these from working, but is there an easier way to handle this multiple column case?
I'm not familiar with pandas but you probably want something like this:
columns = ', '.join(column_names) # Where column names is a tuple or list of all the column headings you want in your query.
query = """ INSERT INTO %s("%s") VALUES(%%s); """ % (table_name, columns)
params = [value]
cursor.execute(query, params)
The point is that you need to insert the column headings and the values separately. See this post for a much better explanation than what I can provide:
Psycopg2 Insert Into Table with Placeholders

Search through SQL table and delete row if cell already exists

I have a table using SQL Lite with Python. The size of the table always has 3 columns and could have many rows. Each of the cells are strings. Here is example table:
serial_num date_measured status
1234A 1-1-2015 passed
4321B 6-21-2015 failed
1423C 12-25-2015 passed
......
My program prompts me for a serial number. This is saved as a variable called serialNum. How can I delete (or overwrite) an entire row if serialNum equals any of the strings in the serial_num column in my table?
I've seen many examples on how to delete (or overwrite) a row in a table if I know all the values in each cell of that row, but my trouble is that the only cell that could ever be the same in each row would be the serial number. I need to so a search through the serial_number column and if any string in that column equals the current value of my serialNum variable, I need to delete (or overwrite) that row.
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE test (serial_num text, date_measured text, status text)''')
c.execute("INSERT INTO test VALUES ('1234A', '1-1-2015', 'passed')")
c.execute("INSERT INTO test VALUES ('4321B', '6-21-2015', 'failed')")
c.execute("INSERT INTO test VALUES ('1423C', '12-25-2015', 'passed')")
conn.commit()
Does anyone know a simple way to do this? I've seen others say that an ID must be used or a temporary table, but I would hope there might be an easier way to accomplish my task. Any advice would be great.
SQL suports this: simply use delete
"delete from test where serial_num=<some input>;"
or in this case
c.execute("delete from test where serial_num=%s;", serialNum);
There's no need to search through the list when using SQL. SQL is declarative: you tell it what to do using your query, not how to do it. Don't loop though all your rows to check which to delete: tell it what to delete and the database engine will find the best/fastest way to satisfy that goal.
Hope I well interpreted your question
for row in c.execute('SELECT * FROM test WHERE serial_num = ?', serialNum'):
# do whatever you want on row
print row
I was able to figure out a working solution:
sql = "DELETE FROM test WHERE serial_num = ?"
c.execute(sql, (serialNum,))
The comma after serialNum for some reason has to be there. Thank you #Michiel Arienfor the head start

Categories