在c#中工作三层,但我的插入查询不工作
本文关键字:工作 我的 插入 查询 三层 | 更新日期: 2023-09-27 18:13:18
访问层:
public bool AddStudent(string busStudentFullName, string busStudentFatherName)
{
con = new SqlCeConnection();
con.ConnectionString = "data source = C:''Users''hasni''Documents''Visual Studio 2010''Projects''UniversityManagementSystem''UniversityManagementSystem''UniversityDB.sdf";
con.Open();
ds1 = new DataSet();
//DataTable t = new DataTable();
// string sql = "SELECT * from AdminPassword where Admin Name ='" + AdminNameLogintextBox.Text + "' and Password='" + PasswordLogintextBox.Text + "'";
//string qry = "SELECT * FROM Students";
// string sql = "SELECT * from AdminPassword where Admin Name ='" + AdminNameLogintextBox.Text + "' and Password='" + PasswordLogintextBox.Text + "'";
string sql = "SELECT * FROM Students";
da = new SqlCeDataAdapter(sql, con);
//da = new SqlCeDataAdapter();
//DataTable t = new DataTable();
//da.Fill(t);
da.Fill(ds1, "Students");
//string userNameDB = Convert.ToString(ds1.Tables[0]);
// return userNameDB;
con.Close();
// string busStudentFullName;
//string busStudentFatherName;
string sql2 = "INSERT INTO Students (Student Full Name,Student Father Name) Values('"+ busStudentFullName + "','" + busStudentFatherName + "')";
da = new SqlCeDataAdapter(sql2, con);
da.Fill(ds1, "Students");
con.Close();
return true;
}
业务层:public bool getResponseForAddStudent(string studentName, string studentfathername)
{
bool var = access.AddStudent(studentName, studentfathername);
return var;
}
表示层:
private void AddStudentButton_Click(object sender, EventArgs e)
{
string studentName = StudentNameBox.Text;
string studentfathername = StdFatherNameBox.Text;
bool var = _busGeneral.getResponseForLogin(studentName, studentfathername);
if (var)
{
MessageBox.Show("Student Added");
}
else
{
MessageBox.Show("Sorry");
}
}
您的Sql是无效的,当列的名称中有空格时需要用方括号包围:
INSERT INTO Students (Student Full Name,Student Father Name)
应该改为INSERT INTO Students ([Student Full Name],[Student Father Name])
如果我明白你想做什么,除了括号问题之外,你的代码还有许多问题。
首先,在执行最后一个DataAdapter之前关闭连接。填充操作。由于希望在(重新)用学生数据填充DataAdapter之前插入一条记录,因此必须首先使用SqlCeCommand对象发出ExecuteNonQuery语句。此外,为了避免注入攻击和其他问题,您应该始终使用参数化查询。我还建议用try…Catch处理错误。
这是我认为你想要实现的插入操作(我只检查了语法):
// con.Close();
// string busStudentFullName;
SqlCeCommand cmd = db.CreateCommand();
cmd.CommandText = "INSERT INTO Students ([Student Full Name],[Student Father Name]) Values(@FullName, @DadsName)";
cmd.AddParameter("@FullName", busStudentFullName);
cmd.AddParameter("@DadsName", busStudentFatherName);
cmd.ExecuteNonQuery();
此时,您可以用学生行填充DataAdapter,包括新插入的行。