您的位置:首页 > 编程语言 > ASP

Asp.net连接数据库及操作数据库--入门

2020-02-01 00:09 996 查看

1.创建公共类DB--4个方法。GetCon()//连接数据库,sqlEx//执行数据库操作, reDt//返回数据表, reDr//返回SqlDataReader对象 dr

 

///<summary>连接数据库</summary>返回SqlConnection对象
public SqlConnection GetCon()//连接数据库,ConfigurationManager对象的AppSettings属性值获取配置节中连接数据库的字符串实例化SqlConnection对象,并返回该对象
{
return new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString());
}

///<summary>执行SQL语句</summary>
///<param name="cmdstr">SQL语句</param>
///返回int类型,1:成功,0:失败
public int sqlEx(string cmdstr)//通过 SqlCommand对象执行数据库操作
{
SqlConnection con = GetCon();//连接数据库
con.Open();//打开连接

try
{
SqlCommand cmd = new SqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();//执行SQL语句并返回受影响的行数
return 1;
}
catch (Exception e)
{
return 0;
}
finally
{
con.Dispose();
}
}

///<summary>执行SQL查询语句</summary>
///返回DataTable数据表
public DataTable reDt(string cmdstr)//通过SQL语句查询数据库中的数据,并将查询结果存储在DataSet数据集中,最终将该数据集中的查询结果的数据表返回
{

try
{
SqlConnection con = GetCon();
SqlDataAdapter da = new SqlDataAdapter(cmdstr, con);
DataSet ds = new DataSet();
da.Fill(ds);
return (ds.Tables[0]);//返回DataSet对象可以作为数据绑定控件的数据源,可以对其中的数据进行编辑操作
}
catch (Exception)
{

throw;
}

}

///<summary>执行SQL查询语句</summary>
///<param name="str">查询语句</param>
///返回SqlDataReader对象 dr
public SqlDataReader reDr(string str)//将执行此语句的结果存放在一个SqlDataReader对象中,最后将这个SqlDataReader对象返回到调用处
{
try
{
SqlConnection conn = GetCon();
conn.Open();
SqlCommand com = new SqlCommand(str, conn);
SqlDataReader dr = com.ExecuteReader(CommandBehavior.CloseConnection);
return dr;
}
catch (Exception)
{

throw;
}
}

2.使用DB方法,操作数据库(这里以登录为例)

 

protected void btlogin_Click(object sender, EventArgs e)
{

DB db = new DB();
string strusername = this.textusername.Text.Trim();//获取输入的用户名和密码
string strpassword = this.textpassword.Text.Trim();
SqlDataReader dr=db.reDr("select * from userInfo where username='"+strusername+"'and password='"+strpassword+"'");//在数据库中select
dr.Read();
//dr对象读取数据集 if (dr.HasRows) { Session["username"] = dr.GetValue(1); Session["role"] = dr.GetValue(3); Response.Redirect("~/SelectObject.aspx"); } else { Response.Write("<script>alert('登录失败!');location='Login.aspx'</script>"); } dr.Close(); }

 3.在web.config文件中添加下面代码

连接sql的登录用户名
连接sql的登录密码
数据库名称
服务器IP
按实际情况填写
<configuration>
<appSettings>
<add key="ConnectionString" value="User id=连接sql的登录用户名;Password=连接sql的登录密码;Database=数据库名称;Server=服务器IP;Connect Timeout=50;Max Pool size=200;Min pool Size=5"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>

</configuration>

 

转载于:https://www.cnblogs.com/Deerjiadelu/p/7252769.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
diplomat1218 发布了0 篇原创文章 · 获赞 0 · 访问量 225 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: