Entity Framework(1)

Web.Config配置

<dataConfiguration defaultDatabase="strConn">

        <providerMappings>

            <add databaseType="Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="System.Data.SqlClient"/>

        </providerMappings>

    </dataConfiguration>

    <connectionStrings>

        <add name="strConn" connectionString="Data Source=.;Initial Catalog=test_DB;Uid=test;Pwd=test001" providerName="System.Data.SqlClient"/>

    </connectionStrings>

 DBHelper类:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;



using Microsoft.Practices.EnterpriseLibrary.Data;

using System.Data;

using System.Data.Common;



namespace WebAppEF

{

    public class DbHelper

    {

        /// <summary>

        /// 创建Database对象

        /// </summary>

        private static Database database = DatabaseFactory.CreateDatabase("strConn");



        /// <summary>

        /// 返回DataReader

        /// </summary>

        /// <param name="CommendText"></param>

        /// <returns></returns>

        public static IDataReader GetSqlDataReader(string CommendText)

        {

            return database.ExecuteReader(CommandType.Text, CommendText);

        }



        /// <summary>

        /// 执行存储过程

        /// </summary>

        /// <param name="storedProcedureName">存储过程</param>

        /// <param name="param">参数</param>

        /// <returns></returns>

        public static int ExecuteSql(string storedProcedureName, params object[] param)

        {

            DbCommand dbCommand = database.GetStoredProcCommand(storedProcedureName, param);//读取存储过程参数及参数赋值

            return database.ExecuteNonQuery(dbCommand);

        }



        /// <summary>

        /// 执行sql语句

        /// </summary>

        /// <param name="strSql">sql语句</param>

        /// <returns></returns>

        public static int ExecuteSql(string strSql)

        {

            DbCommand dbCommand = database.GetSqlStringCommand(strSql); //sql语句  

            return database.ExecuteNonQuery(dbCommand);

        }

    }

}

调用:

        protected void btnSubmit_Click(object sender, EventArgs e)

        {

            object[] param = { txtItem_id.Text, txtName.Text, DateTime.Now };

            string strSql = "insert tbl_my(item_id,name,log_date) select '"+txtItem_id.Text+"',N'"+txtName.Text+"',getdate()";



            if (DbHelper.ExecuteSql(strSql) > 0)//sql语句

            //if (DbHelper.ExecuteSql("stp_addMy", param) > 0)//调用存储过程

            {

                BindData();

                lblInfo.Text = "<font color=green>添加成功!</font>";

            }

            else

            {

                lblInfo.Text = "<font color=red>发生错误,添加失败!</font>";

            }

        }

你可能感兴趣的:(framework)