Simple Sql Database Connection with Select Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace DataBaseTest
{
class Program
{
static void Main(string[] args)
{
//1. Connect to database
SqlConnection myConnection = new SqlConnection(@"user id=UserName;" +
"password=**********;server=ServerName\\SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"database=TravisTestDB; " +
"connection timeout=30");
myConnection.Open();
{ 
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(@"select * from [User]", myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader[0].ToString());
Console.WriteLine(myReader[1].ToString());
Console.WriteLine(myReader[2].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

myConnection.Close();
Console.Read();
}
}
}
}

 

Author: Travis Gneiting

Passionate Professional .NET Developer