SlideShare a Scribd company logo
1 of 14
Download to read offline
P R O D U C T B R I E F
U P D A T E D 9 / 2 4 / 2 0 0 3
C# Code Examples for Connect for .NET SQL Server
Data Provider
Overview
Since the release of our first ADO.NET data providers in June, 2002,
DataDirect Technologies has been fully committed to boosting operation
performance in real-world environments such as SQL Server.
This Product Brief provides code examples that can reduce application
development time by providing working C# source code showing typical
database access tasks in ADO.NET, using the Connect for .NET SQL Server
data provider. To enable the code examples to work, you must create the
sample tables. In addition, you must modify the connection strings in the
examples to work in your environment. Finally, make sure you include the
“using” directive for System.Data and DDTek.SQLServer in your project:
using System.Data;
using DDTek.SQLServer;
The code examples demonstrate:
• Retrieving Data Using a DataReader
• Using a Local Transaction
• Using a Distributed Transaction
• Using the CommandBuilder
• Updating Data in a Dataset
• Calling a Stored Procedure
• Retrieving a Scalar Value
• Retrieving Warning Information
Sample Tables
Many of the samples in this product brief use the emp and dept tables. You
can create the tables using an ISQL script, or by using the data provider.
Creating the sample tables using an ISQL script
The following script can be run in ISQL. See the Microsoft SQL Server
documentation for details.
CREATE TABLE emp (
empno INT PRIMARY KEY,
ename VARCHAR(10),
job VARCHAR(9),
mgr INT NULL,
hiredate DATETIME,
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 2 O F 1 4
sal NUMERIC(7,2),
comm NUMERIC(7,2) NULL,
dept INT)
begin
insert into emp values (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4)
insert into emp values (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3)
insert into emp values (3,'TAFT','SALES I',2,'01-02-1996',25000,500,3)
insert into emp values (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3)
insert into emp values (5,'LINCOLN','TECH',6,'06-23-1994',22500,1400,4)
insert into emp values (6,'GARFIELD','MANAGER',9,'05-01-1993',54000,NULL,4)
insert into emp values (7,'POLK','TECH',6,'09-22-1997',25000,NULL,4)
insert into emp values (8,'GRANT','ENGINEER',10,'03-30-1997',32000,NULL,2)
insert into emp values (9,'JACKSON','CEO',NULL,'01-01-1990',75000,NULL,4)
insert into emp values (10,'FILLMORE','MANAGER',9,'08-09-1994',56000,NULL,2)
insert into emp values (11,'ADAMS','ENGINEER',10,'03-15-1996',34000,NULL,2)
insert into emp values (12,'WASHINGTON','ADMIN',6,'04-16-1998',18000,NULL,4)
insert into emp values (13,'MONROE','ENGINEER',10,'12-03-2000',30000,NULL,2)
insert into emp values (14,'ROOSEVELT','CPA',9,'10-12-1995',35000,NULL,1)
end
CREATE TABLE dept (
deptno INT NOT NULL,
dname VARCHAR(14),
loc VARCHAR(13))
begin
insert into dept values (1,'ACCOUNTING','ST LOUIS')
insert into dept values (2,'RESEARCH','NEW YORK')
insert into dept values (3,'SALES','ATLANTA')
insert into dept values (4, 'OPERATIONS','SEATTLE')
end
Creating the sample tables using the data provider
The sample tables used in this Product Brief can be created with the data
provider, as shown in the following code example:
SQLServerConnection Conn;
Conn = new SQLServerConnection("host=nc-star;port=1433;
User ID=test01;Password=test01; Database Name=Test");
try
{
Conn.Open();
}
catch (SQLServerException ex)
{
// Connection failed
Console.WriteLine(ex.Message);
return;
}
string[] DropTableSQL = {"drop table emp", "drop table dept"};
for (int x=0; x<=1; x++)
{
try
{
// Drop the tables, don't care if they don't exist
SQLServerCommand DBCmd = new SQLServerCommand(DropTableSQL[x], Conn);
DBCmd.ExecuteNonQuery();
}
catch (SQLServerException ex)
{
}
// Create the tables
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 3 O F 1 4
string CreateEmpTableSQL = "CREATE TABLE emp (empno INT PRIMARY KEY NOT NULL,"
+"ename VARCHAR(10) NOT NULL,"
+"job VARCHAR(9) NOT NULL,"
+"mgr INT,"
+"hiredate DATETIME NOT NULL,"
+"sal NUMERIC(7,2) NOT NULL,"
+"comm NUMERIC(7,2),"
+"dept INT NOT NULL)";
string CreateDeptTableSQL = "CREATE TABLE dept ("
+"deptno INT NOT NULL,"
+"dname VARCHAR(14),"
+"loc VARCHAR(13))";
try
{
SQLServerCommand DBCmd = new SQLServerCommand(CreateEmpTableSQL, Conn);
DBCmd.ExecuteNonQuery();
DBCmd.CommandText = CreateDeptTableSQL;
DBCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
//Create tables failed
Console.WriteLine (ex.Message);
return;
}
// Now insert the records
string[] InsertEmpRecordsSQL = {
"insert into emp values (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4)",
"insert into emp values (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3)",
"insert into emp values (3,'TAFT','SALES I',2,'01-02-1996',25000,500,3)",
"insert into emp values (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3)",
"insert into emp values (5,'LINCOLN','TECH',6,'06-23-1994',22500,1400,4)",
"insert into emp values (6,'GARFIELD','MANAGER',9,'05-01-1993',54000,NULL,4)",
"insert into emp values (7,'POLK','TECH',6,'09-22-1997',25000,NULL,4)",
"insert into emp values (8,'GRANT','ENGINEER',10,'03-30-1997',32000,NULL,2)",
"insert into emp values (9,'JACKSON','CEO',NULL,'01-01-1990',75000,NULL,4)",
"insert into emp values (10,'FILLMORE','MANAGER',9,'08-09-1994',56000, NULL,2)",
"insert into emp values (11,'ADAMS','ENGINEER',10,'03-15-1996',34000, NULL,2)",
"insert into emp values (12,'WASHINGTON','ADMIN',6,'04-16-1998',18000,NULL,4)",
"insert into emp values (13,'MONROE','ENGINEER',10,'12-03-2000',30000,NULL,2)",
"insert into emp values (14,'ROOSEVELT','CPA',9,'10-12-1995',35000,NULL,1)"};
string[] InsertDeptRecordsSQL = {
"insert into dept values (1,'ACCOUNTING','ST LOUIS')",
"insert into dept values (2,'RESEARCH','NEW YORK')",
"insert into dept values (3,'SALES','ATLANTA')",
"insert into dept values (4, 'OPERATIONS','SEATTLE')"};
// Insert dept table records first
for (int x = 0; x<InsertDeptRecordsSQL.Length; x++)
{
try
{
SQLServerCommand DBCmd = new SQLServerCommand(InsertDeptRecordsSQL[x], Conn);
DBCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine (ex.Message);
return;
}
}
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 4 O F 1 4
// Now the emp table records
for (int x = 0; x<InsertEmpRecordsSQL.Length; x++)
{
try
{
SQLServerCommand DBCmd = new SQLServerCommand(InsertEmpRecordsSQL[x], Conn);
DBCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine (ex.Message);
return;
}
}
Console.WriteLine ("Tables created Successfully!");
// Close the connection
Conn.Close();
Retrieving Data Using a DataReader
The DataReader provides the fastest but least flexible way to retrieve data
from the database. Data is returned as a read-only, forward-only stream of
data that is returned one record at a time. If you need to retrieve many
records rapidly, using a DataReader would require fewer resources than
using a DataSet, which would need large amounts of memory to hold the
results.
In the following code example, you execute a simple query on a Microsoft
SQL Server database and read the results using a DataReader. This
example uses the emp table.
// Open connection to SQL Server database
SQLServerConnection Conn;
try
{
Conn = new SQLServerConnection("host=nc-star;port=1433;
User ID=test01;Password=test01; Database Name=Test");
Conn.Open();
Console.WriteLine ("Connection successful!");
}
catch (Exception ex)
{
// Connection failed
Console.WriteLine(ex.Message);
return;
}
try
{
// Create a SQL command
string strSQL = "SELECT ename FROM emp WHERE sal>50000";
SQLServerCommand DBCmd = new SQLServerCommand(strSQL, Conn);
SQLServerDataReader myDataReader;
myDataReader = DBCmd.ExecuteReader();
while (myDataReader.Read())
{
Console.WriteLine("High salaries: " + myDataReader["ename"].ToString());
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 5 O F 1 4
}
myDataReader.Close();
// Close the connection
Conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
Using a Local Transaction
The following code example uses the emp table to show how to use a local
transaction:
SQLServerConnection Conn;
Conn = new SQLServerConnection("host=nc-star;port=1433; User ID=test01;
Password=test01;Database Name=Test");
try
{
Conn.Open();
Console.WriteLine ("Connection successful!");
}
catch (Exception ex)
{
// Connection failed
Console.WriteLine(ex.Message);
return;
}
SQLServerCommand DBCmd = new SQLServerCommand();
SQLServerTransaction DBTxn = null;
try
{
DBTxn = Conn.BeginTransaction();
// Set the Connection property of the Command object
DBCmd.Connection = Conn;
// Set the text of the Command to the INSERT statement
DBCmd.CommandText = "insert into emp VALUES
(16,'HAYES','ADMIN',6,'17-APR-2002',18000,NULL,4)";
// Set the transaction property of the Command object
DBCmd.Transaction = DBTxn;
// Execute the statement with ExecuteNonQuery, because we are not
// returning results
DBCmd.ExecuteNonQuery();
// Now commit the transaction
DBTxn.Commit();
// Display any exceptions
Console.WriteLine ("Transaction Committed!");
}
catch (Exception ex)
{
// Display any exceptions
Console.WriteLine (ex.Message);
// If anything failed after the connection was opened, roll back the
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 6 O F 1 4
// transaction
if (DBTxn != null)
{
DBTxn.Rollback();
}
}
// Close the connection
Conn.Close();
Using a Distributed Transaction
The following code shows how to use a distributed transaction across two
connections to two different Microsoft SQL Server servers. The example uses
the emp table.
NOTES:
• When you use distributed transactions, you must add
System.EnterpriseServices to the Solution Reference list. In addition, the
application must be strongly named. To do this, first open a command
window and go to the application directory. Then, run the following
command:
sn –k SolutionName.snk
• Delete the AssemblyInfo.cs file from the Solution.
• Microsoft Distributed Transaction Coordinator must be running on all
clients and servers.
using System;
using System.EnterpriseServices;
using System.Reflection;
using DDTek.SQLServer;
[assembly: ApplicationName("yourapplicationname")]
[assembly: AssemblyKeyFileAttribute(@"....yourapplicationname.snk")]
namespace DistTransaction
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
SQLServerConnection Conn1;
Conn1 = new SQLServerConnection("host=nc-star;port=1433;
User ID=test01;Password=test01;
Database Name=Test;Enlist=true");
SQLServerConnection Conn2;
Conn2 = new SQLServerConnection("host=nc-star;port=1433;
User ID=test07;Password= test07;
Database Name=test;Enlist=true");
try
{
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 7 O F 1 4
DistributedTran myDistributedTran = new DistributedTran();
myDistributedTran.TestDistributedTransaction(Conn1, Conn2);
Console.WriteLine("Success!!");
}
catch (Exception e)
{
System.Console.WriteLine("Error returned: " + e.Message);
}
}
}
/// <summary>
/// To use distributed transactions in .NET, we need a ServicedComponent
/// derived class with transaction attribute declared as "Required".
/// </summary>
[Transaction(TransactionOption.Required) ]
public class DistributedTran : ServicedComponent
{
/// <summary>
/// This method executes two SQL statements.
/// If both are successful, both are committed by DTC after the
/// method finishes. However, if an exception is thrown, both will be
/// rolled back by DTC.
/// </summary>
[AutoComplete]
public void TestDistributedTransaction(SQLServerConnection Conn1,
SQLServerConnection Conn2)
{
// The following Insert statement goes to the first server, orca.
// This Insert statement does not produce any errors.
string DBCmdSql1 = "Insert into emp VALUES
(16,'HAYES','ADMIN',6,'17-NOV-2002',18000,NULL,4)";
string DBCmdSql2 = "Delete from emp WHERE sal > 100000";
try
{
Conn1.Open();
Conn2.Open();
Console.WriteLine ("Connection successful!");
}
catch (Exception ex)
{
// Connection failed
Console.WriteLine(ex.Message);
return;
}
SQLServerCommand DBCmd1 = new SQLServerCommand(DBCmdSql1, Conn1);
SQLServerCommand DBCmd2 = new SQLServerCommand(DBCmdSql2, Conn2);
DBCmd1.ExecuteNonQuery();
DBCmd2.ExecuteNonQuery();
Conn1.Close();
Conn2.Close();
Console.WriteLine("Success!! ");
}
}
}
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 8 O F 1 4
Using the CommandBuilder
A CommandBuilder object can be used to generate the Insert, Update, and
Delete statements for a DataAdapter. The following code example uses the
emp sample table with the CommandBuilder to update a DataSet:
SQLServerConnection Conn;
Conn = new SQLServerConnection("host=nc-star; port=4100;User ID=test01;
Password=test01;Database Name=Test ");
try
{
Conn.Open();
Console.WriteLine ("Connection successful!");
}
catch (Exception ex)
{
// Connection failed
Console.WriteLine(ex.Message);
return;
}
SQLServerDataAdapter myDataAdapter = new SQLServerDataAdapter();
SQLServerCommand DBCmd = new SQLServerCommand("select * from emp",Conn);
myDataAdapter.SelectCommand = DBCmd;
// Set up the CommandBuilder
SQLServerCommandBuilder CommBuild = new SQLServerCommandBuilder(myDataAdapter);
DataSet myDataSet = new DataSet();
try
{
myDataAdapter.Fill(myDataSet);
// Now change the salary of the first employee
DataRow myRow;
myRow = myDataSet.Tables["Table"].Rows[0];
myRow["sal"] = 95000;
// Tell the DataAdapter to resynch with the SQL Server server.
// Without the CommandBuilder, this line would fail.
myDataAdapter.Update(myDataSet);
Console.WriteLine ("Update with CommandBuilder Successful!");
}
catch (Exception ex)
{
// Display any exceptions
Console.WriteLine (ex.Message);
}
// Close the connection
Conn.Close();
Updating Data in a Dataset
When updating a row at the data source, the DataSet uses the SQL provided
in UpdateCommand of the Data Adapter. The Update statement can use
parameters that contain the unique identifier, such as the primary key, and
the columns to be updated, as shown in the following example:
[C#]
string updateSQL As String = "UPDATE emp SET sal = ?, job = ? +
= WHERE empno = ?;
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 9 O F 1 4
The parameterized query statements define the parameters that will be
created. Refer to the DataDirect Connect for .NET User's Guide and
Reference for more information about using parameters with the SQL Server
data provider.
The following code example shows how to provide an UpdateCommand to a
DataAdapter for use in synchronizing changes made to a DataSet with the
actual data on the SQL Server server, using data from the emp table. The
example uses the Parameters.Add method to create the parameters for the
Update statement, fills a DataSet, programmatically makes changes to the
DataSet, then synchronizes the changes back to the database.
SQLServerConnection Conn = new SQLServerConnection("host=nc-star;
port=4100;User ID=test01;Password=test01;Database Name=Test");
try
{
string selectText = "select sal, job, empno from emp";
string updateText = "update emp set sal = ?, job = ? where empno = ?";
SQLServerDataAdapter adapter = new SQLServerDataAdapter(selectText, Conn);
SQLServerCommand updateCommand = new SQLServerCommand(updateText, Conn);
adapter.UpdateCommand = updateCommand;
updateCommand.Parameters.Add("@sal", SQLServerDbType.Int, 15, "SAL");
updateCommand.Parameters.Add("@job", SQLServerDbType.VarChar, 9, "JOB");
updateCommand.Parameters.Add("@empno", SQLServerDbType.Int, 15, "empno");
DataSet myDataSet = new DataSet("emp");
adapter.Fill(myDataSet, "emp");
// Give employee number 11 a promotion and a raise
DataRow changeRow = myDataSet.Tables["emp"].Rows[11];
changeRow["sal"] = "35000";
changeRow["job"] = "MANAGER";
// Send back to database
adapter.Update(myDataSet, "emp");
myDataSet.Dispose();
}
catch (Exception ex)
{
// Display any exceptions
Console.WriteLine (ex.Message);
}
Console.WriteLine("DataSet Updated Successfully!");
// Close the connection
Conn.Close();
Calling a Stored Procedure
You call stored procedures using a Command object. When you issue a
command on a stored procedure, you must set the CommandType of the
Command object to StoredProcedure, or use the ODBC/JDBC escape
syntax. For information on using the ODBC/JDBC escape syntax with the
data provider, refer to the Connect for .NET User’s Guide and Reference.
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 1 0 O F 1 4
The following code shows how to execute a stored procedure on a SQL
Server database and read the results using a DataReader. The sample data
is in the emp table.
Creating the stored procedure
First, execute the following code to create the stored procedure:
// Open connection to SQL Server database
SQLServerConnection Conn;
Conn = new SQLServerConnection("host=nc-star;port=4100;User ID=test01;
Password=test01;Database Name=Test");
try
{
Conn.Open();
Console.WriteLine ("Connection successful!");
}
catch (Exception ex)
{
// Connection failed
Console.WriteLine(ex.Message);
return;
}
string spCreate = "CREATE PROCEDURE GetEmpSalary(@empno int,@sal numeric(7,2) output)AS
SELECT @sal = sal from emp where empno = @empno";
try
{
SQLServerCommand DBCmd=new SQLServerCommand(spCreate, Conn);
DBCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
//Create procedure failed
Console.WriteLine (ex.Message);
return;
}
Console.WriteLine ("Procedure Created Successfully!");
Executing the stored procedure
Now, use the following code example to execute the GetEmpSalary stored
procedure:
// Open connection to SQL Server database
SQLServerConnection Conn;
try
{
Conn = new SQLServerConnection("host=nc-star;port=4100;User ID=test01;
Password=test01;Database Name=Test");
Conn.Open();
Console.WriteLine ("Connection successful!");
}
catch (Exception ex)
{
// Connection failed
Console.WriteLine(ex.Message);
return;
}
// Make a command object for the stored procedure
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 1 1 O F 1 4
// You must set the CommandType of the Command object
// to StoredProcedure
SQLServerCommand DBCmd = new SQLServerCommand("GetEmpSalary",Conn);
DBCmd.CommandType = CommandType.StoredProcedure;
// The stored procedure expects one input and one output parameter
// Define the parameters for the stored procedure
// We don't need to specify the direction of the parameter, since the default is INPUT
DBCmd.Parameters.Add("@empno", SQLServerDbType.Int, 10).Value = 5;
// Output parameter
DBCmd.Parameters.Add("@sal", SQLServerDbType.Numeric, 10).Direction =
ParameterDirection.Output;
SQLServerDataReader myDataReader;
try
{
myDataReader = DBCmd.ExecuteReader();
myDataReader.Close();
}
catch (Exception ex)
{
// Display any exceptions
Console.WriteLine (ex.Message);
}
Console.WriteLine("Procedure Executed Successfully!");
// Close the connection
Conn.Close();
Retrieving a Scalar Value
You can use the ExecuteScalar method of the Command object to return a
single value, such as a sum or a count, from the database. The
ExecuteScalar method returns the value of the first column of the first row of
the result set. If you know the result set has only one row and one column,
you can use this method to speed up retrieval of the value.
The following code example retrieves the number of employees who make
more than $50000. This example uses the emp table.
// Open connection to SQL Server database
SQLServerConnection Conn;
Conn = new SQLServerConnection("host=nc-star;port=4100;User ID=test01;
Password=test01;Database Name=Test");
try
{
Conn.Open();
Console.WriteLine ("Connection successful!");
}
catch (Exception ex)
{
// Connection failed
Console.WriteLine(ex.Message);
return;
}
// Make a command object
SQLServerCommand salCmd = new SQLServerCommand("select count(sal) from emp
where sal>50000",Conn);
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 1 2 O F 1 4
try
{
int count = (int)salCmd.ExecuteScalar();
Console.WriteLine("Count of Salaries >$50,000 : "
+ Convert.ToString(count));
}
catch (Exception ex)
{
// Display any exceptions
Console.WriteLine(ex.Message);
}
// Close the connection
Conn.Close();
Retrieving Warning Information
The data provider handles database server warnings through the
InfoMessage delegates on the Connection objects.
The following example shows how to retrieve a warning generated by a
Microsoft SQL Server server:
// Define an event handler
public void myHandler(object sender, SQLServerInfoMessageEventArgs e)
{
// Display any warnings
Console.WriteLine ("Warning Returned: " + e.Message);
}
Add the following code to a method and call it:
// Define an event handler
public void myHandler(object sender, SQLServerInfoMessageEventArgs e)
{
// Display any warnings
Console.WriteLine ("Warning Returned: " + e.Message);
}
Add the following code to a method and call it:
SQLServerConnection Conn;
Conn = new SQLServerConnection("host=nc-star;port=4100;User ID=test01;
Password=test01;Database Name=Test");
SQLServerCommand DBCmd = new SQLServerCommand
("print 'This is a Warning.'",Conn);
SQLServerDataReader myDataReader;
try
{
Conn.InfoMessage += new SQLServerInfoMessageEventHandler(myHandler);
Conn.Open();
myDataReader = DBCmd.ExecuteReader();
// This will throw a SQLServerInfoMessageEvent as the print
// statement generates a warning.
}
catch (Exception ex)
{
// Display any exceptions in a messagebox
MessageBox.Show (ex.Message);
}
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 1 3 O F 1 4
// Close the connection
Conn.Close();
Summary
DataDirect Technologies is committed to providing the fastest and most
functional ADO.NET managed data providers so that you can develop a
robust .NET solution with unrivaled performance.
These code examples, which provide working C# code for typical data access
tasks, can help you to get started quickly and optimize your development
when you use the Connect for .NET SQL Server data provider with your
ADO.NET application.
C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R
D A T A D I R E C T T E C H N O L O G I E S 1 4 O F 1 4
FOR MORE INFORMATION
800-876-3101
info@datadirect.com
datadirect.com
Worldwide Sales
Belgium (French) .............0800 12 045
Belgium (Dutch) ...............0800 12 046
France............................0800 911 454
Germany ....................0800 181 78 76
Japan .............................0120.20.9613
Netherlands .................0800 022 0524
United Kingdom .........0800 169 19 07
United States .................800 876 3101
DataDirect Technologies is the leading provider of components
for connecting software to data, providing standards-based
technology that ensures consistent behavior and performance
across diverse environments such as J2EE, .NET, Web, and
client/server. With the most comprehensive support for ODBC,
JDBC, ADO, ADO.NET and XML, DataDirect Technologies
provides the easiest experience connecting software to data.
datadirect.com
© 2003 DataDirect Technologies, Inc. All rights reserved.
DataDirect is a registered trademark of DataDirect
Technologies. Other company or product names mentioned
herein may be trademarks or registered trademarks of their
respective companies.

More Related Content

What's hot

Map Reduce 〜入門編:仕組みの理解とアルゴリズムデザイン〜
Map Reduce 〜入門編:仕組みの理解とアルゴリズムデザイン〜Map Reduce 〜入門編:仕組みの理解とアルゴリズムデザイン〜
Map Reduce 〜入門編:仕組みの理解とアルゴリズムデザイン〜
Takahiro Inoue
 
Lisp как универсальная обертка
Lisp как универсальная оберткаLisp как универсальная обертка
Lisp как универсальная обертка
Vsevolod Dyomkin
 
mysql 高级优化之 理解索引使用
mysql 高级优化之 理解索引使用mysql 高级优化之 理解索引使用
mysql 高级优化之 理解索引使用
nigel889
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
MongoDB
 

What's hot (20)

Map Reduce 〜入門編:仕組みの理解とアルゴリズムデザイン〜
Map Reduce 〜入門編:仕組みの理解とアルゴリズムデザイン〜Map Reduce 〜入門編:仕組みの理解とアルゴリズムデザイン〜
Map Reduce 〜入門編:仕組みの理解とアルゴリズムデザイン〜
 
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
 
Lab2-DB-Mongodb
Lab2-DB-MongodbLab2-DB-Mongodb
Lab2-DB-Mongodb
 
Lisp как универсальная обертка
Lisp как универсальная оберткаLisp как универсальная обертка
Lisp как универсальная обертка
 
The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196
 
The Ring programming language version 1.6 book - Part 15 of 189
The Ring programming language version 1.6 book - Part 15 of 189The Ring programming language version 1.6 book - Part 15 of 189
The Ring programming language version 1.6 book - Part 15 of 189
 
mysql 高级优化之 理解索引使用
mysql 高级优化之 理解索引使用mysql 高级优化之 理解索引使用
mysql 高级优化之 理解索引使用
 
The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210
 
Blockchain and smart contracts day 2
Blockchain and smart contracts day 2Blockchain and smart contracts day 2
Blockchain and smart contracts day 2
 
Binomial heap
Binomial heapBinomial heap
Binomial heap
 
PostgreSQL: Data analysis and analytics
PostgreSQL: Data analysis and analyticsPostgreSQL: Data analysis and analytics
PostgreSQL: Data analysis and analytics
 
Modern technologies in data science
Modern technologies in data science Modern technologies in data science
Modern technologies in data science
 
ClickHouse Unleashed 2020: Our Favorite New Features for Your Analytical Appl...
ClickHouse Unleashed 2020: Our Favorite New Features for Your Analytical Appl...ClickHouse Unleashed 2020: Our Favorite New Features for Your Analytical Appl...
ClickHouse Unleashed 2020: Our Favorite New Features for Your Analytical Appl...
 
The Ring programming language version 1.7 book - Part 44 of 196
The Ring programming language version 1.7 book - Part 44 of 196The Ring programming language version 1.7 book - Part 44 of 196
The Ring programming language version 1.7 book - Part 44 of 196
 
The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84
 
Hopping in clouds - phpuk 17
Hopping in clouds - phpuk 17Hopping in clouds - phpuk 17
Hopping in clouds - phpuk 17
 
2018 02-22 React, Redux & Building Applications that Scale | Redux
2018 02-22 React, Redux & Building Applications that Scale | Redux2018 02-22 React, Redux & Building Applications that Scale | Redux
2018 02-22 React, Redux & Building Applications that Scale | Redux
 
제 8회 엑셈 수요 세미나 자료 연구컨텐츠팀
제 8회 엑셈 수요 세미나 자료 연구컨텐츠팀제 8회 엑셈 수요 세미나 자료 연구컨텐츠팀
제 8회 엑셈 수요 세미나 자료 연구컨텐츠팀
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
Uni2
Uni2Uni2
Uni2
 

Viewers also liked

隨其心淨 則佛土淨
隨其心淨 則佛土淨隨其心淨 則佛土淨
隨其心淨 則佛土淨
hsu16868
 
Digital Marketing
Digital MarketingDigital Marketing
Digital Marketing
Sadiq P
 
September geo meeting
September geo meetingSeptember geo meeting
September geo meeting
GeoMedeelel
 
教導感恩 愛
教導感恩 愛教導感恩 愛
教導感恩 愛
hsu16868
 
01 west africa kingdoms
01 west africa kingdoms01 west africa kingdoms
01 west africa kingdoms
Robyn Wingate
 
Feliz navidad para mis amigos del face!!!!!
Feliz  navidad para mis amigos del face!!!!!Feliz  navidad para mis amigos del face!!!!!
Feliz navidad para mis amigos del face!!!!!
marcela1964
 
December geo meeting
December geo meetingDecember geo meeting
December geo meeting
GeoMedeelel
 

Viewers also liked (17)

隨其心淨 則佛土淨
隨其心淨 則佛土淨隨其心淨 則佛土淨
隨其心淨 則佛土淨
 
Supporting cooperatives in Uganda
Supporting cooperatives in UgandaSupporting cooperatives in Uganda
Supporting cooperatives in Uganda
 
Presentación7
Presentación7Presentación7
Presentación7
 
Ahxd001
Ahxd001Ahxd001
Ahxd001
 
Digital Marketing
Digital MarketingDigital Marketing
Digital Marketing
 
Ancient Egypt P3
Ancient Egypt P3Ancient Egypt P3
Ancient Egypt P3
 
Using e-readers to increase access to course content for students without Int...
Using e-readers to increase access to course content for students without Int...Using e-readers to increase access to course content for students without Int...
Using e-readers to increase access to course content for students without Int...
 
September geo meeting
September geo meetingSeptember geo meeting
September geo meeting
 
Engendering smallholder irrigated agriculture in Ethiopia
Engendering smallholder irrigated agriculture in EthiopiaEngendering smallholder irrigated agriculture in Ethiopia
Engendering smallholder irrigated agriculture in Ethiopia
 
Search Library and Information Databases : Constructing searches
Search Library and Information Databases : Constructing searchesSearch Library and Information Databases : Constructing searches
Search Library and Information Databases : Constructing searches
 
教導感恩 愛
教導感恩 愛教導感恩 愛
教導感恩 愛
 
01 west africa kingdoms
01 west africa kingdoms01 west africa kingdoms
01 west africa kingdoms
 
Feliz navidad para mis amigos del face!!!!!
Feliz  navidad para mis amigos del face!!!!!Feliz  navidad para mis amigos del face!!!!!
Feliz navidad para mis amigos del face!!!!!
 
December geo meeting
December geo meetingDecember geo meeting
December geo meeting
 
Probability And Random Variable Lecture(Lec9)
Probability And Random Variable Lecture(Lec9)Probability And Random Variable Lecture(Lec9)
Probability And Random Variable Lecture(Lec9)
 
20150415 Something About Meteor
20150415 Something About Meteor20150415 Something About Meteor
20150415 Something About Meteor
 
Assessing governance for climate smart landscapes
Assessing governance for climate smart landscapesAssessing governance for climate smart landscapes
Assessing governance for climate smart landscapes
 

Similar to Ss dotnetcodexmpl

Microsoft Ado
Microsoft AdoMicrosoft Ado
Microsoft Ado
oswchavez
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
Jay Patel
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
Jay Patel
 

Similar to Ss dotnetcodexmpl (20)

JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Ado.Net
Ado.NetAdo.Net
Ado.Net
 
Microsoft Ado
Microsoft AdoMicrosoft Ado
Microsoft Ado
 
Oracle
OracleOracle
Oracle
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
 
Deeply Declarative Data Pipelines
Deeply Declarative Data PipelinesDeeply Declarative Data Pipelines
Deeply Declarative Data Pipelines
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Python database access
Python database accessPython database access
Python database access
 
Shrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_youShrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_you
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Beg sql
Beg sqlBeg sql
Beg sql
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
ROracle
ROracle ROracle
ROracle
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 
C++ practical
C++ practicalC++ practical
C++ practical
 

Recently uploaded

QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food Additives
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

Ss dotnetcodexmpl

  • 1. P R O D U C T B R I E F U P D A T E D 9 / 2 4 / 2 0 0 3 C# Code Examples for Connect for .NET SQL Server Data Provider Overview Since the release of our first ADO.NET data providers in June, 2002, DataDirect Technologies has been fully committed to boosting operation performance in real-world environments such as SQL Server. This Product Brief provides code examples that can reduce application development time by providing working C# source code showing typical database access tasks in ADO.NET, using the Connect for .NET SQL Server data provider. To enable the code examples to work, you must create the sample tables. In addition, you must modify the connection strings in the examples to work in your environment. Finally, make sure you include the “using” directive for System.Data and DDTek.SQLServer in your project: using System.Data; using DDTek.SQLServer; The code examples demonstrate: • Retrieving Data Using a DataReader • Using a Local Transaction • Using a Distributed Transaction • Using the CommandBuilder • Updating Data in a Dataset • Calling a Stored Procedure • Retrieving a Scalar Value • Retrieving Warning Information Sample Tables Many of the samples in this product brief use the emp and dept tables. You can create the tables using an ISQL script, or by using the data provider. Creating the sample tables using an ISQL script The following script can be run in ISQL. See the Microsoft SQL Server documentation for details. CREATE TABLE emp ( empno INT PRIMARY KEY, ename VARCHAR(10), job VARCHAR(9), mgr INT NULL, hiredate DATETIME,
  • 2. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 2 O F 1 4 sal NUMERIC(7,2), comm NUMERIC(7,2) NULL, dept INT) begin insert into emp values (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4) insert into emp values (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3) insert into emp values (3,'TAFT','SALES I',2,'01-02-1996',25000,500,3) insert into emp values (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3) insert into emp values (5,'LINCOLN','TECH',6,'06-23-1994',22500,1400,4) insert into emp values (6,'GARFIELD','MANAGER',9,'05-01-1993',54000,NULL,4) insert into emp values (7,'POLK','TECH',6,'09-22-1997',25000,NULL,4) insert into emp values (8,'GRANT','ENGINEER',10,'03-30-1997',32000,NULL,2) insert into emp values (9,'JACKSON','CEO',NULL,'01-01-1990',75000,NULL,4) insert into emp values (10,'FILLMORE','MANAGER',9,'08-09-1994',56000,NULL,2) insert into emp values (11,'ADAMS','ENGINEER',10,'03-15-1996',34000,NULL,2) insert into emp values (12,'WASHINGTON','ADMIN',6,'04-16-1998',18000,NULL,4) insert into emp values (13,'MONROE','ENGINEER',10,'12-03-2000',30000,NULL,2) insert into emp values (14,'ROOSEVELT','CPA',9,'10-12-1995',35000,NULL,1) end CREATE TABLE dept ( deptno INT NOT NULL, dname VARCHAR(14), loc VARCHAR(13)) begin insert into dept values (1,'ACCOUNTING','ST LOUIS') insert into dept values (2,'RESEARCH','NEW YORK') insert into dept values (3,'SALES','ATLANTA') insert into dept values (4, 'OPERATIONS','SEATTLE') end Creating the sample tables using the data provider The sample tables used in this Product Brief can be created with the data provider, as shown in the following code example: SQLServerConnection Conn; Conn = new SQLServerConnection("host=nc-star;port=1433; User ID=test01;Password=test01; Database Name=Test"); try { Conn.Open(); } catch (SQLServerException ex) { // Connection failed Console.WriteLine(ex.Message); return; } string[] DropTableSQL = {"drop table emp", "drop table dept"}; for (int x=0; x<=1; x++) { try { // Drop the tables, don't care if they don't exist SQLServerCommand DBCmd = new SQLServerCommand(DropTableSQL[x], Conn); DBCmd.ExecuteNonQuery(); } catch (SQLServerException ex) { } // Create the tables
  • 3. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 3 O F 1 4 string CreateEmpTableSQL = "CREATE TABLE emp (empno INT PRIMARY KEY NOT NULL," +"ename VARCHAR(10) NOT NULL," +"job VARCHAR(9) NOT NULL," +"mgr INT," +"hiredate DATETIME NOT NULL," +"sal NUMERIC(7,2) NOT NULL," +"comm NUMERIC(7,2)," +"dept INT NOT NULL)"; string CreateDeptTableSQL = "CREATE TABLE dept (" +"deptno INT NOT NULL," +"dname VARCHAR(14)," +"loc VARCHAR(13))"; try { SQLServerCommand DBCmd = new SQLServerCommand(CreateEmpTableSQL, Conn); DBCmd.ExecuteNonQuery(); DBCmd.CommandText = CreateDeptTableSQL; DBCmd.ExecuteNonQuery(); } catch (Exception ex) { //Create tables failed Console.WriteLine (ex.Message); return; } // Now insert the records string[] InsertEmpRecordsSQL = { "insert into emp values (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4)", "insert into emp values (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3)", "insert into emp values (3,'TAFT','SALES I',2,'01-02-1996',25000,500,3)", "insert into emp values (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3)", "insert into emp values (5,'LINCOLN','TECH',6,'06-23-1994',22500,1400,4)", "insert into emp values (6,'GARFIELD','MANAGER',9,'05-01-1993',54000,NULL,4)", "insert into emp values (7,'POLK','TECH',6,'09-22-1997',25000,NULL,4)", "insert into emp values (8,'GRANT','ENGINEER',10,'03-30-1997',32000,NULL,2)", "insert into emp values (9,'JACKSON','CEO',NULL,'01-01-1990',75000,NULL,4)", "insert into emp values (10,'FILLMORE','MANAGER',9,'08-09-1994',56000, NULL,2)", "insert into emp values (11,'ADAMS','ENGINEER',10,'03-15-1996',34000, NULL,2)", "insert into emp values (12,'WASHINGTON','ADMIN',6,'04-16-1998',18000,NULL,4)", "insert into emp values (13,'MONROE','ENGINEER',10,'12-03-2000',30000,NULL,2)", "insert into emp values (14,'ROOSEVELT','CPA',9,'10-12-1995',35000,NULL,1)"}; string[] InsertDeptRecordsSQL = { "insert into dept values (1,'ACCOUNTING','ST LOUIS')", "insert into dept values (2,'RESEARCH','NEW YORK')", "insert into dept values (3,'SALES','ATLANTA')", "insert into dept values (4, 'OPERATIONS','SEATTLE')"}; // Insert dept table records first for (int x = 0; x<InsertDeptRecordsSQL.Length; x++) { try { SQLServerCommand DBCmd = new SQLServerCommand(InsertDeptRecordsSQL[x], Conn); DBCmd.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine (ex.Message); return; } }
  • 4. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 4 O F 1 4 // Now the emp table records for (int x = 0; x<InsertEmpRecordsSQL.Length; x++) { try { SQLServerCommand DBCmd = new SQLServerCommand(InsertEmpRecordsSQL[x], Conn); DBCmd.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine (ex.Message); return; } } Console.WriteLine ("Tables created Successfully!"); // Close the connection Conn.Close(); Retrieving Data Using a DataReader The DataReader provides the fastest but least flexible way to retrieve data from the database. Data is returned as a read-only, forward-only stream of data that is returned one record at a time. If you need to retrieve many records rapidly, using a DataReader would require fewer resources than using a DataSet, which would need large amounts of memory to hold the results. In the following code example, you execute a simple query on a Microsoft SQL Server database and read the results using a DataReader. This example uses the emp table. // Open connection to SQL Server database SQLServerConnection Conn; try { Conn = new SQLServerConnection("host=nc-star;port=1433; User ID=test01;Password=test01; Database Name=Test"); Conn.Open(); Console.WriteLine ("Connection successful!"); } catch (Exception ex) { // Connection failed Console.WriteLine(ex.Message); return; } try { // Create a SQL command string strSQL = "SELECT ename FROM emp WHERE sal>50000"; SQLServerCommand DBCmd = new SQLServerCommand(strSQL, Conn); SQLServerDataReader myDataReader; myDataReader = DBCmd.ExecuteReader(); while (myDataReader.Read()) { Console.WriteLine("High salaries: " + myDataReader["ename"].ToString());
  • 5. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 5 O F 1 4 } myDataReader.Close(); // Close the connection Conn.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); return; } Using a Local Transaction The following code example uses the emp table to show how to use a local transaction: SQLServerConnection Conn; Conn = new SQLServerConnection("host=nc-star;port=1433; User ID=test01; Password=test01;Database Name=Test"); try { Conn.Open(); Console.WriteLine ("Connection successful!"); } catch (Exception ex) { // Connection failed Console.WriteLine(ex.Message); return; } SQLServerCommand DBCmd = new SQLServerCommand(); SQLServerTransaction DBTxn = null; try { DBTxn = Conn.BeginTransaction(); // Set the Connection property of the Command object DBCmd.Connection = Conn; // Set the text of the Command to the INSERT statement DBCmd.CommandText = "insert into emp VALUES (16,'HAYES','ADMIN',6,'17-APR-2002',18000,NULL,4)"; // Set the transaction property of the Command object DBCmd.Transaction = DBTxn; // Execute the statement with ExecuteNonQuery, because we are not // returning results DBCmd.ExecuteNonQuery(); // Now commit the transaction DBTxn.Commit(); // Display any exceptions Console.WriteLine ("Transaction Committed!"); } catch (Exception ex) { // Display any exceptions Console.WriteLine (ex.Message); // If anything failed after the connection was opened, roll back the
  • 6. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 6 O F 1 4 // transaction if (DBTxn != null) { DBTxn.Rollback(); } } // Close the connection Conn.Close(); Using a Distributed Transaction The following code shows how to use a distributed transaction across two connections to two different Microsoft SQL Server servers. The example uses the emp table. NOTES: • When you use distributed transactions, you must add System.EnterpriseServices to the Solution Reference list. In addition, the application must be strongly named. To do this, first open a command window and go to the application directory. Then, run the following command: sn –k SolutionName.snk • Delete the AssemblyInfo.cs file from the Solution. • Microsoft Distributed Transaction Coordinator must be running on all clients and servers. using System; using System.EnterpriseServices; using System.Reflection; using DDTek.SQLServer; [assembly: ApplicationName("yourapplicationname")] [assembly: AssemblyKeyFileAttribute(@"....yourapplicationname.snk")] namespace DistTransaction { /// <summary> /// Summary description for Class1. /// </summary> public class Class1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { SQLServerConnection Conn1; Conn1 = new SQLServerConnection("host=nc-star;port=1433; User ID=test01;Password=test01; Database Name=Test;Enlist=true"); SQLServerConnection Conn2; Conn2 = new SQLServerConnection("host=nc-star;port=1433; User ID=test07;Password= test07; Database Name=test;Enlist=true"); try {
  • 7. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 7 O F 1 4 DistributedTran myDistributedTran = new DistributedTran(); myDistributedTran.TestDistributedTransaction(Conn1, Conn2); Console.WriteLine("Success!!"); } catch (Exception e) { System.Console.WriteLine("Error returned: " + e.Message); } } } /// <summary> /// To use distributed transactions in .NET, we need a ServicedComponent /// derived class with transaction attribute declared as "Required". /// </summary> [Transaction(TransactionOption.Required) ] public class DistributedTran : ServicedComponent { /// <summary> /// This method executes two SQL statements. /// If both are successful, both are committed by DTC after the /// method finishes. However, if an exception is thrown, both will be /// rolled back by DTC. /// </summary> [AutoComplete] public void TestDistributedTransaction(SQLServerConnection Conn1, SQLServerConnection Conn2) { // The following Insert statement goes to the first server, orca. // This Insert statement does not produce any errors. string DBCmdSql1 = "Insert into emp VALUES (16,'HAYES','ADMIN',6,'17-NOV-2002',18000,NULL,4)"; string DBCmdSql2 = "Delete from emp WHERE sal > 100000"; try { Conn1.Open(); Conn2.Open(); Console.WriteLine ("Connection successful!"); } catch (Exception ex) { // Connection failed Console.WriteLine(ex.Message); return; } SQLServerCommand DBCmd1 = new SQLServerCommand(DBCmdSql1, Conn1); SQLServerCommand DBCmd2 = new SQLServerCommand(DBCmdSql2, Conn2); DBCmd1.ExecuteNonQuery(); DBCmd2.ExecuteNonQuery(); Conn1.Close(); Conn2.Close(); Console.WriteLine("Success!! "); } } }
  • 8. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 8 O F 1 4 Using the CommandBuilder A CommandBuilder object can be used to generate the Insert, Update, and Delete statements for a DataAdapter. The following code example uses the emp sample table with the CommandBuilder to update a DataSet: SQLServerConnection Conn; Conn = new SQLServerConnection("host=nc-star; port=4100;User ID=test01; Password=test01;Database Name=Test "); try { Conn.Open(); Console.WriteLine ("Connection successful!"); } catch (Exception ex) { // Connection failed Console.WriteLine(ex.Message); return; } SQLServerDataAdapter myDataAdapter = new SQLServerDataAdapter(); SQLServerCommand DBCmd = new SQLServerCommand("select * from emp",Conn); myDataAdapter.SelectCommand = DBCmd; // Set up the CommandBuilder SQLServerCommandBuilder CommBuild = new SQLServerCommandBuilder(myDataAdapter); DataSet myDataSet = new DataSet(); try { myDataAdapter.Fill(myDataSet); // Now change the salary of the first employee DataRow myRow; myRow = myDataSet.Tables["Table"].Rows[0]; myRow["sal"] = 95000; // Tell the DataAdapter to resynch with the SQL Server server. // Without the CommandBuilder, this line would fail. myDataAdapter.Update(myDataSet); Console.WriteLine ("Update with CommandBuilder Successful!"); } catch (Exception ex) { // Display any exceptions Console.WriteLine (ex.Message); } // Close the connection Conn.Close(); Updating Data in a Dataset When updating a row at the data source, the DataSet uses the SQL provided in UpdateCommand of the Data Adapter. The Update statement can use parameters that contain the unique identifier, such as the primary key, and the columns to be updated, as shown in the following example: [C#] string updateSQL As String = "UPDATE emp SET sal = ?, job = ? + = WHERE empno = ?;
  • 9. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 9 O F 1 4 The parameterized query statements define the parameters that will be created. Refer to the DataDirect Connect for .NET User's Guide and Reference for more information about using parameters with the SQL Server data provider. The following code example shows how to provide an UpdateCommand to a DataAdapter for use in synchronizing changes made to a DataSet with the actual data on the SQL Server server, using data from the emp table. The example uses the Parameters.Add method to create the parameters for the Update statement, fills a DataSet, programmatically makes changes to the DataSet, then synchronizes the changes back to the database. SQLServerConnection Conn = new SQLServerConnection("host=nc-star; port=4100;User ID=test01;Password=test01;Database Name=Test"); try { string selectText = "select sal, job, empno from emp"; string updateText = "update emp set sal = ?, job = ? where empno = ?"; SQLServerDataAdapter adapter = new SQLServerDataAdapter(selectText, Conn); SQLServerCommand updateCommand = new SQLServerCommand(updateText, Conn); adapter.UpdateCommand = updateCommand; updateCommand.Parameters.Add("@sal", SQLServerDbType.Int, 15, "SAL"); updateCommand.Parameters.Add("@job", SQLServerDbType.VarChar, 9, "JOB"); updateCommand.Parameters.Add("@empno", SQLServerDbType.Int, 15, "empno"); DataSet myDataSet = new DataSet("emp"); adapter.Fill(myDataSet, "emp"); // Give employee number 11 a promotion and a raise DataRow changeRow = myDataSet.Tables["emp"].Rows[11]; changeRow["sal"] = "35000"; changeRow["job"] = "MANAGER"; // Send back to database adapter.Update(myDataSet, "emp"); myDataSet.Dispose(); } catch (Exception ex) { // Display any exceptions Console.WriteLine (ex.Message); } Console.WriteLine("DataSet Updated Successfully!"); // Close the connection Conn.Close(); Calling a Stored Procedure You call stored procedures using a Command object. When you issue a command on a stored procedure, you must set the CommandType of the Command object to StoredProcedure, or use the ODBC/JDBC escape syntax. For information on using the ODBC/JDBC escape syntax with the data provider, refer to the Connect for .NET User’s Guide and Reference.
  • 10. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 1 0 O F 1 4 The following code shows how to execute a stored procedure on a SQL Server database and read the results using a DataReader. The sample data is in the emp table. Creating the stored procedure First, execute the following code to create the stored procedure: // Open connection to SQL Server database SQLServerConnection Conn; Conn = new SQLServerConnection("host=nc-star;port=4100;User ID=test01; Password=test01;Database Name=Test"); try { Conn.Open(); Console.WriteLine ("Connection successful!"); } catch (Exception ex) { // Connection failed Console.WriteLine(ex.Message); return; } string spCreate = "CREATE PROCEDURE GetEmpSalary(@empno int,@sal numeric(7,2) output)AS SELECT @sal = sal from emp where empno = @empno"; try { SQLServerCommand DBCmd=new SQLServerCommand(spCreate, Conn); DBCmd.ExecuteNonQuery(); } catch (Exception ex) { //Create procedure failed Console.WriteLine (ex.Message); return; } Console.WriteLine ("Procedure Created Successfully!"); Executing the stored procedure Now, use the following code example to execute the GetEmpSalary stored procedure: // Open connection to SQL Server database SQLServerConnection Conn; try { Conn = new SQLServerConnection("host=nc-star;port=4100;User ID=test01; Password=test01;Database Name=Test"); Conn.Open(); Console.WriteLine ("Connection successful!"); } catch (Exception ex) { // Connection failed Console.WriteLine(ex.Message); return; } // Make a command object for the stored procedure
  • 11. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 1 1 O F 1 4 // You must set the CommandType of the Command object // to StoredProcedure SQLServerCommand DBCmd = new SQLServerCommand("GetEmpSalary",Conn); DBCmd.CommandType = CommandType.StoredProcedure; // The stored procedure expects one input and one output parameter // Define the parameters for the stored procedure // We don't need to specify the direction of the parameter, since the default is INPUT DBCmd.Parameters.Add("@empno", SQLServerDbType.Int, 10).Value = 5; // Output parameter DBCmd.Parameters.Add("@sal", SQLServerDbType.Numeric, 10).Direction = ParameterDirection.Output; SQLServerDataReader myDataReader; try { myDataReader = DBCmd.ExecuteReader(); myDataReader.Close(); } catch (Exception ex) { // Display any exceptions Console.WriteLine (ex.Message); } Console.WriteLine("Procedure Executed Successfully!"); // Close the connection Conn.Close(); Retrieving a Scalar Value You can use the ExecuteScalar method of the Command object to return a single value, such as a sum or a count, from the database. The ExecuteScalar method returns the value of the first column of the first row of the result set. If you know the result set has only one row and one column, you can use this method to speed up retrieval of the value. The following code example retrieves the number of employees who make more than $50000. This example uses the emp table. // Open connection to SQL Server database SQLServerConnection Conn; Conn = new SQLServerConnection("host=nc-star;port=4100;User ID=test01; Password=test01;Database Name=Test"); try { Conn.Open(); Console.WriteLine ("Connection successful!"); } catch (Exception ex) { // Connection failed Console.WriteLine(ex.Message); return; } // Make a command object SQLServerCommand salCmd = new SQLServerCommand("select count(sal) from emp where sal>50000",Conn);
  • 12. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 1 2 O F 1 4 try { int count = (int)salCmd.ExecuteScalar(); Console.WriteLine("Count of Salaries >$50,000 : " + Convert.ToString(count)); } catch (Exception ex) { // Display any exceptions Console.WriteLine(ex.Message); } // Close the connection Conn.Close(); Retrieving Warning Information The data provider handles database server warnings through the InfoMessage delegates on the Connection objects. The following example shows how to retrieve a warning generated by a Microsoft SQL Server server: // Define an event handler public void myHandler(object sender, SQLServerInfoMessageEventArgs e) { // Display any warnings Console.WriteLine ("Warning Returned: " + e.Message); } Add the following code to a method and call it: // Define an event handler public void myHandler(object sender, SQLServerInfoMessageEventArgs e) { // Display any warnings Console.WriteLine ("Warning Returned: " + e.Message); } Add the following code to a method and call it: SQLServerConnection Conn; Conn = new SQLServerConnection("host=nc-star;port=4100;User ID=test01; Password=test01;Database Name=Test"); SQLServerCommand DBCmd = new SQLServerCommand ("print 'This is a Warning.'",Conn); SQLServerDataReader myDataReader; try { Conn.InfoMessage += new SQLServerInfoMessageEventHandler(myHandler); Conn.Open(); myDataReader = DBCmd.ExecuteReader(); // This will throw a SQLServerInfoMessageEvent as the print // statement generates a warning. } catch (Exception ex) { // Display any exceptions in a messagebox MessageBox.Show (ex.Message); }
  • 13. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 1 3 O F 1 4 // Close the connection Conn.Close(); Summary DataDirect Technologies is committed to providing the fastest and most functional ADO.NET managed data providers so that you can develop a robust .NET solution with unrivaled performance. These code examples, which provide working C# code for typical data access tasks, can help you to get started quickly and optimize your development when you use the Connect for .NET SQL Server data provider with your ADO.NET application.
  • 14. C # C O D E E X A M P L E S F O R C O N N E C T F O R . N E T S Q L S E R V E R D A T A P R O V I D E R D A T A D I R E C T T E C H N O L O G I E S 1 4 O F 1 4 FOR MORE INFORMATION 800-876-3101 info@datadirect.com datadirect.com Worldwide Sales Belgium (French) .............0800 12 045 Belgium (Dutch) ...............0800 12 046 France............................0800 911 454 Germany ....................0800 181 78 76 Japan .............................0120.20.9613 Netherlands .................0800 022 0524 United Kingdom .........0800 169 19 07 United States .................800 876 3101 DataDirect Technologies is the leading provider of components for connecting software to data, providing standards-based technology that ensures consistent behavior and performance across diverse environments such as J2EE, .NET, Web, and client/server. With the most comprehensive support for ODBC, JDBC, ADO, ADO.NET and XML, DataDirect Technologies provides the easiest experience connecting software to data. datadirect.com © 2003 DataDirect Technologies, Inc. All rights reserved. DataDirect is a registered trademark of DataDirect Technologies. Other company or product names mentioned herein may be trademarks or registered trademarks of their respective companies.