"insert into agentattribute(agentid,attributeRefURL,attributeName,attributeValue,Operation,attributeOldValue) values (" + live_agent_id + ",'" + live_entry + "','" +live_name_value_array[0] + "','" + live_name_value_array[1] + "', 'Added' ,',')")
Can someone help me out please?
As the error message explains, agentId column has primary key/unique constraint on it and value 8207 already exists.
In this case, you can go ahead with one of the below options:
Update the record if the value already exists
Propogate the error message back to User Interface/application
Related
So, I'm trying to add a variable (string) to another variable (table). My code looks like this:
tableName = '123456789'
testVariable = 'test'
c.execute('INSERT INTO ' + tableName + ' (testColumn) VALUES (' + testVariable + ')')
conn.commit()
But for some reason, it's giving me this error
c.execute('INSERT INTO ' + tableName + ' (testColumn) VALUES (' + testVariable + ')')
sqlite3.OperationalError: near "123456789": syntax error
What do I do?
c.execute("INSERT INTO ? (testColumn) VALUES (?)", (tableName, testVariable))
Try this...
c.execute('''INSERT INTO 123456789(testColumn) VALUES(?)''', (testVariable))
Ok, I managed to fix it myself. I had to add single quotes to the start and end of the variables, and then use this: c.execute("INSERT INTO {} (testColumn) VALUES ({})".format(tableName, testVariable))
Thanks for the answers!
I need to insert a record into the table MemberDetails but I end up with the error stating " _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'I' at line 1") "
sql5="INSERT INTO MemberDetails VALUES"+"("+"'2016-2020','"+PhoneNum+"','VEC','"+Address+"','"+StuID+"','"+DOB+"','1000','"+Name+"','"+Pass+"','"+dept+"','"+year+"','"+sec+"')"
cursor.execute(sql5)
You need to add spacing as well as the columns in the table each variable will be inserted into, your query should be like this:
"INSERT INTO MemberDetails (datetime, phone, code, address, stuid, birthdate, num, name, pass, dept, year, sec) VALUES (" + "'2016-2020','" + PhoneNum + "','VEC','" + Address + "','" + StuID + "','" +DOB +"','1000','" + Name + "','" + Pass + "','" + dept + "','" + year + "','" +sec + "')"
Just replace the variables in the first set of brackets with the column name you want each variable to be put into.
I have the following values In Python values:
_sfwBIPMKEeCTfuMZpaDEBQ Atomic Warehouse Model None
These values are sent through a function and is being put into a db3 table like this:
INSERT INTO [PackageRoster] (PkgID, Package, PkgParentID) VALUES ('_sfwBIPMKEeCTfuMZpaDEBQ', 'Atomic Warehouse Model', 'None');
I do not want the string 'None' put into the table. I would like NULL.
How do I tell Python to inject NULL instead of None?
Here's the function that works the statement (includes debug feature):
def StorePackage(PkgID, Package, PkgParentID):
dbutils.ResetTable()
conn = sqlite3.connect(dbutils.db)
try:
conn.execute("INSERT INTO " + dbutils.table + " (PkgID, Package, PkgParentID) VALUES ('" + PkgID + "', '" + Package + "', '" + PkgParentID + "');")
except:
print("INSERT INTO " + dbutils.table + " (PkgID, Package, PkgParentID) VALUES ('" + PkgID + "', '" + Package + "', '" + str(PkgParentID) + "');")
conn.commit()
Thanks
I initially commented a recommendation to use parameter substitution, assuming it wasn't actually related. On further inspection, though, I think it's exactly what you're looking for.
Your code currently inserts all strings because you're explicitly converting everything to a string in Python. Parameter substitution enables Python to handle how to get its values into the database, and also protects you from SQL injection attacks.
conn.execute("INSERT INTO " + dbutils.table + " (PkgID, Package, PkgParentID) VALUES (?,?,?)", (PkgID, Package, PkgParentID))
A Python None object will be inserted as an SQLite NULL using this method. You can read more about parameter substitution in the docs, as well as how Python values are converted to SQLite values and vice versa.
You are converting all of your values to strings, because you add quotes arround them. I.e, because you do '" + str(PkgParentID) + "' it will end up as 'None' instead of None.
You should for example convert your values to a string before the query, and replace them with NULL when they are None:
def StorePackage(PkgID, Package, PkgParentID):
PkgParentID = "'{}'".format(PkgParentID) if PkgParentID is not None else "NULL"
# Same for other parameters if desired
dbutils.ResetTable()
conn = sqlite3.connect(dbutils.db)
query = "INSERT INTO " + dbutils.table + " (PkgID, Package, PkgParentID) VALUES ('" + PkgID + "', '" + Package + "', " + PkgParentID + ");"
try:
conn.execute(query)
except:
print(query)
conn.commit()
Also you should use parameter substitution, although thats not what is causing your issue in the first place
How would I update an entry that is already in a database using sqlite3?
I've tried:
db_curs.execute("INSERT INTO `database` (cID) VALUES ('Updated')")
But this, of course, creates a new entry. I can obtain the (line(?)) number (of the entry) and what is the command to update the database rather than create a new entry?
EDIT:
Put a bit better, when I convert the SQL entry to a python list I get the following,
(1, u'GGS-04', u'John', u'Smith', 9, u'0')
I need to be able to add a digit to the last item. Here is what I have.
info = (1, u'GGS-04', u'John', u'Smith', 9, u'0')
for result in info:
ln = str(result[0])
ggs = str(result[1])
first_name = str(result[2])
last_name = str(result[3])
dob = str(result[4])
spend = str(result[5])
while True:
res = raw_input("Enter points to add: ")
try:
int(res)
break
except:
print "Please enter a number..."
pass
spend = str(int(spend) + int(res))
db_curs.execute("UPDATE `" + db_name + "` (cID, first_name, last_name, date_of_birth, spend) VALUES ('" + srce + "', '" + first_name + "', '" + last_name + "', '" + dob + "' WHERE '" + spend + "')")
db_connection.commit()
Could someone please explain the correct syntax for this command? It would be awesome if I could just update the "Spend" column than having to update them all from prefixed variables.
Thank you :)
This shall work:
db_curs.execute("UPDATE database SET spend =`" + spend + "` WHERE cID="+ cID)
See also SQL Update Syntax
Btw, "database" isn't a useful name for a database's table. What about "users" or "spendtime" or sth more descriptive?
Im running into this error that I can't work out
Im writing some code in Python using tkinter interface to transfer data from a text file to sqlite.
first, here is the relevant code:
def submit_data(self):
self.new_filename = self.file_entry.get()
self.new_tablename = self.table_entry.get()
self.new_fieldname = self.field_entry.get().split(',')
#print(self.new_fieldname)
self.create_new.destroy()
from sqlite3 import dbapi2 as sqlite
con = sqlite.connect(self.new_filename)
cur = con.cursor()
cur.execute('CREATE TABLE ' + self.new_tablename + '(id INTEGER PRIMARY KEY)')
for field in self.new_fieldname:
cur.execute('ALTER TABLE ' + self.new_tablename + ' ADD ' + field)
with open(self.filename, 'r', encoding='latin-1') as self.the_file:
status = True
#_keynumber=1
while status:
_row = self._next_line()
if _row:
_entry_list = _row.split(',')
# add space after text line comma for formatting
_entry_list = ', '.join(_entry_list)
#print(_entry_list)
#entries = {'row': _keynumber, 'entry': _entry_list}
#row_entry = "INSERT INTO " + self.new_tablename + " VALUES(" + _entry_list + ")"
cur.execute("INSERT INTO " + self.new_tablename + " VALUES(" + _entry_list + ")")
#_colrange = range(_colamount)
#_keynumber+=1
else:
status = False
con.commit()
At the cur.execute("INSERT INTO " ... line (about 6 lines up) I get this error:
** cur.execute("INSERT INTO " + self.new_tablename + " VALUES(" + _entry_list + ")")
sqlite3.OperationalError: near ".": syntax error**
I have changed this around in many different ways. At one time I had the whole "INSERT INTO ... VALUES ...." string as a variable and used
cur.execute(*variable*)
when I did it this way the error was the same except "OperationalError: near "." was "OperationalError: near "of" ... and there was no 'of' anywhere.
Im really confused and frustrated. Someone break this down for my please??
Thanks
F
the text file lines its reading are set up like this:
A Big Star In Hollywood,Sandra Dickinson
so I had figured that if I use .join() to put a space after the comma then the string would be the equivalent of two VALUES for the INSERT INTO statement.
Remove
_entry_list = ', '.join(_entry_list)
and use
cur.execute("INSERT INTO " + self.new_tablename + "(" + ",".join(self.new_fieldname) +") VALUES(" + ",".join(("?" for i in xrange(len(_entry_list)))) + ")", _entry_list)
This will parameterize your query and automatically quote all value in _entry_list.
You still have to manually quote self.new_tablename and self.new_fieldname. This should be before you use them in any sql statements.
You need to quote your strings.
As written, your SQL statement is:
INSERT INTO foo VALUES(Hello there, world, I am, unquoted, string, not good)
You should use:
INSERT INTO foo VALUES("Hello there","world","I am","quoted","string","hooray")
I suggest you do the following:
a) Instead of executing the statement, print it to the console. Change the line:
cur.execute("INSERT INTO " + self.new_tablename + ...)
to:
print "INSERT INTO " + self.new_tablename + ...
b) Run your program after making this change. Take a look at the SQL statements that you print to the console. Are they valid SQL statements? Start a SQLite command-line, and copy/paste the statements produced by your program. Does SQLite give any errors when you try to execute the pasted statements?