Connection to SQL Server Database inside Visual Studio 2012 C#

笑着哭i 提交于 2019-12-24 00:49:34

问题


Forgive me if this is easy and I have seen similar posts but I am new-ish to C# and have been struggling on this, so any help would be much appreciated.

I am trying to connect to a local DB SQL Server in Visual Studio 2012 but so far have had no luck.

I got my connection string from the properties of my local DB which in the picture is in the left hand pane.

public void connection()
{

    string connectionString = "Data Source=(localdb)\v11.0;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";

    SqlConnection con = new SqlConnection(connectionString);

    try
    {
        con.Open();
        lblConnectionTest.Text = "Connected successfully";

    }
    catch (SqlException ex)
    {
        lblConnectionTest.Text = ex.Message;
    }


} 

At this point, all I am trying to do is establish a connection to the DB and basically write out "connection successful" etc if it connects.

Currently with what I have, I receive the following error:

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)

What am I doing wrong here?

Many thanks!


回答1:


If you are in C#, you can create an application config file (App.config), which will be having the connection string with its name.

this is sample code in the app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
    <connectionStrings>
       <add name="myConnString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\AppsTest\Nov17RoomBooking\dbRoomBooking.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
    providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

Then Your code should look like this:

private static string sqlConnectionString = ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString;

    private void DeletingDataBase()
    {
        using (SqlConnection sqlConn = new SqlConnection(sqlConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                string sqlQuery = "SELECT, INSERT, UPDATE, DELETE";
                cmd.Connection = sqlConn;
                cmd.CommandText = sqlQuery;
                try
                {
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                }
                catch { }
                finally
                {
                    cmd.Connection.Close();
                }
            }
        }
    }



回答2:


Firstly i suggest you to set conenction string in your config file.

link : http://msdn.microsoft.com/fr-fr/library/ms254494(v=vs.110).aspx

Second subject, best practise set your connection in using bloc

link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx

DataSource is your target sql server, access properties of your server and get name, but for your case i think that you want access remotly, so ensure that your firewall server is configured to allow.




回答3:


I encourage you to start learning LINQ to SQL. In my opinion it's the better way for handling data and interacting with the database. I see you're trying to connect to MySql, but i really don't know if that's possible while using LINQ. I hope someone answers this question.




回答4:


You can actually solve all of this with few clicks, im using visual studio 2012 and by pulling my ms sql table to the aspx file it actually forms the table on its own and even builds all the connection strings for you.




回答5:


Your Connection String is wrong.

Correct Syntax for MS SQL SERVER 2012 Express (Built in )

lets suppose my DataBase File is at the path :

C:\Users\Zohair\Documents\Visual Studio 2012\Projects\Learning2\Learning2\Sample.mdf

My Connection String will be :

SqlConnection conn = new SqlConnection("Data Source=(localdb)\\v11.0;Integrated Security=true;AttachDbFileName=C:\\Users\\Zohair\\Documents\\Visual Studio 2012\\Projects\\Learning2\\Learning2\\Sample.mdf"); 

NOTE: If it gives an error when using single slashes (\) then replace them with double slashes (\\)



来源:https://stackoverflow.com/questions/20269074/connection-to-sql-server-database-inside-visual-studio-2012-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!