C# MSSQL 連線範例 (精簡版)

C# MSSQL 

TestClass.cs
	string _ConnectionString = WebConfigurationManager.ConnectionStrings["testDb"].ConnectionString.ToString();
	string queryString = SqlData.setTeatSql();                  			//取SQL語法
	string[] DataInArry = {	id ,name };                                           	//參數,順序很重要
	DatabaseConnection db = new DatabaseConnection();                               //建立資料庫物件
	DataTable dt = db.DbConnection(_ConnectionString, queryString, DataInArry);     //連線到資料庫
Web.config
	<configuration>
		<connectionStrings>
			<add name="testDb" connectionString="data source=TREECHAO;initial catalog=MsSqlDataBase;user id=super;password=Abc123456;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
		</connectionStrings> 
		<appSettings>
			<add key="DataBaseType" value="mssql" />
		</appSettings>
	</configuration>
DbF.cs
    public class DatabaseConnection
    {
        //資料庫連線
        //輸入:_ConnectionString:連線字串
        //輸入:queryString:SQL語法
        //輸出:DataTable:資料庫資訊
        //ex:
        public DataTable DbConnection(string _ConnectionString, string queryString, string[] DataInArry)
        {
            DataTable dt;//輸出
            using (SqlConnection conn = new SqlConnection(_ConnectionString))
            {
                SqlCommand cmd = new SqlCommand(queryString, conn);
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Clear();
                //參數設定
                int i = 0;
                foreach (var p in DataInArry)
                {
                    cmd.Parameters.Add(new SqlParameter("@DbData" + i, p));  
                    i++;
                }
                conn.Open();//連線         
                SqlDataReader dr = cmd.ExecuteReader();
                dt = new DataTable();
                dt.Load(dr);
                dr.Close();
                conn.Close();
            }
            return dt;
        }
    }
Sql.cs
    public class SqlData
    {
	var getDataBaseType = WebConfigurationManager.AppSettings["DataBaseType"];
        public static string setTeatSql()
        {
            string SqlData = "";
            if (getDataBaseType() == "mssql")
            {
                SqlData = string.Format(@"
					SELECT * 
					FROM dbo.testDb01 WITH (NOLOCK) 
					WHERE 1 = 1 
					    AMD id = @DbData0
					    AMD name = @DbData1
                ");
            }
            else if (getDataBaseType() == "mysql") { }
            else if (getDataBaseType() == "oracle") { }
            return SqlData;
        }
    }

 

我只是一棵樹