一个插入access实例!

1.Class1.cs


--------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data .OleDb ;
using System.Data ;

namespace Mane
{
    public class Class1
    {
        public DataTable selectTable(string sqltext, OleDbConnection con)
        {
            DataTable dt = new DataTable();
            OleDbDataAdapter adp = new OleDbDataAdapter(sqltext, con);
            adp.Fill(dt);
            return dt;
        }

        public void selectcmd(string sqltext, OleDbConnection con)
        {
            OleDbCommand cmd = con.CreateCommand();
            cmd.CommandText = sqltext;
           try
           {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw new SystemException(e.Message);
            }
            finally
            {
                con.Close();
            }
           
        }
    }
}

2.News_add.aspx.cs

 

--------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using Mane;
using System.Data;

namespace Mane.Admin
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                Response.Redirect(Server.MapPath("Login_Admin.aspx"));
            }
            else
            {
                //添加
                Class1 cl = new Class1();
                OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @Server.MapPath("/App_Data/db1.mdb"));
                string Sqlstr = "INSERT INTO News(标题, 作者, 正文,日期) VALUES ('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() +
                                 "','" + FreeTextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "')";
                cl.selectcmd(Sqlstr, con);
                //刷新
                System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('成功!');</script>");
            }
        }
    }
}


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/mane_yao/archive/2010/07/02/5708374.aspx

你可能感兴趣的:(Access)