数据未插入数据库

时间:2016-03-04 19:56:20

标签: c# asp.net sql-server

我是编写代码的新手。请帮我解决一下。我的.aspx.cs文件中的插入命令未执行,因此数据未插入数据库。我的代码如下,请帮助:

文件:Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Data;

    public partial class Default : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\GERP\gerp_support\App_Data\Database1.mdf;Integrated Security=True;User Instance=True");

        protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Attributes.Add("OnClick", "Button1_Click");
        }

        protected void Button1_Click (object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into service_type (type) values('+TextBox1.Text+')";

            cmd.ExecuteNonQuery();
            con.Close();
        }
    }

档案:Deafult.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
<title> GERP and MDM Support</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table> 
 <tr>
   <td> 
    Enter Service Type
    </td>
    <td>
     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
     </td>
     </tr>

     <tr>
     <td colspan="2" align="center">
         <asp:Button ID="Button1" runat="server" Text="Button" onClientclick="Button1_Click" />
     </td>
    </tr>

    </table>
    </div>
    </form>
    </body>
</html>

文件:Deafult.aspx.designer.cs

public partial class Default {

    /// <summary>
    /// form1 control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.HtmlControls.HtmlForm form1;

    /// <summary>
    /// TextBox1 control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.WebControls.TextBox TextBox1;

    /// <summary>
    /// Button1 control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.WebControls.Button Button1;
}

文件:Web.config

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="data source=.\SQLEXPRESS;AttachDbFilename=C:\GERP\gerp_support\gerp_support\App_Data\Database1.mdf;Integrated Security=True;User Instance=True;autocommit=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>

    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>

  </system.web>

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

2 个答案:

答案 0 :(得分:4)

您应该熟悉USING语句。它使数据库工作变得更加痛苦,因为它将处理干净地处理您的对象。此外,您应该在web.config中使用连接字符串,而不是在此处进行硬编码。

这是未经测试但应该非常接近您的需要。我不知道Type的实际数据类型是什么,所以我猜到了。

using(SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\GERP\gerp_support\App_Data\Database1.mdf;Integrated Security=True;User Instance=True"))
{
    con.Open();
    using(SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into service_type (type) values(@Type)";
        cmd.Paramters.Add("@Type", SqlDbType.VarChar, 10).Value = TextBox1.Text;
        cmd.ExecuteNonQuery();
    }
}

答案 1 :(得分:0)

"

之前和之后您遗失了TextBox1.Text
 protected void Button1_Click (object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into service_type (type) values('"+TextBox1.Text.Replace("'","''")+"')";

            cmd.ExecuteNonQuery();
            con.Close();
        }