Unable to insert data in oracle sql using python - python

I am trying to insert data into a table created in oracle sql using python. It temporarily inserts data into the table but as soon as the python process ends , the data is deleted.
def submit_button(roll_no,name,marks):
sql_query = 'INSERT INTO assignment_7 VALUES (:r,:n,:m)'
c.execute(sql_query,[int(roll_no),name,int(marks)])
c.execute('SELECT * FROM assignment_7')
for rows in c:
print(rows[0],'-',rows[1],'-',rows[2])
For example if (12,'aryan',20) are inserted into the table , the print statement works , but actually no data gets inserted when I check the table itself .
Name Null? Type
ROLL_NO NOT NULL NUMBER
STUDENT_NAME VARCHAR2(30)
MARKS NUMBER

try to add c.commit
def submit_button(roll_no,name,marks):
sql_query = 'INSERT INTO assignment_7 VALUES (:r,:n,:m)'
c.execute(sql_query,[int(roll_no),name,int(marks)])
c.commit
c.execute('SELECT * FROM assignment_7')
for rows in c:
print(rows[0],'-',rows[1],'-',rows[2])

Related

Insert Postgres Python while getting an ID from a second table

I want to insert a record into usage_information while getting the machine_id from machines tables
How the query should be?
I'm using something like this for selecting from both tables
cur.execute(
'''SELECT U.timestamp, M.hostname, M.up_time,
U.cpu_utilization, U.running_processes,
U.total_memory, U.available_memory,
U.used_memory, U.total_disk_capacity,
U.free_disk_space, U.used_disk_space,
U.network_requests_sent,
U.network_requests_received
FROM usage_information U, machines M
WHERE U.machine_id = M.machine_id
'''
)

How to the store a column from a SQL request into a variable?

I want to put the result of each column of the result of my request and store them into separate variables, so I can exploit its results.
I precise this is with a SELECt * and not separate requests.
So, If I do for example:
with connection.cursor() as cursor:
# Read a single record
sql = 'SELECT * FROM table'
cursor.execute(sql)
result = cursor.fetchall()
print(result)
I want to do :
a = [results from column1]
b = [results from column2]
The results should be turned into a row and not be left as a column, to make it a dictionary.
It's probably very simple but I'm new with Python / SQL, thank you.

Alter query according to user selection in sqlite python

I have a sqlite database named StudentDB which has 3 columns Roll number, Name, Marks. Now I want to fetch only the columns that user selects in the IDE. User can select one column or two or all the three. How can I alter the query accordingly using Python?
I tried:
import sqlite3
sel={"Roll Number":12}
query = 'select * from StudentDB Where({seq})'.format(seq=','.join(['?']*len(sel))),[i for k,i in sel.items()]
con = sqlite3.connect(database)
cur = con.cursor()
cur.execute(query)
all_data = cur.fetchall()
all_data
I am getting:
operation parameter must be str
You should control the text of the query. The where clause shall allways be in the form WHERE colname=value [AND colname2=...] or (better) WHERE colname=? [AND ...] if you want to build a parameterized query.
So you want:
query = 'select * from StudentDB Where ' + ' AND '.join('"{}"=?'.format(col)
for col in sel.keys())
...
cur.execute(query, tuple(sel.values()))
In your code, the query is now a tuple instead of str and that is why the error.
I assume you want to execute a query like below -
select * from StudentDB Where "Roll number"=?
Then you can change the sql query like this (assuming you want and and not or) -
query = "select * from StudentDB Where {seq}".format(seq=" and ".join('"{}"=?'.format(k) for k in sel.keys()))
and execute the query like -
cur.execute(query, tuple(sel.values()))
Please make sure in your code the provided database is defined and contains the database name and studentDB is indeed the table name and not database name.

UPDATE values of a column in a table with Python in SQL Server

