HOW TO: Open ADO Connection and RecordSet Objects in Visual C# .NET (308611)
The information in this article applies to:
- Microsoft Visual C# .NET (2002)
- Microsoft Visual C# .NET (2003)
- ActiveX Data Objects (ADO) 2.5
- ActiveX Data Objects (ADO) 2.6
- ActiveX Data Objects (ADO) 2.7
This article was previously published under Q308611 For a Microsoft Visual Basic .NET version of this
article, see
308047. IN THIS TASKSUMMARY This step-by-step article shows you how to create ActiveX
Data Objects (ADO) Connection and Recordset objects in Visual C# .NET. back to the topCreate ADO Connection and Recordset Objects in Visual C# .NET- Create a new Visual C# .NET Windows application
project.
- On the Project menu, click Add Reference.
- Click the COM tab. Click Microsoft ActiveX Data Objects 2.X
Library.
- Open the Code window for Form1.
- So that your declarations will be form-level in scope, add
the following code to the top of the Form1 class section, above the public Form1 function:
private ADODB.Connection cn = new ADODB.Connection();
private ADODB.Recordset rs = new ADODB.Recordset();
private string cnStr;
private string query;
- Use the following code samples in the Form1 function below InitializeComponent();. The first example creates a Connection object and connects to a SQL Server Pubs database. The second
example creates a RecordSet object.
To connect to the database:
Note User ID <user name> must have permissions to
perform these operations on the database.
//Connection string.
cnStr = "Provider=SQLOLEDB;Initial Catalog=Pubs;Data Source=servername;User ID=<username>;Password=;<strong password>";
//query
query = "Select * From Authors";
//Connection via Connection open Property.
cn.Open(cnStr, null, null, 0);
cn.Close();
//Connection via ConnectionString Property.
cn.ConnectionString = cnStr;
cn.Open(null, null, null, 0);
cn.Close();
To retrieve the RecordSet from database:
//Open Recordset via Connection object.
cn.Open(cnStr, null, null, 0);
rs.Open(query, cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockOptimistic, -1);
rs.Close();
cn.Close();
//Open Recordset without connection object.
rs.Open(query, cnStr, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockOptimistic, -1);
rs.Close();
- Modify the ConnectionString object for your SQL Server. Press F11 to step through the code
and note the different ways to create a Connection or RecordSet object.
back to the
topREFERENCESFor additional information,
click the article number below to view the article in the Microsoft Knowledge
Base: 168336 HOWTO: Open ADO Connection and Recordset Objects
back to the
top
Modification Type: | Minor | Last Reviewed: | 12/12/2003 |
---|
Keywords: | kbADONET kbHOWTOmaster kbSample KB308611 kbAudDeveloper |
---|
|