0

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

coding
  • 53
  • 1
  • 9
  • 1
    Did you install SQL Express ? – Selvin Oct 02 '20 at 15:58
  • 2
    The slash might work as an alternative for paths but the Data Source (Server) has to use a backslash: `(LocalDB)\MSSQLLocalDB` – madreflection Oct 02 '20 at 15:58
  • example `Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;Trusted_Connection=Yes;` – vikas Oct 02 '20 at 16:02
  • check this out https://www.connectionstrings.com/sql-server/ – vikas Oct 02 '20 at 16:02
  • 3
    Extended reading: [AddWithValue is Evil](https://www.dbdelta.com/addwithvalue-is-evil/) and [Can we stop using AddWithValue() already?](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) – Thom A Oct 02 '20 at 16:03
  • 3
    Also in regards to the procedure's name: [Is the sp_ prefix still a no-no?](https://sqlperformance.com/2012/10/t-sql-queries/sp_prefix) `sp_` is reserved by Microsoft and should not be used. – Thom A Oct 02 '20 at 16:04
  • @madreflection I tried to change to: `Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:/Users/andre/source/repos/TestDatabaseCreation/DatabaseTest.mdf;Integrated Security=True` which gave error: `Users/andre/source/repos/TestDatabaseCreation/DatabaseTest.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.'` (I have to use \\ instead of only \ for it to compile) – coding Oct 02 '20 at 16:10
  • @Selvin I don't think I have installed SQL Express. Is that neccessarcy for Visual Studio 2019 in this problem? – coding Oct 02 '20 at 16:11
  • SQL Express is neccessarcy to connect to `(LocalDB)` – Selvin Oct 02 '20 at 16:13
  • @Selvin that is great, I am currently installing `SQL Server Express LocalDB` from https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/sql-server-express-localdb?view=sql-server-ver15 to see if this can help. – coding Oct 02 '20 at 16:19
  • try return @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\andre\source\repos\TestDatabaseCreation\DatabaseTest.mdf;Integrated Security=True""; – VietDD Oct 02 '20 at 16:25
  • I have just now installed `SQL Server Express`, I use this string: `Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\andre\\source\\repos\\TestDatabaseCreation\\DatabaseTest.mdf;Integrated Security=True` and I now get this error: `System.Data.SqlClient.SqlException: 'Could not find stored procedure sp_insert.` I also tried `proc_insert` with the same error. `Could not find stored procedure 'proc_insert` ` – coding Oct 02 '20 at 16:34
  • To mention when I installed `SQL Server Express` this connection string was shown upon successfull install: `Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;` I don't know if that should be used somehow? – coding Oct 02 '20 at 16:39

1 Answers1

1

First, you can ensure SQL Server Express is installed and working by the following steps

  1. Open Visual Studio Installer >> Modify

Modify Visual Studio

Expand .Net desktop development

.Net desktop development

Scroll down and check SQL Server Express is installed or not

[SQL Server Express3

if it is installed go to step 2

  1. Open Server Explorer

Server Explorer

Connect to Database

Connect to Database

Choose Data Source >> Microsoft SQL Server Database File

Database File

Add Connection >> Browse to your database file, and make sure to Test Connection, then OK

Add Connection

After that, inside Server Explorer will display the connections, right click on that >> properties

database's property

Then you can get the Connection String

Connection String

Second, with Connection String got above, you can check it work or not by

SqlConnection cnn = new SqlConnection(**connectionString**);

cnn.Open();

// not do anything yet

cnn.Close();

Then run to make sure you can open the connection to the database

UPDATE :

Check which Stored Procedures you want is existed or not?

Stored Procedures

VietDD
  • 1,048
  • 2
  • 12
  • 12
  • that is great. I did everything you said there. I got a successfull "Test Connection". Then I receive this connection string: `Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\andre\\source\\repos\\TestDatabaseCreation\\DatabaseTest.mdf;Integrated Security=True;Connect Timeout=30`. Then I `.Open` and `.Close` successfully without any errors. – coding Oct 02 '20 at 16:59
  • But when I run using this code: `int i = cmd.ExecuteNonQuery();`, I get this error: `System.Data.SqlClient.SqlException: 'Could not find stored procedure 'proc_insert'.'` What could this depend on? `sp_insert` gives this error: `System.Data.SqlClient.SqlException: 'Could not find stored procedure 'sp_insert'.'` – coding Oct 02 '20 at 16:59
  • answers updated, check which stored procedure you want is existed or not. – VietDD Oct 02 '20 at 17:03
  • I am not sure if I understand. Should I check somehow if `proc_insert` is a supported command. I am not sure how to check this or how to return supported commands? – coding Oct 02 '20 at 17:06
  • no, you have to create that by your self, create tables, create stored procedures, ... – VietDD Oct 02 '20 at 17:07
  • without stored procedures, you can write query like : insert into table A(col1, col2, col3) values (1, 2, 3) – VietDD Oct 02 '20 at 17:09
  • yes I am sorry, the images you posted doesn't display in my chrome browser(some bug). I could see them now in the opera browser. Now I could see that you had procedures in that folder. I see, this is a new thing. I don't know how to create such procedures. Should I code this somehow? (Sorry for my questions, it is my first attempt with SQL) – coding Oct 02 '20 at 17:10
  • you can see guide to create store procedures by Microsoft here : https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/create-a-stored-procedure?view=sql-server-ver15 – VietDD Oct 02 '20 at 17:12
  • then how to excute that from C# here : https://stackoverflow.com/questions/1260952/how-to-execute-a-stored-procedure-within-c-sharp-program – VietDD Oct 02 '20 at 17:13
  • I think that's all you need. Upvote and mark as answer if my answer help you solved your problem. – VietDD Oct 02 '20 at 17:15
  • that is great. I think I need to learn how to create those procedures. It seems powerful to understand that part also. I should look into that separately how to write that type of code and then try something from that. I will read your links and try to get a start there. It was very helpful. I marked this as answer ofcourse. Thank you very much for your help. A really great start!! Thank you! – coding Oct 02 '20 at 17:18