C#两种不同的sql连接写法


        [HttpPost]
        [ActionName("AddDS")]
        public void AddDataSource(DataSources ds)
        {
            SqlConnection myconnection = new SqlConnection();
            myconnection.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

            SqlCommand sqlCmd = new SqlCommand();
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.CommandText = "INSERT INTO Firefly.vw_Data_Sources_E (DataSourceName, Active, SourceURL, KeyOff, Last_ModifiedBy, Last_Modified) Values (@DataSourceName, @Active, @SourceURL, @KeyOff, @Last_ModifiedBy, @Last_Modified)";
            sqlCmd.Connection = myconnection;

            sqlCmd.Parameters.AddWithValue("@DataSourceName", ds.DataSourceName);
            sqlCmd.Parameters.AddWithValue("@Active", ds.Active);
            sqlCmd.Parameters.AddWithValue("@SourceURL", ((Object)ds.SourceURL) ?? DBNull.Value);
            sqlCmd.Parameters.AddWithValue("@KeyOff", ((Object)ds.SourceURL) ?? DBNull.Value);
            sqlCmd.Parameters.AddWithValue("@Last_ModifiedBy", ds.Last_ModifiedBy);
            sqlCmd.Parameters.AddWithValue("@Last_Modified", ds.Last_Modified);

            myconnection.Open();
            int rowInserted = sqlCmd.ExecuteNonQuery();
            myconnection.Close();
        }
SqlConnection myconnection = new SqlConnection();
            myconnection.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

            SqlCommand sqlCmd = new SqlCommand();
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.CommandText = "select distinct Role, PursuitRole, ResourceType, ResourceTypeName  from [Firefly].[vw_Budget_HoursDollars_Ref]";
            sqlCmd.Connection = myconnection;

            myconnection.Open();
            reader = sqlCmd.ExecuteReader();

            while (reader.Read())
            {

                budgetHoursDollarsRefList.Add(new Budget_HoursDollars_Ref
                {
                    Role = Convert.ToInt32(reader.GetValue(0)),
                    PursuitRole = reader.GetValue(1).ToString(),
                    ResourceType = Convert.ToInt32(reader.GetValue(2)),
                    ResouceTypeName = reader.GetValue(3).ToString()
                });
            }

            reader.Close();
            sqlCmd.Dispose();
            myconnection.Close();
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容