Skip to content

Instantly share code, notes, and snippets.

@lavantien
Last active September 17, 2019 11:40
Show Gist options
  • Save lavantien/46dd807cf21a92d33b692bb085da7051 to your computer and use it in GitHub Desktop.
Save lavantien/46dd807cf21a92d33b692bb085da7051 to your computer and use it in GitHub Desktop.
Example of connecting to SQL Server DB.
using System;
using System.Data.Common;
using System.Configuration;
namespace TestCS
{
class Program
{
static void Main(string[] args) {
string provider = ConfigurationManager.AppSettings["provider"];
string connectionString = ConfigurationManager.AppSettings["connectionString"];
DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
using (DbConnection connection = factory.CreateConnection()) {
if (connection == null) {
Console.WriteLine("Connection Error");
Console.ReadKey();
return;
}
connection.ConnectionString = connectionString;
connection.Open();
DbCommand command = factory.CreateCommand();
if (command == null) {
Console.WriteLine("Command Error");
Console.ReadKey();
return;
}
command.Connection = connection;
command.CommandText = "select * from Products";
using (DbDataReader dataReader = command.ExecuteReader()) {
while (dataReader.Read()) {
Console.WriteLine($"{dataReader["ProdId"]} {dataReader["Product"]}");
}
}
Console.ReadKey();
}
}
}
}
/*
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="provider" value="System.Data.SqlClient" />
<add key="connectionString" value="Data Source=YOURDESKTOP;Initial Catalog=StoreDB;Integrated Security=True;Pooling=False" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment