SqlDataAdapter에서 스토리지 프로세스 호출

12900 단어 Adapter
대부분의 경우 우리가 데이터베이스에 대한 업데이트, 읽기 등은 저장 과정을 통해 조작된다.저장 프로세스가 더욱 빠르고 조정하기 쉽다.이렇게 하면 SqlDataAdapter에서 저장 프로세스를 어떻게 호출하는지 익혀야 한다. 물론 SqlDataAdapter를 통해 호출하지 않고 앞에서 말한 바와 같이 직접 호출할 수도 있다.
다음은 SqlDataAdapter에서 데이터를 업데이트하는 방법에 대한 예입니다.
프로필에 관해서는 앞의 글을 참고할 수 있습니다
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;



namespace DataDemo

{

    class Program

    {

        private static string GetConnectionStringsConfig(string connectionName)

        {

            string connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();

            Console.WriteLine(connectionString);

            return connectionString;

        }



        public static void ManufactureProductDataTable(DataSet ds)

        {

            DataTable products = new DataTable("Products");

            products.Columns.Add(new DataColumn("ProductID", typeof(int)));

            products.Columns.Add(new DataColumn("ProductName", typeof(string)));

            products.Columns.Add(new DataColumn("SupplierID", typeof(int)));

            products.Columns.Add(new DataColumn("CategoryID", typeof(int)));

            products.Columns.Add(new DataColumn("QuantityPerUnit", typeof(string)));

            products.Columns.Add(new DataColumn("UnitPrice", typeof(decimal)));

            products.Columns.Add(new DataColumn("UnitsInStock", typeof(short)));

            products.Columns.Add(new DataColumn("UnitsOnOrder", typeof(short)));

            products.Columns.Add(new DataColumn("RecordLevel", typeof(short)));

            products.Columns.Add(new DataColumn("Discontinued", typeof(bool)));

            ds.Tables.Add(products);

        }



        private static SqlCommand GenerateSelectCommand(SqlConnection conn)

        {

            SqlCommand cmd = new SqlCommand("RegionSelect", conn);

            cmd.CommandType = CommandType.StoredProcedure;

            cmd.UpdatedRowSource = UpdateRowSource.None;

            return cmd;

        }



        private static SqlCommand GenerateInsertCommand(SqlConnection conn)

        {

            SqlCommand cmd = new SqlCommand("RegionInsert", conn);

            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter para1 = new SqlParameter("@RegionDescription", SqlDbType.NChar);

            para1.Value = "North West";

            cmd.Parameters.Add(para1);

            SqlParameter para2 = new SqlParameter("@RegionID", SqlDbType.Int);

            para2.Direction = ParameterDirection.Output;

            cmd.Parameters.Add(para2);

            cmd.UpdatedRowSource = UpdateRowSource.OutputParameters;

            return cmd;

        }



        static void Main(string[] args)

        {

            string source = GetConnectionStringsConfig("Northwind");



            string select = "SELECT * FROM Products";



            SqlConnection conn = new SqlConnection(source);

            conn.Open();



            // Use customized table

            SqlDataAdapter cmd = new SqlDataAdapter(select, conn);

            DataSet ds = new DataSet();

            ManufactureProductDataTable(ds);

            cmd.Fill(ds, "Products");

            foreach (DataRow row in ds.Tables["Products"].Rows)

                Console.WriteLine("'{0}' from {1}", row[0], row[1]);



            // Use stored procedure on adapter

            DataSet ds2 = new DataSet();

            SqlDataAdapter da2 = new SqlDataAdapter();

            da2.SelectCommand = GenerateSelectCommand(conn);

            da2.Fill(ds2, "Region");

            foreach (DataRow row in ds2.Tables["Region"].Rows)

                Console.WriteLine("'{0}' is {1}", row[0], row[1]);



            // Use dataset to read XML file

            DataSet ds3 = new DataSet();

            ds3.ReadXml(".\\MyData.xml");

            foreach (DataRow row in ds3.Tables[0].Rows)

                Console.WriteLine("'{0}' comes {1}", row[0], row[1]);



            // Insert a row to region table

            DataSet ds4 = new DataSet();

            SqlDataAdapter da3 = new SqlDataAdapter();

            

            da3.InsertCommand = GenerateInsertCommand(conn);

            da3.InsertCommand.ExecuteNonQuery();



            da3.SelectCommand = GenerateSelectCommand(conn);



            da3.Fill(ds4, "Region");



            foreach (DataRow row in ds4.Tables["Region"].Rows)

                Console.WriteLine("'{0}' is {1}", row[0], row[1]);



            // Close SQL connection

            conn.Close();

            Console.ReadKey();

        }

    }

}


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
 
InsertCommand 를 호출할 때 잊지 마십시오.
da3.InsertCommand.ExecuteNonQuery();
그렇지 않으면 실행하지 않지만, selectCommand는 이 말을 쓰지 않아도 된다.
호출 중
da3.InsertCommand.ExecuteNonQuery()
이전에 conn이 오픈된 것을 확보해야 한다. 즉, 이 말은
conn.Open();
처음에 주의하지 않아서 한참 동안 찾았는데 어디가 틀렸는지 모르겠어 o(╯□╰)o
 
다음은 MSDN에서 나온 Sql Data Adapter의 예입니다. 각종command를 보여 줍니다.
public static SqlDataAdapter CreateCustomerAdapter(

    SqlConnection connection)

{

    SqlDataAdapter adapter = new SqlDataAdapter();



    // Create the SelectCommand.

    SqlCommand command = new SqlCommand("SELECT * FROM Customers " +

        "WHERE Country = @Country AND City = @City", connection);



    // Add the parameters for the SelectCommand.

    command.Parameters.Add("@Country", SqlDbType.NVarChar, 15);

    command.Parameters.Add("@City", SqlDbType.NVarChar, 15);



    adapter.SelectCommand = command;



    // Create the InsertCommand.

    command = new SqlCommand(

        "INSERT INTO Customers (CustomerID, CompanyName) " +

        "VALUES (@CustomerID, @CompanyName)", connection);



    // Add the parameters for the InsertCommand.

    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");

    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");



    adapter.InsertCommand = command;



    // Create the UpdateCommand.

    command = new SqlCommand(

        "UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " +

        "WHERE CustomerID = @oldCustomerID", connection);



    // Add the parameters for the UpdateCommand.

    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");

    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");

    SqlParameter parameter = command.Parameters.Add(

        "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID");

    parameter.SourceVersion = DataRowVersion.Original;



    adapter.UpdateCommand = command;



    // Create the DeleteCommand.

    command = new SqlCommand(

        "DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);



    // Add the parameters for the DeleteCommand.

    parameter = command.Parameters.Add(

        "@CustomerID", SqlDbType.NChar, 5, "CustomerID");

    parameter.SourceVersion = DataRowVersion.Original;



    adapter.DeleteCommand = command;



    return adapter;

}




.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

좋은 웹페이지 즐겨찾기