[c#] Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

Evening all,

I'm trying to connect to a SQL Server 2012 database from C#. My connection settings when using SQL Server Management Studio are as below:-

Server Type:    Database Engine
Server Name:    Paul-PC\SQLEXPRESS
Authentication: Windows Authentication
Username:   Greyed out
Password:   Greyed out 

The name of the database I'm trying to connect to is "testDB".

Here's my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DatabaseConnection
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            SqlConnection myConnection = new SqlConnection("server=localhost;" +
                                       "Trusted_Connection=yes;" +
                                       "database=testDB; " +
                                       "connection timeout=30");
            try
            {
                myConnection.Open();
                MessageBox.Show("Well done!");
            }
            catch(SqlException ex)
            {
               MessageBox.Show("You failed!" + ex.Message);
            }

        }
    }
}

Unfortunately, my code fails to connect with the following error:-

"You failed!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."

Any suggestions? SQL Server is running locally.

This question is related to c# sql sql-server

The answer is


Note to under

connetionString =@"server=XXX;Trusted_Connection=yes;database=yourDB;";

Note: XXX = . OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 &...

you can replace 'server' with 'Data Source'

too you can replace 'database' with 'Initial Catalog'

Sample:

 connetionString =@"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;";

Try:

SqlConnection myConnection = new SqlConnection("Database=testDB;Server=Paul-PC\\SQLEXPRESS;Integrated Security=True;connect timeout = 30");

Replacing server=localhost with server=.\SQLEXPRESS might do the job.


use this style

@"server=.\sqlexpress;"

I tested all the answers here, but for me, none worked. So I studied a bit the problem, and finally I found the connection string needed. To get this string, you do:
1. in you project name:
a. right click the project name,
b. click Add,
c. select SQL Server Database (obviously you can rename it as you wish).
Now the new desired database will be added to your project.
2. The database is visible in the Server Explorer window.
3. Left click the database name in the Server Explorer window; now check the Solution Explorer window, and you will find the "Connection String", along side with Provider, State, Type, Version.
4. Copy the connection string provided, and put it in the Page_Load method:

string source = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\x\x\documents\visual studio 2013\Projects\WebApplication3\WebApplication3\App_Data\Product.mdf;Integrated Security=True";
SqlConnection conn = new SqlConnection(source);
conn.Open();
//your code here;
conn.Close();

I renamed my database as Product. Also, in the "AttachDbFilename", you must replace "c:\x\x\documents\" with your path to the phisical address of the .mdf file.

It worked for me, but I must mention this method works for VS2012 and VS2013. Don't know about other versions.


In your connection string replace server=localhost with "server = Paul-PC\\SQLEXPRESS;"


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd