0

接入层:

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");
    }
}
4

2 回答 2

0

您的 Sql 无效,当列的名称中有空格时需要用方括号括起来:
INSERT INTO Students (Student Full Name,Student Father Name)
而是需要
INSERT INTO Students ([Student Full Name],[Student Father Name])

于 2013-05-13T22:13:24.967 回答
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,包括新插入的行。

于 2013-05-13T22:46:54.067 回答