How do I connect to a SQL database from C#?
Check out
I'm sure there's plenty more out there - just google for "ADO.NET" and "Tutorial" ......
UPDATE:
If you want to connect to your local SQL Server Express, and connect to the "Northwind" database, and read the top 5 customers from the "Customers" table, you'd have to do something like this:
string connectionString = "server=(local)\SQLExpress;database=Northwind;integrated Security=SSPI;";using(SqlConnection _con = new SqlConnection(connectionString)){ string queryStatement = "SELECT TOP 5 * FROM dbo.Customers ORDER BY CustomerID"; using(SqlCommand _cmd = new SqlCommand(queryStatement, _con)) { DataTable customerTable = new DataTable("Top5Customers"); SqlDataAdapter _dap = new SqlDataAdapter(_cmd); _con.Open(); _dap.Fill(customerTable); _con.Close(); }}
Now you would have all 5 top customers from your Northwind database in the DataTable and you can inspect them, print them out, manipulate them - whatever you want to do.
That's ADO.NET in action!
As for the details of the connection string - what options you can use and what it should look like, check out the Connection Strings web site - it has tons of examples and explanations.
Marc
object is made for this.
Eg:
SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
or
SqlConnection conn = new SqlConnection("Data Source=DatabaseServer; Initial Catalog=Northwind; User ID=YourUserID; Password=YourPassword");conn.Open(); // opens the database connection
Edit:
After doing all your stuff you have to close the connection by
conn.Close();
Data Source: Identifies the server. Could be local machine, machine domain name, or IP Address.
Initial Catalog: Database name.
Integrated Security: Set to SSPI to make connection with user's Windows login
User ID: Name of user configured in SQL Server.
Password: Password matching SQL Server User ID.
To connect to SQL Server Express you need nothing but System.Data
, which is a standard .NET assembly. Just use SqlXXX
classes and you'll be done.
However, writing mundane ADO.NET code is very boring, so it's very common to use an ORM or less heavy-weight result-set mapper such as BLToolkit.
And finally, consider using SQL Server CE. This is a fully ACID-compliant single-file embedded database engine which supports pretty much any feature you can expect form an SQL RDBMS.