【问题标题】:Send values to the database, don't insert duplicates将值发送到数据库,不要插入重复项
【发布时间】:2018-07-04 07:15:25
【问题描述】:

需要检查TextBox中的值是否已经在数据库中,如果没有则再次保存在数据库中。

这是文本框代码:

 <tr>
        <td>
            <asp:Label ID="lblProductConstruction" runat="server" Text="Product Construction:" Font-Names="Open Sans"></asp:Label></td>
        <td>
            <asp:TextBox ID="txtProductConstruction" runat="server"  Font-Names="Merriweather" margin-Left="100px" ></asp:TextBox><br />
        </td>
    </tr>
    <tr>

保存按钮:

<input type="button" class="button" id="myButton" value="Save"/>

Ajax 按钮点击:

 $(function () {

             $('#myButton').on('click', function () {

                 var lvl = $('#MainContent_txtProductConstruction').val()

                 $.ajax({
                     type: "POST",
                     url: "NewProductConstruction.aspx/GetCollection",

                     data: JSON.stringify({'lvl': lvl }),

                     contentType: "application/json; charset=utf-8",
                     dataType: "json",

                     success: function (response) {
                         alert("Saved successfully.");
                         console.log(response);
                         location.reload(true);

                     },
                     error: function (response) {
                         alert("Not Saved!");
                         console.log(response);
                         location.reload(true);
                     }

                 });

             });

         });

获取值并将该参数(@ObjekatName)发送到数据库的WebMethod:

[WebMethod(EnableSession = true)]
        public static void GetCollection(string lvl)
        {

              string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(conn))

                try
                {
                    connection.Open();
                    SqlCommand cmdCount = new SqlCommand("getDuplicate", connection);
                    cmdCount.CommandType = CommandType.StoredProcedure;
                    cmdCount.Parameters.AddWithValue("@ObjekatName", lvl);
                    cmdCount.ExecuteNonQuery();
                    int count = (int)cmdCount.ExecuteScalar();

                    if (count > 0)
                    {
                        connection.Close();
                    }
                    else
                    {
                        SqlCommand cmdProc = new SqlCommand("InsertObjekat", connection);
                        cmdProc.CommandType = CommandType.StoredProcedure;
                        cmdProc.Parameters.AddWithValue("@ObjekatName", lvl);
                        cmdProc.ExecuteNonQuery();
                        //strMsg = "Saved successfully.";
                    }

                }
                catch
                {


                }
                finally
                {
                    connection.Close();

                }

            return;

第一个过程是一个尝试在数据库中查找值的选择。 如果此选择找到某些内容,则 Count 必须大于 0,这应该关闭连接。 如果 select 没有返回任何东西,则必须将这个新值插入到数据库中。

我已经执行并测试了这些存储过程,它们运行良好。 问题出在 C# 中,我认为我在这里做错了,这不能正常工作。 有人可以帮我处理 c# 部分吗? 顺便说一句:Ajax 工作正常,WebMethod 正确获取值

提前致谢!

【问题讨论】:

  • 能否提供程序
  • 找到了解决方案,谢谢!
  • 那是什么问题???
  • 当数据库中没有值时,它返回 NULL 并且此代码帮助 if (count == null) 然后插入新值。
  • 在存储过程中你可以这样做if exists(select * from table)begin select 1 end else begin select -1 end...记住 null 不是建议的方式...您可以轻松地在数据库中处理并且您编写的代码将按原样工作

标签: c# webmethod


【解决方案1】:

这行代码可能有问题

 cmdCount.ExecuteNonQuery();
  int count = (int)cmdCount.ExecuteScalar();

按照这个它命令两次executenonquery然后executescalar

根据您的要求,应该只有一个电话是ExecuteScalar,所以注释掉ExecuteNonQuery

  //cmdCount.ExecuteNonQuery(); comment not needed 
  int count = (int)cmdCount.ExecuteScalar();

【讨论】:

  • 我这样做了,但成功了。如果 (count > 0) 问题是对象引用未设置为对象的实例,则它可以过去。
  • @freej17 - 你能告诉你程序'getDuplicate'..这有助于解决它
【解决方案2】:

您可以检查重复项并在同一过程中插入值,而不是从 C# 执行两次。

            CREATE OR REPLACE PROCEDURE getDuplicate (ObjekatName IN VARCHAR2)
            AS
               V_COUNT   NUMBER;
            BEGIN
               SELECT   COUNT (1)
                 INTO   V_COUNT
                 FROM   TABLENAME
                WHERE   CatName = ObjekatName;

               IF (V_COUNT = 0)
               THEN
                  **-- insert command**

               END IF;
            END;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 2020-07-22
    • 1970-01-01
    相关资源
    最近更新 更多