Below is the C sharp code to connect with the sql data base in .net
usingSystem.Data.Sql;
usingSystem.Data.SqlClient;
// FUNCTION TO CONNECT TO THE SQL SERVER DATABASE
privatevoidconnectToSQLServer()
{
// SQL CONNECTION REPRESENTS AN OPEN CONNECTION TO SQL SERVER DATABASE
SqlConnectionsqlConnection = newSqlConnection(connectionString);
//CONNECTION STRING IS STRING FOR CONNECTING TO THE SQL SERVER
// e.g : "Data Source=servername;Initial Catalog=databasename;Integrated Security=True"
try
{
SqlCommandsqlCommand=newSqlCommand("Select * from tableName");// QUERY TO BE EXECUTED
sqlConnection.Open();// OPEN SQL CONNECTION
sqlCommand.Connection=sqlConnection;
DataTabletableResult = newDataTable();
tableResult.Load(sqlCommand.ExecuteReader()) ;// RETURN RESULT OF QUERY
}
catch (Exception ex)
{
}
finally
{
// CLOSE SQL CONNECTION IF IT IS OPEN
if(sqlConnection!=null&&sqlConnection.State==ConnectionState.Open)
sqlConnection.Close(); }
}
0 Comment(s)