Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将数据插入数据库_C#_Asp.net - Fatal编程技术网

C# 如何将数据插入数据库

C# 如何将数据插入数据库,c#,asp.net,C#,Asp.net,我一直在网上看不同的人对如何做的解释 使用asp.net和C#插入数据,但到目前为止,我尝试过的所有不同方法都不起作用,为什么当我单击将数据插入数据库时,我的按钮不起作用?另外,如何区分文本框和下拉列表,我会使用当前使用的ddl.selecteditem吗?这是最好的方法吗?我看过的大部分在线源代码和教程都是关于GridView的,我只是无法有效地将其转换为我所需要的 这是我的HTML </td> <td style="height:

我一直在网上看不同的人对如何做的解释 使用asp.net和C#插入数据,但到目前为止,我尝试过的所有不同方法都不起作用,为什么当我单击将数据插入数据库时,我的按钮不起作用?另外,如何区分文本框和下拉列表,我会使用当前使用的ddl.selecteditem吗?这是最好的方法吗?我看过的大部分在线源代码和教程都是关于GridView的,我只是无法有效地将其转换为我所需要的

这是我的HTML

           </td>
           <td style="height: 51px; width: 377px; font-weight: bold;">
               Project Tester
           </td>
           <td>
               <asp:DropDownList ID="ddlTester" runat="server"
                    DataTextField="" Width="203px" DataBound="ddlTester_DataBound"
                   AutoPostBack="False">
               </asp:DropDownList>
               &nbsp;
               <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:ProjectsAndTasksTestConnectionString %>' 
                   SelectCommand="SELECT [TesterName] FROM [Users] ORDER BY [TesterName]">
               </asp:SqlDataSource>
           </td>
       </tr>
       <tr>
           <td>
               &nbsp;
           </td>
           <td style="height: 51px; width: 377px; font-weight: bold;">
               Project Name&nbsp;
           </td>
           <td>
               <asp:TextBox ID="txtProjectName" runat="server" Width="200px"></asp:TextBox>
               &nbsp;
           </td>
       </tr>
       <tr>
           <td style="height: 51px">
               &nbsp;
           </td>
           <td style="height: 51px; width: 377px; font-weight: bold;">
               Project Description</td>
           <td style="height: 51px">
               <asp:TextBox ID="txtProjectDesc" runat="server" TextMode="MultiLine" Height="105px" Width="237px"></asp:TextBox>
               &nbsp;
           </td>
       </tr>
       <tr>
           <td>
               &nbsp;</td>
           <td style="height: 51px; width: 377px; font-weight: bold;">
               Assigned Date</td>
           <td>
               <asp:TextBox ID="txtStartDate" runat="server" Width="200px"></asp:TextBox>
           </td>
       </tr>
       <tr>
           <td>
               &nbsp;</td>
           <td style="height: 51px; width: 377px; font-weight: bold;">
               Due Date</td>
           <td>
               <asp:TextBox ID="txtEndDate" runat="server" Width="200px"></asp:TextBox>
           </td>
       </tr>
        <tr>
           <td>
               &nbsp;</td>
           <td style="height: 51px; width: 377px; font-weight: bold;">
               Project Platform</td>
           <td>
               <asp:TextBox ID="TxtProjectPlatform" runat="server" Width="200px"></asp:TextBox>
           </td>
       </tr>
       <tr>
           <td>
               &nbsp;</td>
           <td style="height: 51px; width: 377px; font-weight: bold;">
               BIOS</td>
           <td>
               <asp:TextBox ID="TxtBios" runat="server" Width="200px"></asp:TextBox>
           </td>
       </tr>
       <tr>
           <td>
               &nbsp;</td>
           <td style="height: 51px; width: 377px; font-weight: bold;">
               PCH</td>
           <td>
               <asp:TextBox ID="TxtPch" runat="server" Width="200px"></asp:TextBox>
           </td>
       </tr>
       <tr>
           <td>
               &nbsp;</td>
           <td style="height: 51px; width: 377px; font-weight: bold;">
               PROC</td>
           <td>
               <asp:TextBox ID="TxtProc" runat="server" Width="200px"></asp:TextBox>
           </td>
       </tr>
        <tr>
           <td>
               &nbsp;</td>
           <td style="height: 51px; width: 377px; font-weight: bold;">
               Forward To</td>
           <td>
               <asp:DropDownList ID="employeeEmailDropDownList" runat="server" 
            Visible="True" 
                   DataSourceID="SqlDataSource2" DataTextField="EmailAddress" DataValueField="EmailAddress" Width="203px">
        </asp:DropDownList>
               <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectsAndTasksTestConnectionString %>"
                   SelectCommand="SELECT [EmailAddress] FROM [Users] ORDER BY [TesterName]"></asp:SqlDataSource></td>    
       </tr>
        <tr>
           <td>
               &nbsp;</td>
           <td>
               &nbsp;</td>
           <td>
               &nbsp;</td>
       </tr>
       <tr>
           <td>
               &nbsp;</td>
           <td style="width: 377px">
               &nbsp;</td>
           <td>
               <asp:Button ID="Button1" runat="server" onclick="CreateProject_Click"  
                   Text="Create Project" Font-Bold="true" Height="45px" Width="198px" />
               <asp:Label ID="errorLabel" runat="server" ForeColor="Red"></asp:Label>
               <asp:Label ID="successLabel" runat="server" ForeColor="Green"></asp:Label>
           </td>
       </tr>
       <tr>
           <td style="height: 29px">
               </td>
           <td style="height: 29px; width: 377px;">
               </td>
           <td style="height: 29px">
               </td>
       </tr>
   </table>
    </asp:Panel>

