以下是一种可能的解决方法,您可以尝试:
确保您的ASP.NET代码中数据库连接字符串和表名的名称是正确的。
检查您的代码是否具有正确的权限,以访问数据库并插入数据。
确保您的代码使用合适的语句拼接和参数化来构建SQL查询,以避免SQL注入攻击。
下面是一个示例代码片段,演示如何将数据插入SQL Server数据库:
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;
namespace WebApplication1 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {
}
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=yourServerName;Initial Catalog=yourDatabaseName;Integrated Security=True";
string insertQuery = "INSERT INTO Customers (CustomerName, ContactName, City, Country) VALUES (@customerName, @contactName, @city, @country)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@customerName", txtCustomerName.Text);
command.Parameters.AddWithValue("@contactName", txtContactName.Text);
command.Parameters.AddWithValue("@city", txtCity.Text);
command.Parameters.AddWithValue("@country", txtCountry.Text);
connection.Open();
int result = command.ExecuteNonQuery();
connection.Close();
if (result > 0)
{
lblMessage.Text = "The record has been added to the database.";
}
else
{
lblMessage.Text = "Failed to add the record to the database.";
}
}
}
}
}