Python doesn't save data to sqlite db - python

This is my code:
conn = sqlite3.connect(nnpcconfig.commondb)
cur = conn.cursor()
query = ['2124124', 'test2', 'test3', 'test4', 'test5']
cur.execute("insert into users(id, encpass, sname, name, fname) values (?, ?, ?, ?, ?)", query)
conn.commit
cur.execute("select * from users")
for row in cur:
print row
This code works, returning row fed to it. But it comes out that once script terminated, table is clear again! Where's the mistake? Of course, table users exists.

You have another mistake: conn.commit instead of conn.commit()

Related

Mariadb INSERT INTO but without ID

I want to add data to my database through python, but I do not know what to do with the ID colum.
I have four colums and I only want to add the last three, the ID is counting up itself.
def add_data(temp, hum):
try:
dt = datetime.datetime.now().replace(microsecond=0).isoformat(' ')
statement = "INSERT INTO messstation (?id?,uhrzeit, luftfeuchtigkeit, raumtemperatur) VALUES (?, ?, ?, ?)"
data = (?id?, dt, hum, temp)
cursor.execute(statement, data)
connection.commit()
except database.error as e:
print(f"Error:{e}")
This should work if the id field is an auto-increment one:
statement = "INSERT INTO messstation (uhrzeit, luftfeuchtigkeit, raumtemperatur) VALUES (?, ?, ?)"
data = (dt, hum, temp)

Pyodbc: how can I get the primary key after a successful insert into the SQL Server database?

I have a table Employee in SQL Server as follows:
ID (AUTO, PK),
firstname (varchar),
lastname (varchar)
I want to insert data like ('John', 'Myers') into the table.
I used the following code in Python using pyodbc:
connection = pyodbc.connect(...)
cursor = connection.cursor()
cursor.execute("insert into employee(firstname, lastname) values(?, ?)", ['John','Myers'])
Is it possible to get the ID value of this newly inserted row without having to write a select query?
You can use the OUTPUT clause
cursor.execute("insert into employee(firstname, lastname) output inserted.ID values(?, ?);", ['John','Myers'])
id = cursor.fetchone()
Alternatively, use SCOPE_IDENTITY()
cursor.execute("insert into employee(firstname, lastname) values(?, ?); select SCOPE_IDENTITY();", ['John','Myers'])
id = cursor.fetchone()

Python : Inserting multiple values into a table from excel

I have to read data from Excel and insert it into Table...
For this I am using Python 2.7, pymssql and xlrd modules...
My sql connection is working fine and I am also able to read data from Excel properly.
My table structure :
CREATE TABLE MONTHLY_BUDGET
(
SEQUENCE INT IDENTITY,
TRANSACTION_DATE VARCHAR(100),
TRANSACTION_REMARKS VARCHAR(1000),
WITHDRAWL_AMOUNT VARCHAR(100),
DEPOSIT_AMOUNT VARCHAR(100),
BALANCE_AMOUNT VARCHAR(100)
)
My excel values are like this :
02/01/2015 To RD Ac no 147825000874 7,000.00 - 36,575.74
I am having problem while inserting multiple values in the table... I am not sure how to do this...
import xlrd
import pymssql
file_location = 'C:/Users/praveen/Downloads/OpTransactionHistory03-01-2015.xls'
#Connecting SQL Server
conn = pymssql.connect (host='host',user='user',password='pwd',database='Practice')
cur = conn.cursor()
# Open Workbook
workbook = xlrd.open_workbook(file_location)
# Open Worksheet
sheet = workbook.sheet_by_index(0)
for rows in range(13,sheet.nrows):
for cols in range(sheet.ncols):
cur.execute(
" INSERT INTO MONTHLY_BUDGET VALUES (%s, %s, %s, %s, %s)", <--- Not sure!!!
[(sheet.cell_value(rows,cols))])
conn.commit()
Error :
ValueError: 'params' arg () can be only a tuple or a dictionary.
The docs are here : http://pymssql.org/en/stable/pymssql_examples.html
The exception you are getting says that the "'params' arg() can be only a tuple or a dictionary" but you're passing in a list. Also, your parameter list appears to be a single tuple instead of a list with 4 values. Try changing
cur.execute(
" INSERT INTO MONTHLY_BUDGET VALUES (?, ?, ?, ?, ?)", <--- Not sure!!!
[(sheet.cell_value(rows,cols))])
to
cur.execute(
" INSERT INTO MONTHLY_BUDGET VALUES (?, ?, ?, ?, ?)", <--- Not sure!!!
(sheet.cell_value(rows,cols)))
... or maybe
cur.execute(
" INSERT INTO MONTHLY_BUDGET VALUES (?, ?, ?, ?, ?)", <--- Not sure!!!
((sheet.cell_value(rows,cols))))
NB: untested. I've always changed how the bind variables in your SQL are being called.

