问题
I am using PostgreSQL as my database. I have an application that is written in
- ASP.NET
- C#
- WebForms
- Using Npgsql with PostgreSQL
I have table named tblAppt in my database, in that table I have a column named appttime that column's Data type is time without time zone
In pgAdmin4's Query Tool if I run the following query:
INSERT INTO tblAppt (appttime) VALUES ('00:30:00');
The results are:
INSERT 0 1 Query returned successfully in 105 msec.
Which means the record was added in my table, in the image you can see I have a row:
Now in my web application I have a text box named txtCustTime, in that text box I enter this value 00:30:00
When I press the submit button I get the following error:
System.InvalidCastException
Can't write CLR type System.String with handler type TimeHandler
Here is a snippet of what happens on the submit:
string insertstmt = "INSERT INTO tblAppt(appttime) VALUES (@ApptTime)";
NpgsqlCommand cmd = new NpgsqlCommand (insertstmt, con);
cmd.Parameters.Add("@ApptTime", NpgsqlDbType.Time );
cmd.Parameters ["@ApptTime"].Value = txtCustTime.Text;
con.Open ();
cmd.ExecuteNonQuery ();
con.Close ();
My question is do I need to cast it because the values in a textbox or use a different datatype, or something else.
PLEASE NOTE: I have other columns in that table that are not time or dates and they submit fine. My problem seems to be specifically to this particular column type.
Additional NOTE:
If I run this on submit the value is added to the database:
string insertstmt = "INSERT INTO tblAppt(appttime) VALUES ('00:30:00')";
NpgsqlCommand cmd = new NpgsqlCommand (insertstmt, con);
con.Open ();
cmd.ExecuteNonQuery ();
con.Close ();
Which tells me my problem I am not understanding has something to do with the parameter.
回答1:
The folks in the comments were correct in that TimeSpan is the way to go. However the documentation was not very clear on how to use it.
The correct way to use TimeSpan for the problem above is:
string insertstmt = "INSERT INTO tblAppt(appttime) VALUES
(@ApptTime)"; NpgsqlCommand cmd = new NpgsqlCommand (insertstmt, con);
TimeSpan thetime = TimeSpan.Parse(txtCustTime.Text);
cmd.Parameters.Add("@ApptTime", NpgsqlDbType.Time ); cmd.Parameters
["@ApptTime"].Value = thetime; con.Open (); cmd.ExecuteNonQuery ();
con.Close ();
I used this link as a reference: https://docs.microsoft.com/en-us/dotnet/api/system.timespan?redirectedfrom=MSDN&view=netframework-4.7.2
来源:https://stackoverflow.com/questions/51877868/what-npgsqldbtype-should-be-used-to-clear-cant-write-clr-type-error