使用ASP将数据插入SQL Server数据库.NET不能工作



我编写了代码将数据插入数据库,在我单击插入按钮后,没有发生任何事情,也没有错误。我需要帮助。

如果我从前端单击插入按钮,它应该填充数据库。

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 insertAdo
{
public partial class TableInsert : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = @"Data Source=DESKTOP-5JPBK1L;Database=StudentDB; Integrated Security=SSPI";
cnn = new SqlConnection(connectionString);
cnn.Open();
{
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "";
sql = "INSERT INTO  student_table (Student_id, name, Email, Join_date) VALUES (102, 'Jaja Peter', 'Jaja.Peter@gmail.com', '09/30/2021')";
command = new SqlCommand(sql, cnn);
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
}
Response.Write("Insert successful");
cnn.Close();
}
}
}

首先确保你的前端UI按钮的Click事件是连接的,就像下面在你的aspx页面。

<asp:Button id="Button1"
Text="Click here for inserting..."
OnClick="Button1_Click" 
runat="server"/>

之后在你的。cs代码文件中做如下修改:

string connectionString = @"Data Source=DESKTOP-5JPBK1L;Database=StudentDB; Integrated Security=SSPI";
string sql = "Insert into student_table(Student_id,name,Email,Join_date) values(102,'Jaja Peter','Jaja.Peter@gmail.com','09/30/2021')";
// create connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(sql, cn))
{
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}

使用using块确保您的连接和命令对象被正确处置。

对于学习,这种硬编码值的方式是可以的,但在现实世界的场景中,你需要使用参数,并使用模型类,而不是在你的代码中有连接字符串等。