</asp:Content>
我知道我需要使用.Parameters来防止可能的MySQL注入,但除此之外,我还不熟悉asp.net和C

如果(!IsPostBack)在代码周围,否则会将数据插入数据库,但到达该事件的唯一方法(除了直接从C#调用)是单击按钮并导致回发

您需要从该方法中删除if语句,它应该可以工作

如果您在代码中包含了这些内容,然后进行了修改,您会很快注意到这一点。如果您对程序流有任何疑问,请设置一个断点并逐行遍历代码

其他一些注意事项:

  • 您应该将连接字符串移动到配置文件中,例如
    web.config
    。如果你曾经需要更新它,这使你不必重建网站。您可以通过
    ConfigurationManager.ConnectionStrings[“connection string name here”]以编程方式访问它。ConnectionString

  • 我将移动创建
    SqlCommand
    并设置参数的代码。在using块之外,然后执行
    insCmd.Connection=cnn。我喜欢尽可能短的时间保持连接畅通。这还允许您使用将命令字符串作为参数的构造函数,因此不需要
    insStmt
    变量

  • Web表单没有像WPF或WCF那样的
    MessageBox
    类。相反,当页面在客户端上完成加载时,您可以让它执行一些JavaScript。现在,一个简单的
    alert()
    就可以了,但最终你可能会用类似的东西来修饰它

  • 您可以使用隐式类型变量
    var
    ,而不是为变量显式设置类型。这使得代码更短,更易于阅读,如果以后更改类型,则更易于重构。而且它实际上没有任何缺点

  • 您应该在insert命令执行过程中使用try/catch来捕获任何问题,并可能在某个地方记录错误,然后向客户端显示一个通用的“对不起,发生了意外错误”

  • 传递到参数中的变量大部分为TextBox类型。这意味着您需要访问它们的
    .Text
    属性才能获取输入的文本

  • 如果DateAssigned和DueDate是数据库中的日期类型,则需要使用
    DateTime.TryParse
    确保它们是表示日期的有效字符串。如果格式不正确,则向客户端显示错误消息,并且不执行insert命令。客户端应该使用一些JavaScript强制将输入的日期转换为正确的格式(但不要依赖它,以防用户禁用JavaScript)

总结一下,我将如何编写事件处理程序:

protected void CreateProject_Click(object sender, EventArgs e)
{ 
    var insCmd = new SqlCommand("INSERT INTO Projects (TesterName, ProjectName, ProjectDescription, DueDate, DateAssigned, Platform) values (@TesterName, @ProjectName,@ProjectDesc, @DueDate, @DateAssigned, @Platform)");
    insCmd.Parameters.AddWithValue("@ProjectName", txtProjectName.Text);
    insCmd.Parameters.AddWithValue("@ProjectDesc", txtProjectDesc.Text);
    insCmd.Parameters.AddWithValue("@TesterName", ddlTester.SelectedItem); //This should probably be .SelectedValue instead
    insCmd.Parameters.AddWithValue("@DateAssigned", txtStartDate.Text);
    insCmd.Parameters.AddWithValue("@DueDate", txtEndDate.Text);
    insCmd.Parameters.AddWithValue("@Platform", TxtProjectPlatform.Text);

    using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDatabase"].ConnectionString))
    {
        insCmd.Connection = cnn;
        cnn.Open();            
        insCmd.ExecuteNonQuery();
        cnn.Close();
    }

   ClientScript.RegisterStartupScript(this.GetType(), "insert-success", "alert('Project created');", true);
}

对于第一个查询,您可以使用
DataTable
和内联查询或storedproc更快地完成它。我还建议您单步执行代码。您是否有任何按钮单击事件或任何其他控件会生成
autopostback
您的逻辑看起来也有点可疑
将.ExecuteNonQuert
代码包装在
中尝试{}捕获(DbException ex){}
以捕获/报告可能发生的任何错误。。不要假设任何一个查询都会成功执行..太棒了!谢谢你的帮助,这帮了我很大的忙,我在web.config文件中有我的连接字符串,出于某种原因,我认为我需要这样写。我以前使用过configurationmanager语句,所以我应该知道我也可以使用它。当我最初试图让它全部工作时,我有一个try/catch设置,但我无法让它工作,所以我删除了它(不应该这样做),我的所有文本框上都有.text,但由于它不工作,我把它们取下看看是否工作,我只是还没有把它们重新打开…数据库中有日期的任何东西都是日期类型,因此,我将使用datetime.tryparse,也比你的链接到诺蒂我一定会实现这一点
protected void CreateProject_Click(object sender, EventArgs e)
{ 
    var insCmd = new SqlCommand("INSERT INTO Projects (TesterName, ProjectName, ProjectDescription, DueDate, DateAssigned, Platform) values (@TesterName, @ProjectName,@ProjectDesc, @DueDate, @DateAssigned, @Platform)");
    insCmd.Parameters.AddWithValue("@ProjectName", txtProjectName.Text);
    insCmd.Parameters.AddWithValue("@ProjectDesc", txtProjectDesc.Text);
    insCmd.Parameters.AddWithValue("@TesterName", ddlTester.SelectedItem); //This should probably be .SelectedValue instead
    insCmd.Parameters.AddWithValue("@DateAssigned", txtStartDate.Text);
    insCmd.Parameters.AddWithValue("@DueDate", txtEndDate.Text);
    insCmd.Parameters.AddWithValue("@Platform", TxtProjectPlatform.Text);

    using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDatabase"].ConnectionString))
    {
        insCmd.Connection = cnn;
        cnn.Open();            
        insCmd.ExecuteNonQuery();
        cnn.Close();
    }

   ClientScript.RegisterStartupScript(this.GetType(), "insert-success", "alert('Project created');", true);
}