这是我第一次使用 sql 和 asp.net。我正在研究一些示例,以确保我拥有所需的所有基础知识。我正在浏览一个教程,并且一切都应该正常工作,但我收到了一个 .ExecuteNonQuery() 错误。SqlException 未被用户代码处理 // 关键字“表”附近的语法不正确。
如果您有任何指示,请告诉我。我把教程工作了两次,我确定我在这里做错了什么。-谢谢
.CS 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace WebSite
{
public partial class _default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Table values('" + txtfName.Text + "','" + txtlName.Text + "','" + txtpNumber.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Your DATA has been submitted";
txtpNumber.Text = "";
txtlName.Text = "";
txtfName.Text = "";
}
}
}
.aspx 文件:
<form id="form1" runat="server">
<div class="auto-style1">
<strong>Insert data into Database<br />
<br />
</strong>
</div>
<table align="center" class="auto-style2">
<tr>
<td class="auto-style3">First Name:</td>
<td class="auto-style4">
<asp:TextBox ID="txtfName" runat="server" Width="250px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">Last Name:</td>
<td class="auto-style4">
<asp:TextBox ID="txtlName" runat="server" Width="250px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">Phone Number:</td>
<td class="auto-style4">
<asp:TextBox ID="txtpNumber" runat="server" Width="250px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3"> </td>
<td class="auto-style4">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" Width="150px" />
</td>
</tr>
</table>
<br />
<br />
<asp:Label ID="Label1" runat="server" ForeColor="#663300" style="text-align: center" Visible="False"></asp:Label>
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
</form>
SQL 数据库:
CREATE TABLE [dbo].[Table] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[fName] VARCHAR (50) NOT NULL,
[lName] VARCHAR (50) NOT NULL,
[pNumber] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);