【发布时间】:2013-07-25 18:36:57
【问题描述】:
这些是我在 SQL 数据库中更新学生记录和插入学生记录的函数。
public void UpdateStudent(ref student stu, string rollno) //Update the values to corresponding roll number 'rollno'
{
try
{
connection.Open(); //I have already defined the connection and command
command = new SqlCommand("update student set FirstName='"+stu.Firstname+"',LastName='"+stu.Lastname+"',YearOfAdmission="+stu.Yearofadmission+",Branch='"+stu.Branch+"' where RollNo='"+rollno+"'", connection); //Yearofadmission is int
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
connection.Close();
}
}
public void insertstudent(ref student s)
{
try
{
connection.Open();
command = new SqlCommand("insert into student values('"+s.Rollno+"','"+ s.Firstname+"','"+s.Lastname+"',"+s.Yearofadmission+",'"+s.Branch+"','"+s.Password+"')", connection);
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
connection.Close();
}
}
我将值插入 SQL 表的第二个函数“insertstudent”工作正常,并将值正确插入到数据库表中。但是第一个函数“更新学生”没有更新数据库表中的值。它也没有提供任何错误。 那我哪里错了?
提前致谢!
【问题讨论】:
-
你应该使用命名参数而不是连接一个 sql 字符串。
-
尝试捕获更新中生成的 sql 并在 Management Studio 中运行它以查看它的作用。看起来您的过滤器 rollno 不匹配。
-
一定要切换到sql参数!如果您真的想查看问题,我会在其中放置一个断点并调试到该点。比检查你的命令看看它在做什么。但是,是的,放弃该代码并切换到dotnetperls.com/sqlparameter
-
您对 sql 注入攻击敞开心扉。如果使用您的软件的任何人都知道一点 sql,他们可以轻松地在您的文本框中输入他们自己的查询,并随意删除/更新/插入/混乱您的数据。你应该像 Cam Bruce 所说的那样使用 SqlCommand.Parameters 集合。
标签: c# sql sql-server insert sql-update