Thursday, April 9, 2020

Establishing connection to SQL Server on local machine, C#

The machine name is JOHN-PC
The SQL Server name is: TEW_SQLEXPRESS
The database name is myDB


using System;
using System.Data.SqlClient;

namespace CSharpConnectToSQLServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            string connetionString = null;
            SqlConnection cnn;
            connetionString = @"Server = JOHN-PC\TEW_SQLEXPRESS; Database=myDB; Trusted_Connection=Yes;";
            cnn = new SqlConnection(connetionString);
            try
            {
                cnn.Open();
                Console.WriteLine("Connection Open ! ");
                cnn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Can not open connection ! ");
            }
            Console.ReadLine();

        }
    }
}

Thanks to: https://www.connectionstrings.com/sql-server/
Using the @ symbol: https://stackoverflow.com/questions/22311799/c-sharp-connection-string-error
The general body of the code: https://stackoverflow.com/questions/22803975/connection-to-sql-server-express-from-c-sharp

No comments:

Post a Comment

C# Creating a Picture at Runtime in a windows form app

Add a PictureBox to the form. It will be called PictureBox1 See post:  https://docs.microsoft.com/en-us/dotnet/desktop/winforms/advanced/how...