日期:2014-05-17 浏览次数:20570 次
<%@ Page Language="C#" AutoEventWireup="true" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.OleDb" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { DataSet ds = new DataSet(); DataTable dt = new DataTable(); DataRow dr; //以下3行可以不要,因为我们并没有插入自动增加的列的数据。 dt.Columns.Add(new DataColumn("UserId", typeof(System.Int32))); dt.Columns[0].AutoIncrement = true; dt.PrimaryKey = new DataColumn[] { dt.Columns["UserId"] }; //为了说明问题,我们这里设置的字段名称与MDB文件中的可以不一样 dt.Columns.Add(new DataColumn("MyUserName", typeof(System.String))); dt.Columns.Add(new DataColumn("MyPassword", typeof(System.String))); dt.Columns.Add(new DataColumn("MyTitle", typeof(System.String))); //生成示例数据 for (int i = 0; i < 8; i++) { dr = dt.NewRow(); dr["MyUserName"] = "【孟子E章】" + i.ToString(); dr["MyPassword"] = "http://dotnet.aspx.cc/Default.aspx?id=" + i.ToString(); dr["MyTitle"] = "net_lover" + i.ToString(); dt.Rows.Add(dr); } ds.Tables.Add(dt); //数据库连接字符串 String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|aspxWeb2.mdb;"; using (OleDbConnection connection = new OleDbConnection(connectionString)) { OleDbDataAdapter adapter = new OleDbDataAdapter(); //定义插入数据的方法,注意字段名称与DataSet里面的差异 adapter.InsertCommand = new OleDbCommand("Insert Into TestTable([UserName],[Password],[Title]) values(@UserName,@Password,@Title)", connection); OleDbParameter UserName = new OleDbParameter("@UserName", OleDbType.LongVarWChar, 1073741823, "MyUserName"); //这里的字段名称与DataSet里面的对应。 adapter.InsertCommand.Parameters.Add(UserName); OleDbParameter Password = new OleDbParameter("@Password", OleDbType.LongVarWChar, 1073741823, "MyPassword"); adapter.InsertCommand.Parameters.Add(Password); OleDbParameter Title = new OleDbParameter("@Title", OleDbType.LongVarWChar, 255, "MyTitle"); adapter.InsertCommand.Parameters.Add(Title); adapter.TableMappings.Add("Table",ds.Tables[0].TableName); OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter); builder.QuotePrefix = "["; builder.QuoteSuffix = "]"; adapter.Update(ds); } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> </form> </body>