473,799 Members | 3,832 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Database connection code

1 New Member
Can anyone help me with the meaning of this snippet?


Expand|Select|Wrap|Line Numbers
  1. string conString =@"Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=c:\billing.mdb";
  2. OleDbConnection conn = new OleDbConnection(conString);
  3. Conn.Open();
  4.  
  5. DataSet ds = new DataSet();
  6. OleDbDataAdapter adapter =
  7. new OleDbDataAdapter("Select * from product where id=" + id, conn);
  8. adapter.Fill(ds);
  9.  
  10. conn.Close();
  11.  
  12. DataTable dt = ds.Tables[0];
  13. foreach (DataRow dr in dt.Rows)
  14. {
  15.    data = Convert.ToInt32(dr["count"]);
  16. }
Oct 11 '11 #1
2 1701
Rabbit
12,516 Recognized Expert Moderator MVP
It connects to a database, queries it, and puts the field count into the variable data. However, the data variable keeps getting replaced with the current row's data so you're only ever going to get the last row of data.
Oct 11 '11 #2
Frinavale
9,735 Recognized Expert Moderator Expert
This line:
Expand|Select|Wrap|Line Numbers
  1. string conString =@"Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=c:\billing.mdb";
Declares a string variable called "conString" that contains information on for connecting to a database. This type of string is referred to as a Connection String.

The next line declares and creates a new instance of a OleDbConnection. The OleDbConnection is used to connect to a database. It requires the Connection String in order to know how to connect to the database.
Expand|Select|Wrap|Line Numbers
  1. OleDbConnection conn = new OleDbConnection(conString);
The next line opens the connection to the database.
Expand|Select|Wrap|Line Numbers
  1. Conn.Open();
The next lines create a new instance of a DataSet. A DataSet is a collection of DataTables. These are fill with information retrieved from the database using a DataAdapter.

Expand|Select|Wrap|Line Numbers
  1.  
  2. DataSet ds = new DataSet();
  3. OleDbDataAdapter adapter =
  4. new OleDbDataAdapter("Select * from product where id=" + id, conn);
  5. adapter.Fill(ds);
After executing the DataAdapter's Fill method, the DataSet is filled with DataTables that are populated with data retrieved from the database. In this case the SQL command executed is very simple and only 1 table is involved...ther efore the DataSet will only contain 1 DataTable.


The following line closes the connection to the database because you're done working with the database (you've retrieved the data you need to work with)
Expand|Select|Wrap|Line Numbers
  1. conn.Close();

In the following code, you are retrieving the 1 DataTable within the DataSet that was created for you by the DataAdpter.

Then you are looping through each row/record in that DataTable and retrieving the data stored in the "count" field/cell.

For some reason you're converting this into a .NET Integer type and are storing this into a variable called "data". I don't know why you're doing this...the data variable will continue to be replaced while looping....


Expand|Select|Wrap|Line Numbers
  1. DataTable dt = ds.Tables[0];
  2. foreach (DataRow dr in dt.Rows)
  3. {
  4.    data = Convert.ToInt32(dr["count"]);
  5. }
So, the result of this code is that "data" is filled with the "count" information for the last row/record in the data table retrieved from the database.

Whenever you don't understand what a control is in a piece of code you should refer to the MSDN Library. This library contains documentation, articles, walk-throughs on all of the .NET controls and programming concepts. I have added links to each control and concept that was used in the code you posted. In the future please use the Search function of the MSDN Library to research a control before asking about it.

-Frinny
Oct 11 '11 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

4
2367
by: Poewood | last post by:
Does anyone have some basic code and the corresponding resources needed that will enable me to connect to an Access Database in .net compact frmwrk using C#. I need to learn how to create a recordset and do some reading, updating and appending. I can't seem to find any straight forward examples. It's all blah, blah, blah. I would appreciate any code that I can build on. Thank you.
3
2479
by: R Reyes | last post by:
Hi, I'm trying to modularize my database connections a little better and get more out of my project with less code. First check out this common dbOpen() function inside class clsDatabase. I removed the try/catch part as it is not important for my question: // This function opens a connection to the database. public static SqlConnection dbOpen() { // Create a SqlConnection object and pass in our connection string
2
3501
by: Bryan | last post by:
Hello, I'm just starting to develop in asp.net and i have a question about using a database connection globally in my app. I have set up the procedures for getting all my connection string info which each page will use, but my question relates to how to use the database connection i create in all my classes. I have a database class, in a separate namespace and file, i created that handles all the connection opening, executing statements...
7
2211
by: Bernie Yaeger | last post by:
I can't believe that there aren't lots of developers who: 1. create a crystal report that connects to sql server 2. calls the report using the crystalreportviewer control to view it and then, if appropriate, print it 3. tries to deploy that report to the client's database, but now it calls for a different database name Yet I can't get an answer to the question: I have developed numerous reports in an app (Windows Database App) that...
3
10298
by: Martin B | last post by:
Hallo! I'm working with C# .NET 2.0, implementing Client/Server Applications which are connecting via Network to SQL-Server or Oracle Databases. To stay independent from the underlaying Database I use System.Data.Common.DBConnection and .DBCommand. How can I keep aware from connection losses (network not availeable, db-server not available...)? Are there any strategies to detect this broken connections, and how can I
35
4853
by: Terry Jolly | last post by:
Web Solution Goal: Have a global database connection Why: (There will be 30+ tables, represented by 30+ classes) I only want to reference the database connection once. I put the connection string in the web.config. I created a class with a static database connection and the class opens and closes the database.
5
2133
by: Matt | last post by:
Hello, What is the best way to handle the database connection string for a class library project that will be compiled and used as a .dll? This .dll will be accessed via classic ASP and in the future by ASP.NET pages. I have created a constant that contains the connection string (as shown below).
4
1655
by: Mike P2 | last post by:
Hi. I'm writing controls that have to query the database, and it bothers me that I might have several of these controls on a page that each create, open, and close their own connection with the same connection string, and the page class has a connection object too. I'm using the code-behind way of doing things, and I considered leaving the database connection open as a field in the page's class and somehow letting the controls use that...
3
1750
by: Hahn, Thomas | last post by:
Hallo, I have an ASP.NET application with masterpages, skins and diffrent themes. The application works fine, but the performance is not realy good. If I load an ASPX file, which has no database connection, is the performance ok. ASPX file with one or more database queries have a answer time about 15 or 20 seconds. Each database query need maximal a second to give the answer. So the query works ok! Know you a reason, why the time with a...
3
1849
eboschi
by: eboschi | last post by:
Hi all, i'm new to .net programming and i have some problems with database connection. I have written two web application. Both of them use ADODB Connection to Sql Server 2000 database. The problem is in second one. The first application is used for order management. I have defined in Main.aspx page a variable called localSqlConnection. Every time i enter this page (only one time per session) i create connection to local database and then i...
0
9687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9543
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10488
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9077
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7567
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6808
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4144
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.