Domanda

Questa è una domanda davvero, davvero stupida, ma sono così abituato a usare linq / altri metodi per connettere e interrogare un database che non ho mai smesso di imparare a farlo da zero.

Domanda: come posso stabilire una connessione manuale a un database e passargli un parametro stringa in C #? (sì, lo so ... pura ignoranza).

Grazie

È stato utile?

Soluzione

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

Altri suggerimenti

Uno utilizza il SqlCommand per eseguire comandi (stored procedure o sql) su SQL Server utilizzando ado.net. I tutorial abbondano.

Ecco un esempio da 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 cose che nessun altro ti ha ancora mostrato:

  • " Stacking " usando dichiarazioni
  • Impostare un tipo di parametro esplicito anziché lasciare che .Net provi a sceglierne uno per te
  • " var " parola chiave

.

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;
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top