访问层:
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");
}
}
答案 0 :(得分:0)
当您的名称中的空格需要用方括号括起来时,您的Sql无效:
INSERT INTO Students (Student Full Name,Student Father Name)
而需要是
INSERT INTO Students ([Student Full Name],[Student Father Name])
答案 1 :(得分:0)
如果我理解您的尝试,除了括号问题之外,您的代码还存在许多问题。
首先,在执行最后一次DataAdapter.Fill操作之前关闭连接。 并且由于您希望在使用学生数据填充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,包括新插入的行。