2个回答
展开全部
话说楼上的方法比较水啊,你这个数据库的连接,打开了没有关啊,资源一直占在那里。另外你的SQL语句也有问题啊。。。
使用using的方法来建立数据库的连接,在使用完资源之后,会自动关闭。
class SqlHelper
{
public static DataTable ExecutDataTable(string sql, params SqlParameter[] parameter)
{
using (SqlConnection conn = new SqlConnection(这个位置写连接字符串))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameter);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataset = new DataSet();
//在dataset中添加刷新行
adapter.Fill(dataset);
return dataset.Tables[0];
}
}
}
}
public Employee GetById(Guid id)//传入的参数,你也可以自己写
{
DataTable table = SqlHelper.ExecutDataTable("select* from tbl_Employee where Id=@id",
new SqlParameter("@id", id));
if (table.Rows.Count <= 0)
{
return null;
}
else if (table.Rows.Count == 1)
{
return ToModel(table.Rows[0]);
}
else
{
throw new Exception("查找出错");
}
}
这里的查找,是按照数据库的ID字段查找的,因为我的数据库定义的ID字段是唯一的,所以我有个判断有没有查找到重复的。
删除的方法如下
public void DeleteById(Guid id)
{
SqlHelper.ExecuteNonQuery("Delete from tbl_Operator where Id = @id",
new SqlParameter("@id", id));
}
class SqlHelper
{
public static int ExecuteNonQuery(string sql,params SqlParameter[] parameter)
{
using (SqlConnection conn= new SqlConnection(连接字符串))
{
conn.Open();
using (SqlCommand cmd= conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameter);
return cmd.ExecuteNonQuery();
//ExecuteNonQuery对连接执行SQL语句并返回受影响行数
}
}
}
}
展开全部
我这个是C#,ASp.net的:
查询后显示在Gridview控件里:
SqlConnection Conn = BaseClass.DBCon();
Conn.Open();
string mystr = "select * from tb_AddBook where textbox.text";
DataSet mydt = new DataSet();
SqlDataAdapter mysda = new SqlDataAdapter(mystr, Conn);
mysda.Fill(mydt);
GvNavol.DataSource = mydt;
GvNavol.DataBind();
删除代码:
protected void btnDelete_Click(object sender, EventArgs e)
{
SqlConnection conn = BaseClass.DBCon();
conn.Open();
string str = "delete tb_AddBook where BookName='"+ddlBookName.SelectedValue+"' and BookAuthor='"+ddlBookAuthor.SelectedValue+"'";
BaseClass.OperateData(str);
Response.Write("<script>alert('删除成功!')</script>");
}
查询后显示在Gridview控件里:
SqlConnection Conn = BaseClass.DBCon();
Conn.Open();
string mystr = "select * from tb_AddBook where textbox.text";
DataSet mydt = new DataSet();
SqlDataAdapter mysda = new SqlDataAdapter(mystr, Conn);
mysda.Fill(mydt);
GvNavol.DataSource = mydt;
GvNavol.DataBind();
删除代码:
protected void btnDelete_Click(object sender, EventArgs e)
{
SqlConnection conn = BaseClass.DBCon();
conn.Open();
string str = "delete tb_AddBook where BookName='"+ddlBookName.SelectedValue+"' and BookAuthor='"+ddlBookAuthor.SelectedValue+"'";
BaseClass.OperateData(str);
Response.Write("<script>alert('删除成功!')</script>");
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询