هل تريد تمرير عبارات SQL كسلاسل إلى mssql باستخدام C#؟

StackOverflow https://stackoverflow.com/questions/604862

  •  03-07-2019
  •  | 
  •  

سؤال

هذا سؤال غبي حقًا ولكنني معتاد جدًا على استخدام linq/طرق أخرى للاتصال بقاعدة البيانات والاستعلام عنها لدرجة أنني لم أتوقف أبدًا عن تعلم كيفية القيام بذلك من الألف إلى الياء.

سؤال:كيف أقوم بإنشاء اتصال يدوي بقاعدة بيانات وتمرير سلسلة معلمات إليها في C#؟(نعم أنا أعلم..جهل محض).

شكرًا

هل كانت مفيدة؟

المحلول

using (SqlConnection conn = new SqlConnection(databaseConnectionString))
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "StoredProcedureName";
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@ID", fileID);

        conn.Open();
        using (SqlDataReader rdr =
                   cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            if (rdr.Read())
            {
                // process row from resultset;
            }
        }
    }
}

نصائح أخرى

واحد يستخدم SqlCommand الطبقة لتنفيذ الأوامر (إما الإجراءات المخزنة أو SQL) في SQL Server باستخدام ado.net. دروس كثيرة.

وهنا مثال من http://www.csharp-station.com /Tutorials/AdoDotNet/Lesson07.aspx

public void RunStoredProcParams()
    {
        SqlConnection conn = null;
        SqlDataReader rdr  = null;

        // typically obtained from user
        // input, but we take a short cut
        string custId = "FURIB";

        Console.WriteLine("\nCustomer Order History:\n");

        try
        {
            // create and open a connection object
            conn = new 
                SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
            conn.Open();

            // 1.  create a command object identifying
            //     the stored procedure
            SqlCommand cmd  = new SqlCommand(
                "CustOrderHist", conn);

            // 2. set the command object so it knows
            //    to execute a stored procedure
            cmd.CommandType = CommandType.StoredProcedure;

            // 3. add parameter to command, which
            //    will be passed to the stored procedure
            cmd.Parameters.Add(
                new SqlParameter("@CustomerID", custId));

            // execute the command
            rdr = cmd.ExecuteReader();

            // iterate through results, printing each to console
            while (rdr.Read())
            {
                Console.WriteLine(
                    "Product: {0,-35} Total: {1,2}",
                    rdr["ProductName"],
                    rdr["Total"]);
            }
        }
        finally
        {
            if (conn != null)
            {
                conn.Close();
            }
            if (rdr != null)
            {
                rdr.Close();
            }
        }   
    }

3 أشياء لم يظهرها لك أحد بعد:

  • "التراص" باستخدام البيانات
  • تعيين نوع معلمة صريح بدلاً من السماح لـ .Net بمحاولة اختيار واحد لك
  • الكلمة المفتاحية "فار".

.

string sql = "MyProcedureName";

using (var cn = new SqlConnection(databaseConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@ParameterName", SqlDbType.VarChar, 50)
        .Value = "MyParameterValue";

    conn.Open();
    using (SqlDataReader rdr =
               cmd.ExecuteReader(CommandBehavior.CloseConnection))
    {
        if (rdr.Read())
        {
            // process row from resultset;
        }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top