【问题标题】:why is my insert not inserting a record in database为什么我的插入没有在数据库中插入记录
【发布时间】:2012-11-09 16:20:06
【问题描述】:

我正在尝试使用以下方法将记录插入数据库。我在按钮单击事件中调用此方法,但由于某些原因没有插入记录。

需要插入四个字段:rpttemplateid - 我从另一个数据库表中获取该字段,所有其他字段都只是静态值。

我在下面做错了什么?

public void updatereporttemplate()
{
    string cnn = WebConfigurationManager.ConnectionStrings["Underwriting"].ConnectionString;
    SqlConnection cnn1 = new SqlConnection(cnn);
    cnn1.Open();
    string getrptdesc = "select max(rptdesc) + 1 from report_description where rptdesc < 999 and rptdesc is not null";
    SqlCommand cmd = new SqlCommand(getrptdesc, cnn1);
    SqlDataReader sdr = cmd.ExecuteReader();
    sdr.Read();

    int getcount = int.Parse(sdr[0].ToString());
    sdr.Close();
    string commandtext1 = "INSERT INTO report_template" + "(rpttemplateid,rpttemplatedescr,minsubs,minmebers) " +
          " Values( " + getcount  + "," + "  " + " ,  " +  0  + "," + 0  + ")";
    SqlCommand command1 = new SqlCommand
    {
        CommandText = commandtext1,
        Connection = cnn1

    };

【问题讨论】:

  • 你在哪里执行 INSERT 查询字符串?
  • 我在按钮单击事件中执行插入
  • 不,但是您需要在 command1 对象上调用 execute() 对吗?否则 command1 将如何插入?
  • 你在哪里执行 commandtext1
  • @vamsikirankolla,重要但与此无关,“永远不要相信编写内联参数的开发人员”。 Jon Skeet 使用 SQL/DB 参数。

标签: asp.net sql ado.net


【解决方案1】:

你不见了command1.ExecuteNonQuery();

另外,您是否考虑过在表中使用 IDENTITY 列而不是尝试手动设置计数?如果该页面同时被多人点击怎么办?

【讨论】:

  • 确保您的连接已打开
  • 您的插入语句可能缺少某些内容:尝试为第二个值输入“''”。即引号+单引号+单引号+引号
  • " 值(" + getcount + "," + " '' " + " , " + 0 + "," + 0 + ")";
  • SqlConnection cnn2 = new SqlConnection(cnn); cnn2.Open();字符串 commandtext1 = “插入报告模板”+“(rpttemplateid,rpttemplatedescr,minsubs,minmebers)“+”值(“+getcount+”,“+”''“+”,“+0+”,“+0+” )"; SqlCommand command1 = new SqlCommand(commandtext1,cnn2); command1.ExecuteNonQuery(); cnn2.Close();
【解决方案2】:

你需要打开连接

cnn1.Open();

然后执行命令

command1.ExecuteNonQuery();

【讨论】:

  • 说明:在执行当前网络请求的过程中发生了一个未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。异常详细信息:System.Data.SqlClient.SqlException:“,”附近的语法不正确。源错误:第 145 行:第 146 行:SqlCommand command1 = new SqlCommand(commandtext1,cnn2);第 147 行:command1.ExecuteNonQuery();第 148 行:cnn2.Close();第 149 行:
  • 这是一个sql错误。您没有为命令提供第二列的字段名。你有 " + getcount + "," + " " + " , " + 0 + "," + 0 + ")"; 你看到第一个逗号后面的 " " 了吗?你的 DB 期望那里有一个字段名或值。如果您没有要放在那里的值,请将其更改为 " + getcount + "," + 0 + "," + 0 + ")";
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 2017-05-19
  • 1970-01-01
  • 2013-06-22
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多