Skip to content

Commit 8ad8da6

Browse files
authored
Add more code samples for documentation - Transaction and GetSchema (#824)
1 parent bf5969d commit 8ad8da6

5 files changed

+294
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// <Snippet1>
2+
using System;
3+
using System.Data;
4+
using Microsoft.Data.SqlClient;
5+
6+
class Program
7+
{
8+
static void Main(string[] args)
9+
{
10+
string connectionString = "Data Source = localhost; Integrated Security = true; Initial Catalog = AdventureWorks";
11+
12+
using (SqlConnection connection = new SqlConnection(connectionString))
13+
{
14+
connection.Open();
15+
16+
// Specify the restrictions.
17+
string[] restrictions = new string[4];
18+
restrictions[1] = "Sales";
19+
System.Data.DataTable table = connection.GetSchema("Tables", restrictions);
20+
21+
// Display the contents of the table.
22+
DisplayData(table);
23+
Console.WriteLine("Press any key to continue.");
24+
Console.ReadKey();
25+
}
26+
}
27+
28+
private static void DisplayData(System.Data.DataTable table)
29+
{
30+
foreach (System.Data.DataRow row in table.Rows)
31+
{
32+
foreach (System.Data.DataColumn col in table.Columns)
33+
{
34+
Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
35+
}
36+
Console.WriteLine("============================");
37+
}
38+
}
39+
}
40+
// </Snippet1>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// <Snippet1>
2+
using System;
3+
using System.Data;
4+
using Microsoft.Data.SqlClient;
5+
6+
class Program
7+
{
8+
static void Main(string[] args)
9+
{
10+
string connectionString = "Data Source = localhost; Integrated Security = true; Initial Catalog = AdventureWorks";
11+
12+
using (SqlConnection connection = new SqlConnection(connectionString))
13+
{
14+
connection.Open();
15+
DataTable table = connection.GetSchema("Tables");
16+
17+
// Display the contents of the table.
18+
DisplayData(table);
19+
Console.WriteLine("Press any key to continue.");
20+
Console.ReadKey();
21+
}
22+
}
23+
24+
private static void DisplayData(System.Data.DataTable table)
25+
{
26+
foreach (System.Data.DataRow row in table.Rows)
27+
{
28+
foreach (System.Data.DataColumn col in table.Columns)
29+
{
30+
Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
31+
}
32+
Console.WriteLine("============================");
33+
}
34+
}
35+
}
36+
// </Snippet1>
+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// <Snippet1>
2+
using System;
3+
using System.Data;
4+
using Microsoft.Data.SqlClient;
5+
6+
class Program
7+
{
8+
static void Main(string[] args)
9+
{
10+
string connectionString = "Data Source = localhost; Integrated Security = true; Initial Catalog = Northwind";
11+
12+
using (SqlConnection connection = new SqlConnection(connectionString))
13+
{
14+
// Assumes connection is a valid SqlConnection.
15+
SqlDataAdapter adapter = new SqlDataAdapter(
16+
"SELECT CustomerID, CompanyName FROM Customers ORDER BY CustomerID",
17+
connection);
18+
19+
// The Update command checks for optimistic concurrency violations
20+
// in the WHERE clause.
21+
adapter.UpdateCommand = new SqlCommand("UPDATE Customers Set CustomerID = @CustomerID, CompanyName = @CompanyName " +
22+
"WHERE CustomerID = @oldCustomerID AND CompanyName = @oldCompanyName", connection);
23+
adapter.UpdateCommand.Parameters.Add(
24+
"@CustomerID", SqlDbType.NChar, 5, "CustomerID");
25+
adapter.UpdateCommand.Parameters.Add(
26+
"@CompanyName", SqlDbType.NVarChar, 30, "CompanyName");
27+
28+
// Pass the original values to the WHERE clause parameters.
29+
SqlParameter parameter = adapter.UpdateCommand.Parameters.Add(
30+
"@oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
31+
parameter.SourceVersion = DataRowVersion.Original;
32+
parameter = adapter.UpdateCommand.Parameters.Add(
33+
"@oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName");
34+
parameter.SourceVersion = DataRowVersion.Original;
35+
36+
// Add the RowUpdated event handler.
37+
adapter.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated);
38+
39+
DataSet dataSet = new DataSet();
40+
adapter.Fill(dataSet, "Customers");
41+
42+
// Modify the DataSet contents.
43+
adapter.Update(dataSet, "Customers");
44+
45+
foreach (DataRow dataRow in dataSet.Tables["Customers"].Rows)
46+
{
47+
if (dataRow.HasErrors)
48+
Console.WriteLine(dataRow[0] + "\n" + dataRow.RowError);
49+
}
50+
}
51+
}
52+
53+
protected static void OnRowUpdated(object sender, SqlRowUpdatedEventArgs args)
54+
{
55+
if (args.RecordsAffected == 0)
56+
{
57+
args.Row.RowError = "Optimistic Concurrency Violation Encountered";
58+
args.Status = UpdateStatus.SkipCurrentRow;
59+
}
60+
}
61+
}
62+
// </Snippet1>

doc/samples/SqlTransactionLocal.cs

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// <Snippet1>
2+
using System;
3+
using Microsoft.Data.SqlClient;
4+
5+
class Program
6+
{
7+
static void Main(string[] args)
8+
{
9+
string connectionString = "Data Source = localhost; Integrated Security = true; Initial Catalog = AdventureWorks";
10+
11+
using (SqlConnection connection = new SqlConnection(connectionString))
12+
{
13+
connection.Open();
14+
15+
// Start a local transaction.
16+
SqlTransaction sqlTran = connection.BeginTransaction();
17+
18+
// Enlist a command in the current transaction.
19+
SqlCommand command = connection.CreateCommand();
20+
command.Transaction = sqlTran;
21+
22+
try
23+
{
24+
// Execute two separate commands.
25+
command.CommandText =
26+
"INSERT INTO Production.ScrapReason(Name) VALUES('Wrong size')";
27+
command.ExecuteNonQuery();
28+
command.CommandText =
29+
"INSERT INTO Production.ScrapReason(Name) VALUES('Wrong color')";
30+
command.ExecuteNonQuery();
31+
32+
// Commit the transaction.
33+
sqlTran.Commit();
34+
Console.WriteLine("Both records were written to database.");
35+
}
36+
catch (Exception ex)
37+
{
38+
// Handle the exception if the transaction fails to commit.
39+
Console.WriteLine(ex.Message);
40+
41+
try
42+
{
43+
// Attempt to roll back the transaction.
44+
sqlTran.Rollback();
45+
}
46+
catch (Exception exRollback)
47+
{
48+
// Throws an InvalidOperationException if the connection
49+
// is closed or the transaction has already been rolled
50+
// back on the server.
51+
Console.WriteLine(exRollback.Message);
52+
}
53+
}
54+
}
55+
}
56+
}
57+
// </Snippet1>

doc/samples/SqlTransactionScope.cs

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
// <Snippet1>
2+
using System;
3+
using System.Transactions;
4+
using Microsoft.Data.SqlClient;
5+
6+
class Program
7+
{
8+
static void Main(string[] args)
9+
{
10+
string connectionString = "Data Source = localhost; Integrated Security = true; Initial Catalog = AdventureWorks";
11+
12+
string commandText1 = "INSERT INTO Production.ScrapReason(Name) VALUES('Wrong size')";
13+
string commandText2 = "INSERT INTO Production.ScrapReason(Name) VALUES('Wrong color')";
14+
15+
int result = CreateTransactionScope(connectionString, connectionString, commandText1, commandText2);
16+
17+
Console.WriteLine("result = " + result);
18+
}
19+
20+
static public int CreateTransactionScope(string connectString1, string connectString2,
21+
string commandText1, string commandText2)
22+
{
23+
// Initialize the return value to zero and create a StringWriter to display results.
24+
int returnValue = 0;
25+
System.IO.StringWriter writer = new System.IO.StringWriter();
26+
27+
// Create the TransactionScope in which to execute the commands, guaranteeing
28+
// that both commands will commit or roll back as a single unit of work.
29+
using (TransactionScope scope = new TransactionScope())
30+
{
31+
using (SqlConnection connection1 = new SqlConnection(connectString1))
32+
{
33+
try
34+
{
35+
// Opening the connection automatically enlists it in the
36+
// TransactionScope as a lightweight transaction.
37+
connection1.Open();
38+
39+
// Create the SqlCommand object and execute the first command.
40+
SqlCommand command1 = new SqlCommand(commandText1, connection1);
41+
returnValue = command1.ExecuteNonQuery();
42+
writer.WriteLine("Rows to be affected by command1: {0}", returnValue);
43+
44+
// if you get here, this means that command1 succeeded. By nesting
45+
// the using block for connection2 inside that of connection1, you
46+
// conserve server and network resources by opening connection2
47+
// only when there is a chance that the transaction can commit.
48+
using (SqlConnection connection2 = new SqlConnection(connectString2))
49+
try
50+
{
51+
// The transaction is promoted to a full distributed
52+
// transaction when connection2 is opened.
53+
connection2.Open();
54+
55+
// Execute the second command in the second database.
56+
returnValue = 0;
57+
SqlCommand command2 = new SqlCommand(commandText2, connection2);
58+
returnValue = command2.ExecuteNonQuery();
59+
writer.WriteLine("Rows to be affected by command2: {0}", returnValue);
60+
}
61+
catch (Exception ex)
62+
{
63+
// Display information that command2 failed.
64+
writer.WriteLine("returnValue for command2: {0}", returnValue);
65+
writer.WriteLine("Exception Message2: {0}", ex.Message);
66+
}
67+
}
68+
catch (Exception ex)
69+
{
70+
// Display information that command1 failed.
71+
writer.WriteLine("returnValue for command1: {0}", returnValue);
72+
writer.WriteLine("Exception Message1: {0}", ex.Message);
73+
}
74+
}
75+
76+
// If an exception has been thrown, Complete will not
77+
// be called and the transaction is rolled back.
78+
scope.Complete();
79+
}
80+
81+
// The returnValue is greater than 0 if the transaction committed.
82+
if (returnValue > 0)
83+
{
84+
writer.WriteLine("Transaction was committed.");
85+
}
86+
else
87+
{
88+
// You could write additional business logic here, notify the caller by
89+
// throwing a TransactionAbortedException, or log the failure.
90+
writer.WriteLine("Transaction rolled back.");
91+
}
92+
93+
// Display messages.
94+
Console.WriteLine(writer.ToString());
95+
96+
return returnValue;
97+
}
98+
}
99+
// </Snippet1>

0 commit comments

Comments
 (0)