【问题标题】:Convert text into date format in Visual Studio 2013 using C# and save it in SQL Server 2014在 Visual Studio 2013 中使用 C# 将文本转换为日期格式并将其保存在 SQL Server 2014 中
【发布时间】:2023-03-02 22:03:02
【问题描述】:

我想在 Visual Studio 2013 中使用 C# 将文本转换为日期格式。唉!我遇到了困难。我还想将这些数据保存在 SQL Server 2014 中。

我的代码是

protected void Button1_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText= "insert into Optical values('"+date.Text+"','"+name.Text+"','"+guardian.Text+"','"+gender.Text+"','"+age.Text+"','"+address.Text+"','"+occupation.Text+"','"+telephone.Text
                +"','"+sph.Text+"','"+cyl.Text+"','"+axis.Text+"','"+prism.Text+"','"+lsph.Text+"','"+lcyl.Text+"','"+laxis.Text+"','"+lprism.Text+"','"+note.Text+"')";
            cmd.ExecuteNonQuery();

            con.Close();
        }

我只想将日期的文本更改为日期格式。请各位大神指导一下,我该怎么做呢?

【问题讨论】:

  • 您的date 文本看起来如何?您可以使用DateTime.ParseExact 将其转换为DateTime,然后您可以使用您想要的格式将其重新转换为string。它看起来怎么样?
  • 使用parametrized insert——你有一个SQL注入漏洞,把'放在note中看看会发生什么。这也将允许您直接传递 DateTime。
  • 你能具体解释一下你遇到了什么“困难”吗?如果您遇到异常情况,请将它们包括在内,或描述您获得的结果以及它们与您想要的结果有何不同。
  • @Alex K,如果我想使用参数化插入,那么我应该在上面提到的代码中做什么?
  • 链接中有很好的例子/解释

标签: c# visual-studio visual-studio-2013 sql-server-2014-express


【解决方案1】:

DateTime.TryParseExact() 可能是更好的选择,但您可以使用正则表达式来确保输入的文本一开始就采用正确的格式。您可以在表单上的占位符中显示您想要的格式(“格式必须是 yyyy-MM-dd”)。要保存在 SQL Server 中,字符串可能类似于“yyyy-MM-dd HH:mm:ss”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-30
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多