In a Python environment, I've got the following variable:
post_time_ms="1581546697000"
which is a Unix-style time with milliseconds.
In my table, "created_date_time" is defined as a datetime column.
I'm trying to use an INSERT statement of the form:
sql_insert_query = "INSERT INTO myTable (id_string, text,
created_date_time) VALUES ('identifier', 'text_content',
FROM_UNIXTIME('post_time/1000')"
I can't figure out how I'm supposed to punctuate that. If I run the query as shown above, I get:
"Failed to insert record 1292 (22007): Truncated incorrect DECIMAL value: 'post_time/1000'
I've tried every variation of single quotes/no quotes I can think of but I always get errors.
For example if I do:
sql_insert_query = "INSERT INTO myTable (id_string, text,
created_date_time) VALUES ('identifier', 'text_content',
FROM_UNIXTIME('post_time'/1000)"
I get:
Failed to insert record 1292 (22007): Truncated incorrect DOUBLE value: 'post_time'
I've gone so far as to try and convert the Unix-style "1581546697000" value as follows:
post_time_mysql = datetime.fromtimestamp(int(post_time)/1000)
and then:
sql_insert_query = "INSERT INTO myTable (id_string, text,
created_date_time) VALUES ('identifier', 'text_content',
'post_time_mysql')"
and even though
print(post_time_mysql)
outputs "2020-02-14 09:25:28",
I still get this error for the above query:
Failed to insert record 1292 (22007): Incorrect datetime value: 'post_time_mysql' for column `myDatabase`.`myTable`.`created_date_time` at row 1
Any ideas/suggestions?
==========
My workaround is to do the following:
sql_insert_query = "INSERT INTO myTable (id_string, text, created_date_time) VALUES (%s, %s, %s)"
sql_insert_data = (identifier, text_content, post_time_mysql)
cursor.execute(sql_insert_query, sql_insert_data)
But I still don't understand how to successfully do it with one query statement - if it's possible.
Related
sql = ("INSERT INTO {0} "
"(id, timestamp, status, priority, client, group, capacity, level, mail_id) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)".format(TABLE_NAME_MAIL))
values = ('NULL', report['timestamp'], 'succeeded', report['priority'], c.strip(), report['group'], 'NULL', 'NULL', ref_mailid)
cursor.execute(sql, values)
#cursor.execute('INSERT INTO %s VALUES (NULL,"%s","%s","%s","%s","%s",NULL,NULL,"%s") ' % (TABLE_NAME_REPORT, report['timestamp'], 'succeeded', report['priority'], c.strip(), report['group'], ref_mailid))
The commented out cursor.execute works, the uncommented throws an error:
_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 'group, capacity, level, mail_id) VALUES ('NULL', '2014-12-05 23:46:56', 'succeed' at line 1")
Column 'id' has AUTO_INCREMENT
Why am I getting this error?
group is a reserved keyword in MySQL. Use backticks to escape the name
INSERT INTO {0} (id, timestamp, status, priority, client, `group`, capacity ...
here--------------------------------^-----^
or even better use a different column name.
And don't use 'NULL' as parameter. Either use NULL without the quotes or remove it completely from the query:
INSERT INTO {0} (timestamp, ...
^----------no ID
When using an auto increment column, you have two options:
Insert a value in there (ie: Override the auto increment)
Do not set the column at all
1:
In case of setting a value, and you want to set "NULL" the column has to allow a NULL. This is rarely the case with an auto increment column since it would defeat its purpose.
So this is allowed:
INSERT INTO tab (id, sometext) VALUES (10,"Hi");
2:
Alternative (most used) is not to name the column at all:
INSERT INTO tab (sometext) VALUES ("Hi");
which would lead to mysql assigning a value to id in your table.
I'm a beginner to SQL (as you'll soon be able to tell...) and I cannot for the life of me figure out how to best insert a simple JSON array of strings into a PostgreSQL table. I suspect the solution is quite easy but I've spent just a bit too long trying to puzzle it out on my own.
First I create the table:
CREATE TABLE test (
id serial PRIMARY KEY
my_array jsonb
);
Where the array is of type JSON. Insert some initial data:
INSERT INTO test (id, my_array) VALUES(1, '[]');
And now I want to update the myarray column with a JSON array using Node.js node-postgres. The array might look something like
const myArray = ['foo', 'bar', 'foobar\'s escaped character emporium'];
await db.none(
'UPDATE test ' +
`SET my_array = ${myArray} ` +
'WHERE id = 1'
);
This results in
error: syntax error at or near ","
Ok, so what if I do
await db.none(
'UPDATE test ' +
`SET my_array = "${myArray}" ` +
'WHERE id = 1'
);
I get
error: column "foo,bar,foobar's escaped character emporium" does not exist
and if I do
await db.none(
'UPDATE test ' +
`SET my_array = ${JSON.stringify(myArray)} ` +
'WHERE id = 1'
);
I get
ERROR error: syntax error at or near "["
Finally, if I do
await db.none(
'UPDATE test ' +
`SET my_array = '${JSON.stringify(myArray)}' ` +
'WHERE id = 1'
);
I end up with
stack=error: syntax error at or near "s"
I've also tried storing the data data as a native PostgreSQL array but I encounter similar problems:
CREATE TABLE test (
id serial PRIMARY KEY
my_array text ARRAY
);
INSERT INTO test (id, my_array) VALUES(1, '{}');
Then
const myArray = ['foo', 'bar', 'foobar\'s escaped character emporium'];
await db.none(
'UPDATE test ' +
`SET my_array = ${myArray} ` +
'WHERE id = 1'
);
gives
stack=error: syntax error at or near ","
Similar variations using JSON.stringify() and combinations of different quotes have proved fruitless as well. I kind of expected this approach to be less likely to work as PostgreSQL arrays are just a different format, but I was hoping there might be some kind of attempt at coercion. Reading through the documentation I can't spot any obvious way to convert a JSON array into the expected format for a PostgreSQL array.
Consider using a Parameterized query or Prepared statements.
That will help with you with qoutes and get protection against SQL injection as a bonus.
I am trying to insert a row into my table with the following query in ssms:
INSERT INTO [Reservation].[dbo].[Contacts]
([ContactID]
,[Name]
,[Phone]
,[Email]
,[QoowayUserName])
VALUES
(<"100", nvarchar(50),>
,<"Vincent Chase", nvarchar(50),>
,<"3103331234", nvarchar(50),>
,<"vincent_chase#hollywood.com", nvarchar(50),>
,<"Username", nvarchar(50),>)
GO
I get the error:
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '<'.
I've also tried using single quotes. What am I doing wrong?
INSERT INTO Reservation.dbo.Contacts
(ContactID
,Name
,Phone
,Email
,QoowayUserName)
VALUES
('100'
,'Vincent Chase'
,'3103331234'
,'vincent_chase#hollywood.com'
,'Username')
You might need to remove the "dbo", like this:
INSERT INTO Reservation.Contacts
(ContactID
,Name
,Phone
,Email
,QoowayUserName)
VALUES
('100'
,'Vincent Chase'
,'3103331234'
,'vincent_chase#hollywood.com'
,'Username')
I'm trying to insert a record to a table and I get the following error.
Mysql Error Code : 1292 Incorrect datetime value : ''
Mysql code snip-let is as follows
INSERT INTO tbl_dashboard (avg_response)
SELECT cast(ifnull(floor(avg(5 * (DATEDIFF(substring(im.inq_managerreply,-10), im.inq_managerdate) DIV 7)
+ MID('0123444401233334012222340111123400001234000123440',
7 * WEEKDAY(im.inq_managerdate) + WEEKDAY(substring(im.inq_managerreply,-10)) + 1, 1))),'not_applicable')AS CHAR(45)) 'average_response_time_in_working_days'
FROM inq_manager im
There are no errors in executing the select statement which gives the average response time excluding the weekends but when I try to insert the above to my table the error is given.
The data type of the tbl_dashboard is avg_response char(45)
How can I overcome this . Please help
I am not sure this will matter, but it is worth a shot. And i'll delete this if it doesn't help but maybe
INSERT INTO tbl_dashboard (avg_response) VALUES
(SELECT cast(ifnull(floor(avg(5 * (DATEDIFF(substring(im.inq_managerreply,-10), im.inq_managerdate) DIV 7)
+ MID('0123444401233334012222340111123400001234000123440',
7 * WEEKDAY(im.inq_managerdate) + WEEKDAY(substring(im.inq_managerreply,-10)) + 1, 1))),'not_applicable')AS CHAR(45)) 'average_response_time_in_working_days'
FROM inq_manager im)
I have an INSERT INTO which works fine with the parameters as constants:
INSERT INTO FinalValidityCodes
(tblReceivedSamplersID, Substudy, Location, FinalValidityCode, DateTimeProcessed)
SELECT ID, true, 'I', 0, now()
FROM tblReceivedSamplers
WHERE (SampleID = ?)
This would affect 1 row (as expected)
Yet if I change the query to use parameters it will allow it to run but will never affect any rows.
INSERT INTO FinalValidityCodes
(tblReceivedSamplersID, Substudy, Location, FinalValidityCode, DateTimeProcessed)
SELECT ID, ?, ?, ?, ?
FROM tblReceivedSamplers
WHERE (SampleID = ?)
What is the difference and why, when I use parameters, does the Insert, seemingly, fail?
Edit:
SampleID is a text datatype.
It looks like the purpose of that INSERT is to add a single row to FinalValidityCodes with values for 5 fields. However, 4 of those values will be supplied directly by query parameters, and ID/tblReceivedSamplersID will be derived from another parameter.
So I would try a DLookup() expression to get the ID (using the parameter for SampleID), and insert that value along with the other 4 parameter values. Here is an untested guess.
INSERT INTO FinalValidityCodes (
tblReceivedSamplersID,
Substudy,
Location,
FinalValidityCode,
DateTimeProcessed
)
VALUES (
DLookup("ID", "tblReceivedSamplers", "SampleID ='" & param1 & "'"),
param2,
param3,
param4,
param5
);