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)
Related
I want to insert different variable values in SQl where the values must not be present in the table using pyodbc but gets error.
variables
for data in datafield:
id = data.Id
iname = data.name
ivalue = data.value
cursor.execute("INSERT INTO Description (SrId, FieldName, FieldValue) VALUES (?, ?, ?) WHERE IN (SELECT * from Description WHERE SrId <>id AND FieldName<>iname AND FieldValue<>ivalue)", (id, iname, ivalue))
connection.commit()
Using Pyodbc to connect the Sql server with python
Error : Syntax error
In SQL Server, there is no VALUES...WHERE syntax. Consider an insert-select with a LEFT JOIN...NULL on table value constructor to avoid duplicates:
# PREPARED STATEMENT WITH QMARK PLACEHOLDERS
sql = """INSERT INTO Description (SrId, FieldName, FieldValue)
SELECT vals.SrId, vals.FieldName, vals.FieldValue
FROM Description d
LEFT JOIN (VALUES (?, ?, ?)) AS vals(SrId, FieldName, FieldValue)
ON d.SrId = vals.SrId
AND d.FieldName = vals.FieldName
AND d.FieldValue = vals.FieldValue
WHERE d.SrId IS NULL
OR d.FieldName IS NULL
OR d.FielValue IS NULL
"""
# BIND PARAMS
cur.execute(sql, (id, iname, ivalue))
connection.commit()
You have an extra " at the end of the line.
cursor.execute("INSERT INTO Description (SrId, FieldName, FieldValue) VALUES (?, ?, ?) WHERE IN (SELECT * from Description WHERE SrId <>id AND FieldName<>iname AND FieldValue<>ivalue)", (id, iname, ivalue)")
Should be
cursor.execute("INSERT INTO Description (SrId, FieldName, FieldValue) VALUES (?, ?, ?) WHERE IN (SELECT * from Description WHERE SrId <>id AND FieldName<>iname AND FieldValue<>ivalue)", (id, iname, ivalue))
I was trying to insert the CSV file to an already existing table in the SSMS database table. I have a data column in my data. But I keep getting this error when I try to insert data. Please tell me where am I doing it wrong because server connection and extracting data from the database are fine. Below is the code.
with open("combine.csv", encoding="utf8") as f:
csvreader = csv.reader(f)
csvdata = []
for row in csvreader:
csvdata.append(row)
print(csvdata)
for row in csvdata:
# Insert a row of data
print(row)
if len(row)>=8:
data = [row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7]]
cursor.execute("INSERT INTO BILLING_COPY (DATE, DEPARTMENT_NUMBER, DEPARTMENT_NAME, DIVISION_CODE, DIVISION_NAME, O_T_AMT, R_AMT, U_AMT ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", data)
Error:
File "", line 7, in
cursor.execute("INSERT INTO BILLING_COPY (DATE, DEPARTMENT_NUMBER, DEPARTMENT_NAME, DIVISION_CODE, DIVISION_NAME, O_T_AMT, R_AMT, U_AMT ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", data)
DataError: ('22007', '[22007] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Conversion failed when converting date and/or time from character string. (241) (SQLExecDirectW)')
File "", line 7, in
cursor.execute("INSERT INTO BILLING_COPY (DATE, DEPARTMENT_NUMBER, DEPARTMENT_NAME, DIVISION_CODE, DIVISION_NAME, O_T_AMT, R_AMT, U_AMT ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", data)
I think the data type you mentioned in VALUES(?,?,? etc) is not right valid data type, try using it as %d or %s
Here is some example:
mySql_insert_query = """INSERT INTO Laptop (Id, Name, Price, Purchase_date)
VALUES
(10, 'ProductValues SP99', 6459, '2019-12-27') """
cursor = connection.cursor()
cursor.execute(mySql_insert_query)
connection.commit()
My two cents: Better to assign insert query to a variable just like data variable.
import sqlite3
import codecs
sqlite3.connect("test.db")
db.execute("""CREATE TABLE IF NOT EXISTS STATIONS
(StationUID INT PRIMARY KEY NOT NULL,
StationNumber TEXT NOT NULL,
StationName TEXT NOT NULL,
StationLongitude REAL NOT NULL,
StationAltitude REAL NOT NULL);""")
print "Created Table STATIONS successfully"
cr = db.cursor()
name = "b"
station_number = "0123"
longitude = 13.4
altitude = 34.4
cr.execute("INSERT INTO STATIONS VALUES", (None, station_number, name, longitude, altitude))
db.commit()
It throws sqlite3.OperationalError: near "VALUES": syntax error, but I don't understand why, because it is the same syntax I found in the example.
You need to specify what values to insert:
INSERT INTO STATIONS VALUES (value1, value2, ...)
You cannot omit that part. Use SQL parameters to map Python values to those locations in the SQL syntax:
cr.execute(
"INSERT INTO STATIONS VALUES (?, ?, ?, ?, ?)",
(None, station_number, name, longitude, altitude))
The INSERT command is not complete. You need to insert the values into the INSERT by writing:
cr.execute("INSERT INTO STATIONS VALUES (?, ?, ?, ?, ?)", (None, station_number, name, longitude, altitude))
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.
I need to update a row if a record already exists or create a new one if it dosen't. I undersant ON DUPLICATE KEY will accomplish this using MYSQLdb, however I'm having trouble getting it working. My code is below
cursor = database.cursor()
cursor.execute("INSERT INTO userfan (user_id, number, round VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE user_id =%s, number=%s, round=%s", (user_id, number, round))
database.commit()
primary key is user_id
A parenthesis was missiing. You can also use the VALUES(column) in the ON DUPLICATE KEY UPDATE section of the statement:
cursor = database.cursor()
cursor.execute("""
INSERT INTO userfan
(user_id, number, round)
VALUES
(%s, %s, %s)
ON DUPLICATE KEY UPDATE
-- no need to update the PK
number = VALUES(number),
round = VALUES(round) ;
""", (user_id, number, round) # python variables
)
database.commit()
def insertAndUpdateData(lVideoList, no_of_gate):
connection = sqlite3.connect('db.sqlite',
detect_types=sqlite3.PARSE_DECLTYPES |
sqlite3.PARSE_COLNAMES)
cursor = connection.cursor()
success = 200
unsuccess = 500
default_value = 0
lDefaultEntry = None
for i in range(no_of_gate):
gate_id = i+1
for videofilename in lVideoList:
cursor.execute("SELECT * FROM dailyfootfall WHERE csv_name=? AND gate_id=?", [videofilename, gate_id])
lDefaultEntry = cursor.fetchone()
try:
if lDefaultEntry is not None:
print ('Entry found...!!!')
cursor.execute("UPDATE dailyfootfall SET video_download=?, processed=?, send_status=? ,male_footfall=?, send_status_male=?, "
"female_footfall =?,send_status_female=?, outsiders=?, send_status_outsiders=? "
"WHERE csv_name=? AND gate_id=? AND footfall=0", [unsuccess,unsuccess,unsuccess,default_value,unsuccess,
default_value,unsuccess,default_value,unsuccess,videofilename,gate_id])
print("Data_Updated..!!!")
else:
cursor = connection.cursor()
print ('Entry Not found...!!!')
print("videofilename: ", videofilename)
insert_query = ("INSERT or IGNORE INTO dailyfootfall(csv_name, video_download, processed, footfall, send_status, "
"male_footfall, send_status_male, female_footfall, send_status_female, gate_id,outsiders, send_status_outsiders) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)")
cursor.execute(insert_query,[videofilename, unsuccess, unsuccess, default_value, unsuccess, default_value,
unsuccess, default_value, unsuccess, gate_id, default_value, unsuccess])
print("Data_Inserted..!!")
print("="*20)
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("Entry found: ",exc_type, fname, exc_tb.tb_lineno)
print("Data Inserted Successfully !")
connection.commit()
cursor.close()
connection.close()
if __name__ == "__main__":
lVideoList = ['2022_01_27_10_00_00-2022_01_25_10_30_00', '2022_01_27_10_30_00-2022_01_25_11_00_00',
'2022_01_27_11_00_00-2022_01_25_11_30_00', '2022_01_27_11_30_00-2022_01_25_12_00_00']
no_of_gate = 3
UpdateData(lVideoList, no_of_gate)
print("default_value inserted!!!!")