【问题标题】:Unable to insert DateTime format into database无法将 DateTime 格式插入数据库
【发布时间】:2012-07-05 09:09:58
【问题描述】:

我无法将 DateTime 插入我的数据库。我是不是写错了声明?

显然没有日期时间,我可以插入到数据库中

    string dateAndTime = date + " " + time;

    CultureInfo provider = CultureInfo.InvariantCulture;        
    DateTime theDateTime = DateTime.ParseExact(dateAndTime, "d MMMM yyyy hh:mm tt", provider);

//Create a connection, replace the data source name with the name of the SQL Anywhere Demo Database that you installed
            SAConnection myConnection = new SAConnection("UserID=dba;Password=sql;DatabaseName=emaDB;ServerName=emaDB");
            //open the connection 
            ; myConnection.Open();
            //Create a command object. 
            SACommand insertAccount = myConnection.CreateCommand();
            //Specify a query. 
            insertAccount.CommandText = ("INSERT INTO [meetingMinutes] (title,location,perioddate,periodtime,attenders,agenda,accountID,facilitator,datetime) VALUES ('"+title+"','" + location + "', '" + date + "','" + time + "', '" + attender + "','" + agenda + "', '" + accountID + "','" + facilitator + "','" +theDateTime+ "')");
try
    {
        insertAccount.ExecuteNonQuery();

        if (title == "" || agenda == "")
        {
            btnSubmit.Attributes.Add("onclick", "displayIfSuccessfulInsert();");
            //ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please ensure to have a title or agenda!');", true);
        }
        else
        {

            btnSubmit.Attributes.Add("onclick", "displayIfSuccessfulInsert();");
            Response.Redirect("HomePage.aspx");
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Redit", "alert('Minutes Created!'); window.location='" + Request.ApplicationPath + "/HomePage.aspx';", true);
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception);
    }

    finally 
    {            
        myConnection.Close();          
    }

它不会将 SQL 插入到我的数据库中。

PS:例如,theDateTime 的值可能是 7/14/2012 1:35:00 AM。如何将其插入数据库??

【问题讨论】:

  • 您尝试将日期时间 formatDateTime theDateTime = DateTime.ParseExact(dateAndTime, "d MMMM yyyy hh:mm tt", provider); 更改为 DateTime theDateTime = DateTime.ParseExact(dateAndTime, "dd MMMM yyyy hh:mm tt", provider);
  • 出现错误:字符串未被识别为有效的日期时间。

标签: c# asp.net date insert sqlanywhere


【解决方案1】:

是的,您应该使用参数 {0}、{1} 等编写查询,然后使用 Parameters.Add

insertAccount.CommandText = ("INSERT INTO [meetingMinutes]  
   (title,location,perioddate,periodtime, ...) 
   VALUES (?,?,?,?,  ... )");
insertAccount.Parameters.Add( ... );

这将确保 SQL 以正确的语法形成;并且还可以防止 SQL 注入攻击。

【讨论】:

  • 没有.CreateParam,你能帮我写一个完整的例子吗?对不起,我的 C# 知识还处于初学者阶段
  • @melvg 抱歉,我对您使用的库感到困惑。 SAConnectionSACommand 来自哪里?
  • 用于数据库的 Sybase iAnywhere 12。
  • 使用 iAnywhere.Data.SQLAnywhere;
  • @melvg 啊,好的。请参阅我更新的答案。我不确定我的语法是否正确(我不熟悉 Sybase iAnywhere),但看起来文档还不错:dcx.sybase.com/1101/en/dbprogramming_en11/…
【解决方案2】:

首先,切勿对 SQL 查询或命令使用字符串连接。使用参数。 如果你将使用参数,那么:

  • 无法进行sql注入
  • 查询文本和计划被缓存,从而提高了性能
  • 以及对您而言重要的是 - 您不必考虑值的格式,只需将 DateTime 变量作为参数传递

还要交叉检查您的 DB 列是否具有 datetime2 类型,否则您很可能无法存储小于 1758 年 1 月 1 日的值(例如 DateTime.MinValue)。

【讨论】:

  • 不,Sybase Anywhere DB 没有 datetime2 类型。只有 datetime 和 datetimeoffset
  • 我不熟悉 Sybase Anywhere DB,但如果您指定的 DateTime 值小于 1758 年 1 月 1 日,最好检查一下 DB 驱动程序会做什么。无论如何,使用带参数的 sql 命令 = )
【解决方案3】:

不要在你的日期使用引号,删除所有使用日期的引号

change ,'" +theDateTime+ "') to ," +theDateTime+ ") 

并且还保护你的 sql 导致它不保存用于 SQL 注入

【讨论】:

  • 照你说的做了,但仍然没有重定向。 :S
猜你喜欢
  • 2015-09-23
  • 2012-04-13
  • 2013-05-05
  • 2023-03-19
  • 2017-05-12
  • 2013-03-02
相关资源
最近更新 更多