gpt4 book ai didi

c# - 从 ASP.NET 向本地 SQL Server 数据库插入数据

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:50 30 4
gpt4 key购买 nike

我正在尝试将数据从 ASP.NET 插入到本地 SQL Server 数据库中。我正在关注 https://www.youtube.com/watch?v=8bNCfUaJPf8 .也许您可以先尝试观看视频。我遵循完全相同的过程。

代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"  Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
text-align: center;
}
.auto-style2 {
width: 100%;
}
.auto-style3 {
width: 183px;
}
.auto-style4 {
width: 183px;
height: 21px;
}
.auto-style5 {
height: 21px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>

<h2 class="auto-style1">insert data</h2>
<br />

</div>
<table class="auto-style2">
<tr>
<td class="auto-style4">FirstName :</td>
<td class="auto-style5">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">LastName :</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">City :</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">&nbsp;</td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
</td>
</tr>
</table>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" OnSelecting="SqlDataSource1_Selecting" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
</form>
</body>
</html>

这是代码隐藏文件:

 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;

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 (fname, lname, city) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();

TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
}

当我尝试插入数据时,出现此错误:

error

table

最佳答案

Table

是一个SQL关键字,你应该可以使用

[Table] 

将您的表名与关键字区分开来。

所以尝试使用

SqlCommand cmd = new SqlCommand("insert into [Table] (fname, lname, city) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);

关于c# - 从 ASP.NET 向本地 SQL Server 数据库插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45873709/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com