Using pymssql to insert datetime object into SQL Server - python

How do I insert a datatime object using pymssql? I know that the SQL Server table is expecting a datetime object, let's say in position 3. I've tried all three of these:
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', datetime.datetime.now())")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', 20130410)")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', '20130410')")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', GETDATE())")
and I get the same error each time:
OperationalError: (241, 'Conversion failed when converting date and/or time from character string.DB-Lib error message 241, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n')
I've scoured the little documentation there is, and searched repeatedly.
EDIT: Secondary problem was a field-length problem. See the first comment on the accepted answer.

you are trying to insert a string that is not formated as date (datetime.datetime.now(), 20130410, '20130410', GETDATE()) so sql server can't parse date from it...
so try this...
cursor.execute("
INSERT INTO MyTable
VALUES(
1,
'Having Trouble',
'" + str(datetime.datetime.now()) + "'
)
")

You can use this code:
# a tuple with the data to be stored in db
data = (1, 'Having Trouble', datetime.datetime.now())
# perform the query
cursor.execute("INSERT INTO MyTable VALUES(%s, %s, %s)" % data)

Try this out:
timeStamp = str(datetime.datetime.now())[0:-3]
This time stamp format can be converted by MS SQL SERVER and can be used in pymssql to insert an object of type datetime

For others facing this same issue my problem was different.
My year was getting parsed as 0014; which I thought was being interpreted as 2014. Took me a while to realize what was happening.
Where pymssql comes in is that the smalldate type didn't recognize 0014 as a year and was unable to make the conversion.

Related

Use table names as sql parameters in python [duplicate]

I have a syntax error in my python which which stops MySQLdb from inserting into my database. The SQL insert is below.
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
I get the following error in my stack trace.
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your
SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near ''four' (description, url) VALUES ('', 'http://imgur.com/a/V8sdH')' at line 1")
I would really appreciate assistance as I cannot figure this out.
EDIT:
Fixed it with the following line:
cursor.execute("INSERT INTO " + table_name + " (description, url) VALUES (%s, %s);", (key.encode("utf-8"), data[key].encode("utf-8")))
Not the most sophisticated, but I hope to use it as a jumping off point.
It looks like this is your SQL statement:
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
IIRC, the name of the table is not able to be parameterized (because it gets quoted improperly). You'll need to inject that into the string some other way (preferably safely -- by checking that the table name requested matches a whitelisted set of table names)... e.g.:
_TABLE_NAME_WHITELIST = frozenset(['four'])
...
if table_name not in _TABLE_NAME_WHITELIST:
raise Exception('Probably better to define a specific exception for this...')
cursor.execute("INSERT INTO {table_name} (description, url) VALUES (%s, %s);".format(table_name=table_name),
(table_name.encode("utf-8"),
key.encode("utf-8"),
data[key].encode("utf-8")))

Insert data in oracle database in python

I can't insert data into database using a dynamic query in python script
def execute_query(self, qo):
query_string = "INSERT INTO " +dep_table+ " (client, sis, entity_name_1, entity_name_2, flag_dep,process, flag_dep_det) VALUES (%s, %s, %s, %s, %s, %s, %s)" % ("'CO'","'"+qo.db_src+"'","'"+qo.table_src+"'","'"+qo.table_des+"'","'"+qo.check_func+"'","'"+qo.table_des+"'","'NULL'")+";"
cursor.execute(query_string)
I got this error:
ERROR: Failed to set dependencies informations : ORA-00933: SQL command not properly ended
The connection to the database is okay, but I can't insert.
Drop the semi-colon at the end of the string you are creating / executing.
It shouldn't be part of the SQL statement, rather used in some client tools to indicate the end of a statement so that the client can send it to the database to be executed.
I found the solution to the problem
connection.commit()
You can use format method in Python like below:
def execute_query(self, qo):
query_string = "INSERT INTO {0} (client, sis, entity_name_1, entity_name_2, flag_dep,process, flag_dep_det) VALUES ('{1}', '{2}', '{3}', '{4}', '{5}', '{6}', {7})".format(dep_table, 'CO', qo.db_src, qo.table_src, qo.table_des, qo.check_func, qo.table_des, 'NULL')
cursor.execute(query_string)

How to write proper MySQL Insert statement in Python?

I am trying to insert two columns of data into a MySQL table from Python. And my Insert statement is true, I guess. But I am still getting 1064 error code.
This is for MySQL server version 8.0.12 and Python 3.7. I had tried changing different methods of inserting dynamic variables.
#alter is the data value read from serial port
sql="select * from stds"
cur.execute(sql)
records=cur.fetchall()
if cur.rowcount>0:
print('Number of rows - ',cur.rowcount)
else:
print('No data in table')
for row in records:
print(row)
if row[1]==alter:
print("Student exists : ",row[1])
date = datetime.datetime.now()
print(type(date))
ins = (alter, date)
sql = "Insert into 'attendance' ('stdid', 'dt') VALUES (%s,%s)"
cur.execute(sql, ins)
cnn.commit()
print('Sucessfully Stored the Record')
#success(alter)
break
else:
print("Student doesn't exist")
I am getting this error message
Error:
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ''attendance' ('stdid', 'dt') VALUES ('FE0070E83D5B','2019-08-01 09:09:06.162304'' at line 1
And I am expecting that these read tag values are inserted successfully​.
Identifiers (e.g. column and table names) in MySQL (and most other flavors of SQL as well) do not take single quotes. They take either no quotes, double quotes, or maybe backticks in the case of MySQL. Try this version:
sql = "INSERT INTO attendance (stdid, dt) VALUES (%s, %s)"
ins = (alter, date)
cur.execute(sql, ins)
cnn.commit()

Can't get the right SQL syntax using pymsql, error 1064

My output works in csv, but not when trying to insert it into mysql. I get the following error and have not been able to figure it out. I'm a novice so I may be missing something obvious. Same error in Python 2x and 3x.
pymysql.err.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 'key, title, content, start_date, end_date, initial_update) VALUES('reddit', 'h' at line 1")
mainDB_cnx = pymysql.connect(user='XXXX', password='XXXX',
host='XXXX',
database='Test', use_unicode=True, charset="utf8mb4")
with mainDB_cnx:
mainDB_cursor = mainDB_cnx.cursor()
mainDB_cursor.execute(
"INSERT INTO reddit(site, site_url, key, title, content, start_date, end_date, initial_update) VALUES(%s, %s, %s, %s, %s, STR_TO_DATE(%s,'%%Y-%%m-%%d'), STR_TO_DATE(%s,'%%Y-%%m-%%d'), STR_TO_DATE(%s,'%%Y-%%m-%%d'))",
(["reddit", "http://www.reddit.com", url, title, content, datetime.strptime(date,'%d %B %Y').strftime('%Y-%m-%d'), datetime.strptime('2018-07-25','%Y-%m-%d').strftime('%Y-%m-%d'), datetime.strptime('2018-07-25','%Y-%m-%d').strftime('%Y-%m-%d')]))
print("Successful")
KEY is a reserved word in the MySQL dialect of structured query language. See this. https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-K
So you must wrap that column name in delimiters whenever you mention it.
Try
INSERT INTO reddit (side, site_url, `key`, title, ....
Or, better, don't use reserved words for the names of columns in your tables. The next programmer to work on your system will thank you.

Python insert into %s MySQL

I am trying to insert some data into a database using the variable test as the table name. But unfortunately I cant seem to achieve this. Can anyone help me out?
From my raise I am getting:
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
My code:
test = "hello"
# Open database connection
db = MySQLdb.connect("127.0.0.1","admin","password","table" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = ("""INSERT INTO %s (name,
age, gender)
VALUES (%s, %s, %s)""",(test))
try:
# Execute the SQL command
cursor.execute(sql, (name, age, gender))
db.commit()
except:
raise
db.rollback()
# disconnect from server
db.close()
I don't think MySQLdb lets you use parameters for table names -- usually this is used for actual parameters (ones that are sometimes from user input and need sanitization - the name/age/gender part gets this right). You could use Python's string formats to achieve this:
sql = ("""INSERT INTO {table} (name, age, gender)
VALUES (%s, %s, %s)""".format(table=table), (test))
Something like this will work:
sql = """INSERT INTO %s (name, age, gender)
VALUES (%s, %s, %s)""" % (test, "%s", "%s", "%s")
You need to separate Python's string substitution from MySQL's parameter substitution. The above is a crude approach, but minimally different from your own code.

Categories