Я новичок в написании кода. Пожалуйста, помогите мне найти решение. Вставка команды в мой файл .aspx.cs
не выполняется, поэтому данные не вставляются в БД. Мой код ниже, пожалуйста, помогите:Данные не вставляются в DB
Файл: 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>
Прежде чем что-либо делать, вам нужно прочитать, понять и начать использовать параметризованные запросы. Это пример учебника SQL-инъекции. –
В ваш запрос должен быть вставлен литеральный текст «+ TextBox1.Text +». Вы получаете исключение или просто ничего не вставили? – juharr
Это похоже на * замечательную возможность познакомиться с использованием отладчика. С его помощью вы можете переходить через свой код, по очереди, по мере его выполнения. Это позволяет вам проверить фактическое поведение и значения времени выполнения и более точно увидеть, что происходит на самом деле. Вы найдете этот процесс незаменимым при написании программного обеспечения. – David