这篇文章主要介绍了ASP.NET如何连接数据库,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
数据库连接篇
在WEB项目里看到Web.config配置文件,在configuration这行加入下面代码用于和SQL服务器进行连接
<appSettings>
<!-- 数据库连接字符串 -->
<add key="ConnStr" value="Data Source=localhost;database=company;UID=sa;Password=;Persist Security Info=True;" />
</appSettings>
数据列表显示篇,如图:
using System;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//引用命名空间:SQL托管,配置文件
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected SqlConnection myconn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
//读取web.config配置文件中的数据库连接字符串,并连接到指定的数据库
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)//判断页面是否第一次运行
{
string strsql="select * from Product";//定义一个数据库的查询字符串
DataSet ds = new DataSet();
myconn.Open();//打开数据库连接
SqlDataAdapter command = new SqlDataAdapter(strsql,myconn);//表示用于填充DataSet 和更新SQL Server 数据库的一组数据命令和一个数据库连接
command.Fill(ds, "Product");
productList.DataSource = ds.Tables[0].DefaultView;
productList.DataBind();
ds.Clear();
myconn.Close();//关闭数据库连接
}
}
protected void grid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
foreach (System.Web.UI.WebControls.HyperLink link in e.Item.Cells[7].Controls)
{
link.Attributes.Add("onClick", "if (!window.confirm('您真的要删除这条记录吗?')){return false;}");
}
}
}
数据添加篇
protected void btnAdd_Click(object sender, EventArgs e)
{
string ProductId = this.txtProductId.Text;
string CategoryId = this.txtCategoryId.Text;
string Name = this.txtName.Text;
string Description = this.txtDescription.Text;
string Price =this.txtPrice.Text;
string sql_Exeits = "select * from Product where ProductId='" + ProductId + "'";
SqlCommand cmd_Exeits = new SqlCommand(sql_Exeits, myconn);
myconn.Open();
SqlDataReader rdr = cmd_Exeits.ExecuteReader();
while (rdr.Read())
{
Response.Write("<script language='JavaScript'>");
Response.Write("alert('对不起,该产品编号已经存在!')");
Response.Write("</script>");
this.txtCategoryId.Text = "";
this.txtDescription.Text = "";
this.txtName.Text = "";
this.txtPrice.Text = "";
this.txtProductId.Text = "";
return;
}
rdr.Close();
string sql_add = "insert into Product(ProductId,CategoryId,Name,Description,Price)values('" + ProductId + "','" + CategoryId + "','" + Name + "','" + Description + "','" + Price + "')";
SqlCommand cmd_add = new SqlCommand(sql_add, myconn);//SqlCommand:表示要对SQL Server数据库执行的一个Transact-SQL语句或存储过程
cmd_add.ExecuteNonQuery();//对连接执行Transact-SQL语句并返回受影响的行数。对于 UPDATE、INSERT 和 DELETE 语句,返回值为该命令所影响的行数。对于所有其他类型的语句,返回值为 -1。如果发生回滚,返回值也为 -1。
myconn.Dispose();
myconn.Close();
}
[/CODE
[COLOR=Red]数据显示篇[/COLOR]
[CODE]
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string id = Request.Params["id"];
if (id == null || id.Trim() == "")
{
Response.Redirect("default.aspx");
Response.End();
}
else
{
string sql_show = "select * from Product Where ProductId=" + id;
SqlCommand cmd_show = new SqlCommand(sql_show, conn);
conn.Open();
SqlDataReader rd_show = cmd_show.ExecuteReader();//使用SqlDataReader对象读取并返回一个记录集
shows.DataSource = rd_show;//指向数据源
shows.DataBind();//绑定数据
rd_show.Close();//关闭SqlDataReader
}
}
}
数据修改篇
protected void btnAdd_Click(object sender, EventArgs e)
{
string ProductId = this.lblProductId.Text;
string CategoryId = this.txtCategoryId.Text;
string Name = this.txtName.Text;
string Description = this.txtDescription.Text;
decimal Price = decimal.Parse(this.txtPrice.Text);
string sql_edit = "update Product set CategoryId='" + CategoryId + "',Name='" + Name + "',Description='" + Description + "',Price='" + Price + "' where ProductId =" + ProductId;
SqlCommand cmd_edit = new SqlCommand(sql_edit, conn);
conn.Open();
cmd_edit.ExecuteNonQuery();
conn.Close();
Response.Write("<script language=javascript>window.alert('保存成功!')</script>");
Response.Redirect("show.aspx?id=" + ProductId);
}
数据删除篇
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string ProductId = Request.Params["id"];
string sql_del = "delete from Product where ProductId=" + ProductId;
SqlCommand cmd_del = new SqlCommand(sql_del, conn);
conn.Open();
cmd_del.ExecuteNonQuery();
conn.Close();
Response.Redirect("default.aspx");
}
}
感谢你能够认真阅读完这篇文章,希望小编分享的“ASP.NET如何连接数据库”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。