View Single Post
Join Date: Feb 2003
Posts: 793
Reputation: Paladine has a spectacular aura about Paladine has a spectacular aura about Paladine has a spectacular aura about 
Solved Threads: 26
Team Colleague
Paladine's Avatar
Paladine Paladine is offline Offline
Master Poster

Re: How do you connect to a sql database using C#

 
0
  #2
Apr 9th, 2005
Umm, ok. I will give you some sample code, but you should really consider checking out the tutorials here at Daniweb, or C# websites with tutorials. The principles are the same no matter what language, the syntax is the only thing that differs. And google searches are a really good place to start.

Sample - as a console application in C#

using System;
using System.Data.SqlClient;

namespace ConsoleCSharp
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class DataReader_SQL
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			//
			// TODO: Add code to start application here
			//
			try
			{
		    	SqlConnection thisConnection = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=192.168.0.100,1433;database=Northwind;User id=Paladine;Password=;");
				thisConnection.Open();
		 	SqlCommand thisCommand = thisConnection.CreateCommand();
		 	thisCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers";
			 SqlDataReader thisReader = thisCommand.ExecuteReader();
				while (thisReader.Read())
				{
		 		Console.WriteLine("\t{0}\t{1}", thisReader["CustomerID"], thisReader["CompanyName"]);
					}
				thisReader.Close();
				thisConnection.Close();

			}
			catch (SqlException e)
			{
				Console.WriteLine(e.Message);
			}
			
		}
	}
}

** NOTE **
If you are using Visual Studio, rather than the commandline compiler, use CTRL + F5 to compile, as that will put a pause in the Console app, and keep it open for you to see the results.

Hope this helps.
Assistant Manager, Pharmacy Informatics
Wordpress Learning Blog
Updated : ASP.Net Login Code
Reply With Quote