I have created a SQL DataBase (DatabaseTest.mdf) in Visual Studio 2019 Preview (.NET Core 3.1, Windows Form Application). It is my first time, I am trying to do this. I run the database locally on my computer.
The database consists of 4 columns:
- First Name
- Last Name
- PhoneNumber
- Salary
Now, I am trying to use C# to programatically ADD a row with information to this database.
The code is the below:
using System.Data.SqlClient;
private void button1_Click(object sender, EventArgs e)
{
string connectionString = GetConnectionString();
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("sp_insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@First Name", "Peter");
cmd.Parameters.AddWithValue("@Last Name", "Smith");
cmd.Parameters.AddWithValue("@PhoneNumber", "5548945667");
cmd.Parameters.AddWithValue("@Salary", 50000);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i != 0)
{
MessageBox.Show(i + "Data Saved");
}
}
static private string GetConnectionString()
{
return "Data Source=(LocalDB)/MSSQLLocalDB;AttachDbFilename=C:/Users/andre/source/repos/TestDatabaseCreation/DatabaseTest.mdf;Integrated Security=True";
}
However, when I now run this code by clicking on the button. I receive this error:
System.Data.SqlClient.SqlException: '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)'
Win32Exception: Network path not found.
I have copied this connection string from the DatabaseTest.mdf properties exactly. So the path to the DatabaseTest.mdf below is correct etc
"Data Source=(LocalDB)/MSSQLLocalDB;AttachDbFilename=C:/Users/andre/source/repos/TestDatabaseCreation/DatabaseTest.mdf;Integrated Security=True"
I wonder what the problem is that I get this error message?
(I attach a screenshot on the link below also from Visual Studio 2019 Preview .NET Core 3.1)
Image of the error in C# code behind in Visual Studio 2019 Preview