0

现在我正在制作一个 C# winForm,我必须使用网格来显示从两个表中检索到的数据以供用户编辑。

表格如下。

学生表:

id int
name char(10)

主题表:

id int
name char(10)

学生科目表:

id int (Pri key, AUTO_INCREMENT)
student_id int 
subject_id int 
mark int

winform中的网格会显示某个学生的科目,例如id = 12345,SQL如下:

select studentsubject.id, subject.name, studentsubject.mark
from subject, studentsubject
where studentsubject.student_id = 12345
and studentsubject.subject_id = subject.id

检索到的数据被放入数据集,然后放入网格中,第一列 (studentsubject.id) 被隐藏。

我使用 datagridview 来做到这一点,并且可以让用户更改标记,为新主题添加新行并通过删除 datagridview 中的一行来删除主题。

但问题是如何将网格中的数据更改回数据库。

我应该使用数据网格来代替吗?

谢谢

4

1 回答 1

0

以下是与您的要求相对应的 UPDATE、INSERT 和 DELETE 命令:

update studentsubject 
set mark = @mark

insert into [subject] (name) 
values (@name); 
insert into studentsubject (student_id, subject_id, mark) 
values (1, @@identity, @mark)

declare @subject_id int; 
select @subject_id = subject_id 
from studentsubject 
where id = @id; 
delete from studentsubject 
where id = @id; 
delete from [subject] 
where id = @subject_id

我建议您使用SqlDataAdapter执行更新,因为它可以根据 DataRow 的状态自动决定执行哪个操作。您只需要执行SqlDataAdapter.Update方法。当然,必须分配SqlDataAdapter.DeleteCommandSqlDataAdapter.InsertCommandSqlDataAdapter.UpdateCommand属性。

这是一个代码片段:

adapter.InsertCommand = connection.CreateCommand();
adapter.InsertCommand.CommandText = "insert into [subject] (name) values (@name); insert into studentsubject (student_id, subject_id, mark) values (1, @@identity, @mark)";
adapter.InsertCommand.Parameters.AddRange(new SqlParameter[] {
    new SqlParameter("@name", SqlDbType.Char, 10, "name"),
    new SqlParameter("@mark", SqlDbType.Int, 1, "mark")
});
adapter.UpdateCommand = connection.CreateCommand();
adapter.UpdateCommand.CommandText = "update studentsubject set mark = @mark";
adapter.UpdateCommand.Parameters.Add("@mark", SqlDbType.Int, 1, "mark");
adapter.DeleteCommand = connection.CreateCommand();
adapter.DeleteCommand.CommandText = "declare @subject_id int; select @subject_id = subject_id from studentsubject where id = @id; delete from studentsubject where id = @id; delete from [subject] where id = @subject_id";
adapter.DeleteCommand.Parameters.Add("@id", SqlDbType.Int, int.MaxValue, "id");
于 2013-06-24T21:21:40.153 回答