如果缺少日期,则从文本框中插入日期,不会出现错误
本文关键字:日期 插入 错误 文本 如果 | 更新日期: 2023-09-27 18:08:07
我有两个文本框和日期。我想将文本转换为日期并将其插入SQL数据库。如果用户没有输入日期,则会出现错误。如何防止错误发生?
try
{
DateTime abc,bsd;
abc = Convert.ToDateTime(textBox1.Text);
bsd = Convert.ToDateTime(textBox2.Text);
SqlConnection con = new SqlConnection();
con.ConnectionString = Scout_DHQ_Manager.Properties.Settings.Default.constring;
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO Table1 (dt,dt2) VALUES('"+abc +"','"+bsd+"')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Details of a new unit is successfully added", " Successfully Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erroe Occure in Connection.", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
您应该对您的输入进行某种验证。如果看起来不像日期,则抛出错误。
你可以使用DateTime.TryParse()。
DateTime date = new DateTime();
if(DateTime.TryParse(textBox1.Text, out date))
{
//The text is a valid date
//Insert it
}
如果你需要一个特定的格式,你可以使用DateTime.TryParseExact()。
您也可以考虑使用参数化查询,因为编写这样的代码将使您容易受到SQL注入攻击。
几点:
- 使用参数来避免格式问题(是DMY格式还是MDY格式?)在这个特殊的情况下你没有sql注入问题,但如果你直接使用用户输入的字符串值,你会有问题。
- 确保这些日期列在你的数据库表中是可空的。
- 确保
abc
和bsd
变量类型为Nullable<DateTime>
(或DateTime?
,两者相同)。 - 仅当文本框中有内容时使用
Convert.ToDateTime
(并捕获错误):empty textbox = null date.
更改如下代码
DateTime? abc, bsd;
if (textBox1.Text != "")
abc = Convert.ToDateTime(textBox1.Text);
else
abc = null;
if (textBox2.Text != "")
bsd = Convert.ToDateTime(textBox2.Text);
else
bsd = null;
记住这些事情:
- 在查询中使用参数
- 为变量使用合理的名称
- 在请求用户 输入时检查值是否为null
- 当在查询中使用引号时,sql将var转换为字符串
考虑到上面的尝试:
try
{
string date1=textBox1.Text;
string date2= textBox2.Text;
if (date1!=null)&&((date2!=null)
{
date1=DateTime.TryParse(date1).ToString("yyyy/MM/dd HH:mm:ss.fff");
date2=DateTime.TryParse(date2).ToString("yyyy/MM/dd HH:mm:ss.fff");
SqlConnection con = new SqlConnection();
using (con)
{
con.ConnectionString = Scout_DHQ_Manager.Properties.Settings.Default.constring;
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO Table1 (dt,dt2) VALUES(@dt1,@dt2)", con);
cmd.Parameters.AddWithValue("@dt1", date1);
cmd.Parameters.AddWithValue("@dt2", date2);
cmd.ExecuteNonQuery();
}
}
else
{
MessageBox.Show("Please Fill in both Textboxes");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erroe Occure in Connection.", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
编辑:改变你的文本框DateTimePicker
控件,可能会导致更好的功能(你永远不会有空值),如果你坚持在你的其他块的文本框,你可以设置在你的参数:
parameter.Value = DBNull.Value;