我们可以用ADO.NET来访问SQL Server数据库并将输入插入到数据库中。首先,我们需要在Web.config文件中添加连接字符串,如下所示:
然后,在代码中,我们需要创建一个SqlConnection对象,打开连接并创建一个SqlCommand对象来执行插入操作,如下所示:
using System; using System.Data.SqlClient;
namespace InsertData { public partial class InsertData : System.Web.UI.Page { protected void btnInsert_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString); SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (FirstName, LastName, Age) VALUES (@FirstName, @LastName, @Age)", conn); cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text); cmd.Parameters.AddWithValue("@LastName", txtLastName.Text); cmd.Parameters.AddWithValue("@Age", txtAge.Text); conn.Open(); int result = cmd.ExecuteNonQuery(); conn.Close(); if (result > 0) { lblResult.Text = "Insert successful!"; } } } }
在上面的示例中,我们首先创建了一个SqlConnection对象,然后创建了一个SqlCommand对象来执行插入操作。我们使用AddWithValue方法来添加参数,并用查询字符串指定要插入的值。然后执行ExecuteNonQuery方法来执行插入操作。最后,我们检查插入是否成功,并将结果显示在Label控件中。