Hi,
How to insert NULL date and time in database MySql with MVC ASP.NET
I have a table in MySQL database that has a column of the Date data format and a column of the Time data.
All two columns are can accept null values, and when I try to insert a null value in Navigate, it works correctly.
However, when I try to do the same from my webpage using a MVC ASPNET on a form and stored procedure, I have this error:
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 'NULL' at line 1
How to do see if it is an empty string, and if so, convert it to a DBNull value for insertion into the database?
Here is my code
Controller
if (!String.IsNullOrEmpty(person.off_day.ToString()))
{
command.Parameters.AddWithValue("toff_day", person.off_day);
}
else
{
command.Parameters.AddWithValue("toff_day", DBNull.Value);
}
if (!String.IsNullOrEmpty(person.off_hrs.ToString()))
{
command.Parameters.AddWithValue("toff_hrs", person.off_hrs);
}
else
{
command.Parameters.AddWithValue("toff_hrs", DBNull.Value);
}
Model
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
[DataType(DataType.Time)]
[RegularExpression(@"^([01][0-9]|2[0-3]):[0-5][0-9]$", ErrorMessage = "hh:mm")]
[Display(Name = "off_hrs")]
public DateTime? off_hrs { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.Date)]
[Column(TypeName = "date")]
[Display(Name = "off_day")]
public DateTime? off_day { get; set; }
View
<div class="row">
<div class="col-md-3">
<div class="form-group">
@Html.LabelFor(m => m.off_day)
@Html.TextBoxFor(m => m.off_day, "{0:dd/MM/yyyy}", new { @Class = "Mytextarea2" })
</div>
</div>
<div class="col-md-3">
<div class="form-group">
@Html.LabelFor(m => m.off_hrs)
@Html.TextBoxFor(m => m.off_hrs, "{0:HH:mm}", new { @Class = "Mytextarea2" })
</div>
</div>
</div>
Stored procedure
CREATE DEFINER=`root`@`%` PROCEDURE `sp_ins`(
IN toff_day DATE,
IN toff_hrs TIME
)
BEGIN
DECLARE 2off_day DATE;
DECLARE 2off_hrs TIME;
SET 2off_day = toff_day;
SET 2off_hrs = toff_hrs;
SET @s = CONCAT('INSERT INTO tbl_ins
SET
off_day = \'',2off_day,'\',
off_hrs = \'',2off_hrs,'\';');
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE `stmt`;
END