ASP关于数据库的操作
来源:互联网 发布:熊猫直播for mac 编辑:程序博客网 时间:2024/05/22 20:55
使用ADO.NET进行数据库的操作
1. 添加SqlClient命名空间
using System.Data.SqlClient;
2. 在Page_Load中获取表,必要时,需要将它绑定给GridView控件
a. 创建一个连接字符串和命令字符串
b. 将字符串传递给SqlDataAdapter的构造函数
c. 创建DataSet的实例
d. 询问DataAdapter来填充DataSet
e. 从DataSet中抽取表格
f. 将表格绑定给GridView
例子:
protected void Page_Load(object sender, EventArgs e){string connectionString="Data Source=服务器地址/ip地址;Initial Catalog=数据库名;User ID=用户名;Password=密码";string commandString="Select * from Customers";SqlDataAdapter dataAdapter=new SqlDataAdapter(commandString, connectionString);DataSet dataSet = new DataSet();dataAdapter.Fill(dataSet, "Customers");DataTable dataTable=dataSet.Tables["Customers"];GridView1.DataSource=dataTable;GridView1.DataBind();}
插入数据:
protected void btnAdd_Click(object sender, EventArgs e){string cmd = @"Insert into Shippers values ('"+this.txtName.Text+"','"+this.txtPhone.Text+"')";UpdateDB(cmd);PopulateGrid();//刷新Grid控件,相当于重新再读取一遍数据库}
编辑数据:
protected void btnEdit_Click(object sender, EventArgs e){int shipperID = GetSelectedRecod();//获取主键的值string cmd = @"Update Shippers set CompanyName = '"+this.txtName.Text+"',Phone='"+this.txtPhone.Text+@"'where ShipperID="+shipperID;UpdateDB(cmd);PopulateGrid();//刷新Grid控件,相当于重新再读取一遍数据库}
删除数据:
protected void btnDelete_Click(object sender, EventArgs e){string cmd = @"delete from Shippers where shipperID = "+GetSelectedRecord();UpdateDB(cmd);PopulateGrid();//刷新Grid控件,相当于重新再读取一遍数据库}
private void UpdateDB(string cmd){string connectionString="Data Source=服务器地址/ip地址;Initial Catalog=数据库名;User ID=用户名;Password=密码";System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConection(connectionString);try{connection.Open();System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();command.Connection = connection;command.CommandText = cmd;command.ExecuteNonQuery();}finally{connection.Close();}}
protected int GetSelectedRecord(){int shipperID = -1;int index = GridView1.SelectedIndex;if (index != -1){DataKey key = GridView1.DataKeys[index];shipperID = (int)key.Value;}return shipperID;}
- ASP关于数据库的操作
- ASP数据库的操作
- 关于ASP连接数据库和数据操作
- 关于数据库的操作
- ASP的数据库指针操作
- ASP操作数据库的函数库
- ASP操作数据库的类
- ASP操作数据库的类
- asp操作数据库的ui
- asp.net随记------关于连接数据库,对数据库进行操作的几个类
- 关于Asp程序操作Access数据库时出现死锁.ldb的解决方法
- 关于写入数据库的操作
- 关于数据库的一些操作
- 关于数据库的相关操作
- Xutils3关于数据库的操作
- 关于数据库操作的事务
- 关于数据库操作的触发器
- ASP.NET中数据库的操作初步----DataSet操作数据库
- Base64编码在PHP中的应用
- 无法再R.java中生成id的问题及R.layout.main中main一直报红错
- Mac,iOS界面中的三维坐标系
- C语言中define的用法
- c#年月日的初始化
- ASP关于数据库的操作
- Matlab绘制二维图
- Java关键字final、static使用总结
- oxford picture dictionary interactive 的安装步骤
- c++中使用python
- 关于Hibernate的oracle主键id生成策略uuid、native和sequence
- java基础--静态
- 原型模式(Prototype Pattern)
- openCV——角点检测