I want to update a column with SQL server query in python, as you see I am updating the relative column as below:
I have a CSV file with some A values of relative table as below:
CSV file: (a.csv)
ART-B-C-ART0015-D-E01
ADC-B-C-ADC00112-V-E01
Python Code: (create Name Value)
ff = pd.read_csv("C:\\a.csv",encoding='cp1252')
ff["Name"]= df["A"].str.extract(r'([a-zA-Z]{3}\d{4,5})') + "-A"
Result of python Code:
ART0015-A
ADC00112-A
Table :
A Name FamilyName
ART-B-C-ART0015-D-E01 NULL ART
ADC-B-C-ADC00112-V-E01 NULL ADC00112
Also A is a column in my table (Not all of the A records but some of them) and based on A value I want to update Name column.
My database is SQL Server and I don't know how to update in Name Column in SQL Server where the A value in the csv file is equal to A in the relative table.
Code in Python:
conn = pyodbc.connect('Driver={SQL Server}; Server=ipaddress; Database=dbname; UID=username; PWD= {password};')
cursor = conn.cursor()
conn.commit()
for row in ff.itertuples():
cursor.execute('''UPDATE database.dbo.tablename SET Name where ?
)
conn.commit()
Expected result in table
A Name FamilyName
ART-B-C-ART0015-D-E01 ART0015-A ART
ADC-B-C-ADC00112-V-E01 ADC00112-A ADC00112
I would use an SQL temp table and inner join to update the values. This will work for only updating a subset of records in your SQL table. It can also be efficient at updating many records.
SQL Cursor
# reduce number of calls to server on inserts
cursor.fast_executemany = True
Create Temporary Table
statement = "CREATE TABLE #temp_tablename(A VARCHAR(200), Name VARCHAR(200))"
cursor.execute(statement)
Insert Values into a Temporary Table
# insert only the key and the updated values
subset = ff[['A','Name']]
# form SQL insert statement
columns = ", ".join(subset.columns)
values = '('+', '.join(['?']*len(subset.columns))+')'
# insert
statement = "INSERT INTO #temp_tablename ("+columns+") VALUES "+values
insert = [tuple(x) for x in subset.values]
cursor.executemany(statement, insert)
Update Values in Main Table from Temporary Table
statement = '''
UPDATE
tablename
SET
u.Name
FROM
tablename AS t
INNER JOIN
#temp_tablename AS u
ON
u.A=t.A;
'''
cursor.execute(statement)
Drop Temporary Table
cursor.execute("DROP TABLE #temp_tablename")

Select rows from one table where certain field is equal to a field in a row from another table, with Python and SQLite3

I have a small database which is legacy from an almost defunct project. This database has a "Patients" table with individual personal data and an unique "Id" field, and an "Exams" table with some fields for each exam, one of these fields being "Patient_Id".
What I want is, for a given patient (row from "Pacientes" table) the exams (rows) from "Exames" table whose "Patient_Id" matches that of the given patient.
I am very beginner with SQL, so if the question is very naive, I apologize.
My working code is the following, but I am using a for loop while I would much rather have a SQL query (which is the very point of using databases, I think...):
#!/usr/bin/env python
# coding: utf-8
import os, sqlite3
conn = sqlite3.connect('BDdata.db3')
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('SELECT * FROM Exames')
exams = c.fetchall()
c.execute('SELECT * FROM Pacientes')
for row in c:
Nome = row['nome']
ID = row['Id']
for exam in exams: # I would like to replace this loop
if exam['Id_Paciente'] == ID: # with a SQL query meaning
print exam['File']
============================
An answer to a similar question seems to be what I want, but I have no idea how to do this in Python with sqlite3 module, much less what in this expression is essential and what is incidental, or what is the syntax structure:
Selecting rows from a table by One a field from other table
SELECT i.prof_image
FROM profile_images i
WHERE cat_id = (select max(cat_id) from images_cat)
I think the following should do what you want:
...
c = conn.cursor()
c.execute('SELECT * FROM Pacientes')
for row in c.fetchall():
Nome = row['nome']
ID = row['Id']
c.execute('SELECT File FROM Exames WHERE Id_Paciente=?', [ID])
for exam in c:
print exam['File']

Categories

Resources