I tried to open a connection with SQL Server Express and assign a new record on a specific table in C#.
This code is giving me this error
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
And the following:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SqlConnection myConnection = new SqlConnection("Server=HABCHY-PC/SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"Database=mydatabase;" +
"User Instance=true;"+
"Connection timeout=30");
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand myCommand = new SqlCommand("INSERT INTO students (firstname, age) "+
"Values ('string', 1)", myConnection);
myCommand.ExecuteNonQuery();
try
{
SqlDataReader myReader = null;
myCommand.CommandText = "select * from students";
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["firstname"].ToString());
Console.WriteLine(myReader["age"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
Please tell me what's the problem.