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();

你可能感兴趣的:(C#两种不同的sql连接写法)