【问题标题】:Month not increasing after Increment of a Year in SQL Server using C#使用 C# 在 SQL Server 中增加一年后月份不增加
【发布时间】:2019-02-02 19:59:58
【问题描述】:

我将每笔交易的到期日保存到下个月。它适用于 2019 年,但不适用于 2020 年等等。

string Due_Date_Sample;
DateTime Due_Date_var;
public static string format = "yyyy-MM-dd";

using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
    string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') AS Due_Date FROM Transactions where Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";

    SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);

    sqlCon.Open();

    SqlDataReader dr = sqlCmd.ExecuteReader();

    while (dr.Read())
    {
        date_control_var = 2;
        Due_Date_Sample = (dr["Due_Date"].ToString());
        Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
    }

    dr.Close();
}

Due_Date_var = Convert.ToDateTime(Due_Date_var.ToString(format)).AddMonths(1);
commandstring1 = "INSERT INTO Transactions (Trans_Code,Plot_Code,Plot_No,Inst_No,Inst_Amt,Status,Due_Date,Balance) values ('"
               + Transaction_Code_var + "','" + Plot_Code_var + "','" + Plot_No_var + "','"
               + Inst_No_var + "','" + Inst_Amt_var + "','Due','" + Due_Date_var.ToString(format) + "','" + (Bal_var - int.Parse(Inst_Amt_var)) + "');";//Saving Transactions

SqlCommand sqlCmd = new SqlCommand(commandstring1, sqlCon);

sqlCon.Open();

SqlDataReader dr = sqlCmd.ExecuteReader();

【问题讨论】:

  • Due_Date_var 最初是如何设置的? format的值是多少?
  • 1.显示Due_Date_varformat 的内容。 2. 始终使用parameterised queries
  • 我也加了
  • 最重要的NEVER EVER通过像您正在做的那样将 SQL 字符串连接在一起来构建您的 SQL 语句它在这里 - 你正在向 SQL 注入攻击 打开你的系统 - 互联网上排名第一的漏洞。学习改用参数化查询!其次:如果你想执行 INSERT 命令 - not 使用 .ExecuteReader(因为你并没有真正阅读结果集) - 但使用 .ExecuteNonQuery() 代替
  • 如果您使用日期,请将它们保留为日期。您多次对它们进行字符串格式化,因此它没有按预期运行也就不足为奇了。您完全有可能只用一个简单的 SQL 语句就可以做到这一点。如果您希望它正常工作,请删除所有日期格式(包括 SQL 中的格式)并重试。还要学习调试,以便您可以在运行时检查变量值

标签: c# sql-server date


【解决方案1】:

我已经使用实体框架测试了你的问题,它工作正常,不需要你写的那么长的代码,微软推荐 EF 用于新的桌面和 Web 应用程序检查使用 EF 的简单代码

using (var context = new ProductionContext())
{

    DateTime PayDate = PaymentDatePicker.Value;  //Payment or Transaction Date 
    DateTime DueDate = PayDate.AddMonths(1);  // due date = Payment date + one month 
    var install = new Instalment();  // object of instalment class/table

   install.PaymentDate = PayDate;
   install.NextDueDate = DueDate;
   context.Instalments.Add(install);
   context.SaveChanges();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 2020-02-14
    相关资源
    最近更新 更多