【发布时间】:2014-04-03 16:58:18
【问题描述】:
我有一个连接到我的 sql 数据库的 asp.net gridview。插入新记录或更新记录时,我会进行一些服务器端检查,然后更新/插入记录或什么也不做。现在我有 2 个方法 CheckArtistExists 和 CheckSongExists 都使用 SqlConnection 对象,例如
public bool CheckSongExists(string _title, int _artistId)
{
int cnt = -1;
using (SqlConnection con = new SqlConnection(CS))
{
//check if song already is exists in DB
SqlCommand cmd = new SqlCommand("Select Count(ID) from tblSong WHERE Title = @newTitle AND ArtistId = @newArtistId;", con);
cmd.Parameters.AddWithValue(@"newTitle", _title);
cmd.Parameters.AddWithValue(@"newArtistId", _artistId);
con.Open();
cnt = (int)cmd.ExecuteScalar();
// if cnt ==1 song exists in DB, of cnt == 0 song doesnt exist
if(cnt == 1)
{ return true; }
else
{ return false; }
}
}
因此,对于 gridview 中的更新功能,我需要建立 3 个 SqlConnections(最多)一个来检查艺术家(如果艺术家不存在,我必须先向 tblArtist 插入一条记录) 然后检查歌曲是否存在(仅当艺术家存在时),最后如果歌曲不存在,我必须插入一条新记录。
我知道数据库连接是宝贵的资源,所以我将它们放在 using 块中。所以我不太确定使用 3 个 SqlConnection 对象来更新/插入是否是好的风格。你能告诉我我的代码是否正常,或者我是否应该使用其他方法来解决这个问题。
谢谢
【问题讨论】: