Entity Framework(1)

weixin_30924079發表於2020-04-04

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>";
            }
        }

轉載於:https://www.cnblogs.com/myjacky/p/3253003.html

相關文章