Error when inserting rows into SQLite with Python

Getting an error when trying to insert a row into SQLite table from Python.
The relevant code;
sql = '''INSERT INTO scr(scr=?, close_date=?, vendor=?, application=?, dev=?, tester=?, release=?)''', (issueId, closeDate, vendor, application, assignedDev, assignedTester, enterpriseRelease)
try:
cursor.execute(sql)
db.commit()
except Exception, err:
print("\nFailed to insert row into table scr:\n" + str(sql))
print(Exception, err)
and the error returned:
Failed to insert row into table scr:
('INSERT INTO scr(scr=?, close_date=?, vendor=?, application=?, dev=?, tester=?, release=?)', ('236500', '0', 'Database', 'Starbase Deleted', 'john.doe', 'jane.doe', 'None'))
(<type 'exceptions.Exception'>, ValueError('operation parameter must be str or unicode',))
Your sql statement is not right, try this:
sql = '''INSERT INTO scr(scr, close_date, vendor, application, dev, tester, release) VALUES (?, ?, ?, ?, ?, ?, ?)'''
params = (issueId, closeDate, vendor, application, assignedDev, assignedTester, enterpriseRelease)
try:
cursor.execute(sql, params)
db.commit()
except Exception as err:
print("\nFailed to insert row into table scr:\n" + str(sql))
print(Exception, err)

How do i use table data from my sqlite3 database as a python variable

My code so far
conn = sqlite3.connect('databaserm/database')
curs = conn.cursor()
curs.execute('SELECT * FROM saves')
lvl = curs.fetchone()
conn.close()
ok maybes its the code i used to add the data to the db
i've tried this
cn = sqlite3.connect(/databaserm/database")
curs = cn.cursor()
curs.execute('DROP TABLE saves')
curs.execute('CREATE TABLE saves (lvl)')
#curs.execute('INSERT INTO saves VALUES (null, ?)', lvl)
query = """INSERT INTO saves (lvl)
VALUES (?)"""
data = [lvl]
curs.execute(query, data)
cn.commit
cn.close()
and this
conn = sqlite3.connect('/databaserm/database')
curs = conn.cursor()
curs.execute('INSERT INTO saves VALUES(null, ?,)', (lvl,))
conn.commit
Executing select and then fetchone will return a tuple. What else do you need?
Here's an example:
import sqlite3 as sqlite
con = sqlite.connect(':memory:')
cursor = con.cursor()
cursor.execute('''
create table names (id integer primary key,
name varchar(50), email varchar(50))''')
cursor.execute('''
insert into names values (null, "John Doe", "jdoe#jdoe.zz")''')
cursor.execute('''
insert into names values (null, "Mary Sue", "msue#msue.yy")''')
name = """Lu'k'e d"fdf" Sma"""
email = "use#force.net"
cursor.execute(
'''insert into names values (null, ?, ?)''',
(name, email))
cursor.execute('select * from names')
for c in cursor:
print c
Uses iteration over cursor (an alternative way to get result). Prints:
(1, u'John Doe', u'jdoe#jdoe.zz')
(2, u'Mary Sue', u'msue#msue.yy')
(3, u'Lu\'k\'e d"fdf" Sma', u'use#force.net')
Using fetchone instead of iteration:
print cursor.fetchone()
cursor.close()
Prints:
(1, u'John Doe', u'jdoe#jdoe.zz')

Categories