|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication4
{
class Program
{
// NOTICE: You MUST replace ‘localhost\baligoal’ with your own DB instance name
const string ConnString = @”Data Source=localhost\baligoal;Initial Catalog=SpTestDB;Integrated Security=True”;
/// <summary>
/// Write a record to DB with stored procedure “WriteData”,
/// and then read it out with stored procedure “ReadData”
/// </summary>
/// <param name=”args”></param>
static void Main(string[] args)
{
const string TestID = “firstid”;
const int TestValue = 500;
// Firstly, write a record with store procedure
using (SqlConnection conn = new SqlConnection(ConnString))
{
// Specify ‘WriteData’ procedure in the params
using (SqlCommand cmd = new SqlCommand(“WriteData”, conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
// The param names are exactly the same with SP WriteData’s
cmd.Parameters.AddWithValue(“@id”, TestID);
cmd.Parameters.AddWithValue(“@SomeValue”, TestValue);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
// If you set BP here, and check you DB table, you should find ‘firstid, 500′ there
Console.WriteLine(“Write: done.”);
// Next, read it out with store procedure
using (SqlConnection conn = new SqlConnection(ConnString)) {
// Specify ‘ReadData’ procedure in the params
using (SqlCommand cmd = new SqlCommand(“ReadData”, conn)) {
cmd.CommandType = System.Data.CommandType.StoredProcedure;
// The param names is exactly the same with SP ReadData’s
cmd.Parameters.AddWithValue(“@id”, TestID);
cmd.Connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read()) {
Console.WriteLine(“read: id – “ + Convert.ToString(reader[0]));
Console.WriteLine(“read: SomeValue – “ + Convert.ToInt32(reader[1]));
}
}
}
}
// End for bp
Console.WriteLine(“exit”);
}
}
}
|