《aspnet操作access的mdb数据库》由会员分享,可在线阅读,更多相关《aspnet操作access的mdb数据库(2页珍藏版)》请在金锄头文库上搜索。
1、.NET 与数据库操作 (2004-12-10)一:数据库连接语句:1:从数据库里读取数据(添加: using System.Data.OleDb;)OleDbConnection myConnection = newOleDbConnection( “Provider=Microsoft.Jet.OLEDB.4.0;DataSource= 数据库源” ); /新建连接对象OleDbDataAdapter myCommand = new OleDbDataAdapter(操作数据库语句,myConnection);DataSet ds = new DataSet();/数据集合myComman
2、d.Fill(ds,type);DataTable dt=new DataTable();/数据表dt=ds.Tablestype;TextBox1.Text=dt.Rows01.ToString();/显示一个数据到TextBox12:插入、更新、删除数据到数据库(添加: using System.Data.OleDb;)OleDbConnection myConnection = new OleDbConnection(“ Provider=Microsoft.Jet.OLEDB.4.0;DataSource= 数据库源 );OleDbCommand myCommand = new Ole
3、DbCommand(数据库操作语句,myConnection);myCommand.Connection.Open();myCommand.ExecuteNonQuery();myCommand.Connection.Close();二:数据库操作实例1:实例初始化:数据库名字: db1.mdb表名字: student数据库存放路径:D 盘student 表的字段有: id (自动编号), stu_number (文本), stu_sex (文本), stu_name (文本), stu_address (文本), stu_note (文本) 原始数据:11 ,男,张三,金华,爱好广泛12,女
4、,李红,杭州,学习很好2:数据库源写法:Data Source=数据库存放的路径+数据库名例子: Data Source=D:/db1.mdb3: 数据库操作语句:string str1=“select * from student“ ;/选择stringstr2= “insertintostudent(s tu_number,stu_sex,stu_name,stu_address,stu_note)values( ” +number+“ , ” +sex+“ , ” +name+“ , ” +sddress+ “ , ” +note+“ ) ”;/插入语句string str3=“dele
5、te from student where id=1”;/删除string str4=“update student set stu_sex=男”;请看下页4:向 db1 数据库的student表中添加信息:string str_insert= “insert into student (stu_number,stu_sex,stu_name,stu_address,stu_note) values ( ” +number+“ , ” +sex+“ , ” +name+“ , ” +sddress+ “ , ” +note+“ ) ”;OleDbConnectionmyConnection=n
6、ewOleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0;DataSource=D:/db1.mdb);OleDbCommand myCommand = new OleDbCommand(str_insert,myConnection);myCommand.Connection.Open();myCommand.ExecuteNonQuery();myCommand.Connection.Close();5:从db1 数据库的student表中读取id=1记录的数据string str_select= OleDbConnection“delete f
7、rom student where id=1”;myConnection=newOleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0;DataSource=D:/db1.mdb);OleDbDataAdapter myCommand = new OleDbDataAdapter(str_select,myConnection); DataSet ds = new DataSet();myCommand.Fill(ds,type);DataTable dt=new DataTable();dt=ds.Tablestype;TextBox1.Text=d
8、t.Rows01.ToString();/以下语句显示数据TextBox2.Text=dt.Rows02.ToString();6:在 db1 数据库的student表中,把id=1 的这行记录的地址改为“浙江金华”:string str_update=“update student set stu_address=浙江金华 where id=1”;OleDbConnection myConnection = new OleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0;DataSource=D:/db1.mdb);OleDbCommand myCo
9、mmand = new OleDbCommand(str_update,myConnection);myCommand.Connection.Open();myCommand.ExecuteNonQuery();myCommand.Connection.Close();7:从db1 数据库的student表中删除id=1 的记录string str_de OleDbConnection Source=D:/db1.mdb);lete= “delete from student where id=1”;myConnection=newOleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0;DataOleDbCommand myCommand = new OleDbCommand(str_delete,myConnection); myCommand.Connection.Open();myCommand.ExecuteNonQuery();myCommand.Connection.Close();