[英]Trying to insert data into a table of a database through c#/asp.net
这段代码在执行sql命令后应该带我到一个页面,而在失败时会向我显示错误页面。 每当我通过表单插入值时,都会带我到错误页面。 不知何故没有插入我的物品。 帮助将不胜感激
public partial class StudentManage : System.Web.UI.Page
{
protected void Add_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString);
con.Open();
// here added "@" to write continuous strind in new line
SqlCommand cmd = new SqlCommand(@"INSERT INTO ManageStudents(StudentName, StudentEmail, StudentAddress, StudentCity) VALUES(@name, @email, @address, @city)",con);
cmd.Parameters.AddWithValue("@name", txtStudentName.Text);
cmd.Parameters.AddWithValue("@email", txtStudentEmail.Text);
cmd.Parameters.AddWithValue("@address", txtStudentAddress.Text);
cmd.Parameters.AddWithValue("@city", txtStudentCity.Text);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da1.Fill(dt2);
if (dt2.Rows.Count > 0)
{
Response.Write("Table Updated");
Response.Redirect("StudentManage.aspx");
}
else
{
Response.Redirect("Error.aspx");
//ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
}
要执行INSERT,UPDATE或DELETE语句,您需要使用ExecuteNonQuery()
方法而不是DataTable。
var result = cmd.ExeuteNonQuery();
if(result > 0)
{
Response.Write("Table Updated");
Response.Redirect("StudentManage.aspx");
}
// ...
我想这是一个测试项目,因为您的代码有三个主要问题,
希望对您有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.