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!
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.
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();
}
}
}
}
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.
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.
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 (\\)
Related
So, I want to create a SQL database in Microsoft SQL Management Studio and connect it to Microsoft Visual Studio. I linked the database to Visual Studio and it worked. Now, I want to open that connection to test it with a button on a windows form application. Every time I try, it says "invalid pointer" but the database name is correct. I don't know what is wrong.
I still get the invalid pointer error...My instance name is DESKTOP-BJSAO6B but it doesnt seem to work...
You need provide a proper connection string like
string connectionString =
"data source=.\SQLEXPRESS;initial catalog=student;integrated security=True;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
MessageBox.Show("You are connected");
}
where SQLEXPRESS - name your MSSQL instance ( may be different). More you can see here
For Ex:
string connectionString = "Data Source=Server-Name; Initial Catalog= Database-Name;Integrated Security=True"; //If you are using a local Database.
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
MessageBox.Show("You are connected");
I am not sure what I am doing wrong, If I use the connection string shown here, my application works fine.
SqlConnection conn = new SqlConnection();
string DbPath = Application.StartupPath;
DbPath = DbPath.Substring(0, DbPath.LastIndexOf("\\bin"));
DbPath = DbPath + "\\MyDatabase.mdf";
conn.ConnectionString = "Data Source=.\\EXPRESS2008;AttachDbFilename=" + DbPath + ";Integrated Security=True;User Instance=True";
but if I use connection string here, it's not inserting data into MyDatabase table
conn.ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString;
My app.config is
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="ERPSystem.Properties.Settings.MyDatabaseConnectionString"
connectionString="Data Source=.\EXPRESS2008; AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated
Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
INSERT statement and preceding code:
comm = new SqlCommand("CreateUser", MyConnection.MyConn("Open"));
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("#UserName", SqlDbType.VarChar).Value = userName.Text;
comm.Parameters.Add("#Password", SqlDbType.VarChar).Value = userPassword.Text;
comm.Parameters.Add("#UserRole", SqlDbType.VarChar).Value = UserRole.SelectedItem.ToString();
comm.ExecuteNonQuery();
This is the code to get the connection
class MyConnection
{
public static SqlConnection MyConn(string str)
{
SqlConnection conn = new SqlConnection();
try
{
//get application path
string DbPath = Application.StartupPath;
if (Program.RunFrEn == true) //bool var
//remove string after bin folder
DbPath = DbPath.Substring(0, DbPath.LastIndexOf("\\bin"));
//add database name with new path
DbPath = DbPath + "\\MyDatabase.mdf";
//generate new connection string for database
conn.ConnectionString = "Data Source=.\\EXPRESS2008;AttachDbFilename="
+ DbPath
+ ";Integrated Security=True;User Instance=True";
//conn.ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString;
if (str == "Open")
{
if (conn.State == ConnectionState.Closed)
conn.Open();
}
else
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return conn;
}
}
I am not getting any error
Thank you
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
I also had fighted long time with same problem. And I saw many same questions & answers.
You're using |DataDirectory|. I assume you can get values from the DB file and you don't get error to run insert command but the values are not inserted into the DB file.
This is absolutely my private idea and my private conclusion is that this behavior is normal as |DataDirectory| does. I mean a data file of an application should be protected from manipulation once after deployment. The 'Data' file should provide data inside the file so that we can read the data.
Therefore, I coded to create a localDB .MDF file (SQL Server 2014) from users' side so that my applications can utilize the localDB to write and read data. My application automatically downloads data from cloud server which are we need to update frequently. On the other side, I put big and already fixed data into |DataDirectory| .MDF file, I mean inserted big data for read only and add the .MDF file to my project before deployment.
Hope my experience helps.. But, please keep in mind again that this is really my private opinion and I might be totally wrong and my experience is limited only to localDB. But again, I couldn't find a Microsoft's official document mentioning this behavior.
Do you have only 1 option like |DataDirectory|? Did this work to insert before? Is this code by you wrote on your own? If possible, try to find another option rather than |DataDirectory| to connect to the SQL Server database. I use a cloud SQL server with IP address but I can't understand why you use |DataDirectory|. There might be many various options as connection strings to SQL Server Express.
So I'm following this tutorial: http://support.microsoft.com/kb/314145/
and I get an unexpected error: A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
My class looks like this:
class Database
{
public Database()
{
string connectionString = "Password=pass;User ID=userid;Initial Catalog=soksko;Data Source=(local)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
Console.WriteLine("Database: OK");
}
}
I googled, but I couldnt find anything valuable. I am using MySQL database, it is on the same computer and I am using VS 2013. I successfully added my database to Server Explorer with the same connection information that I use above, but I get exception, when I try to open the connection.
See this link for how a MySQL connection string should look:
ASP.NET use SqlConnection Connect Mysql
See this link for an explanation of the oft mis-used Data Source=(local):
http://blogs.msdn.com/b/sql_protocols/archive/2008/09/19/understanding-data-source-local-in-sql-server-connection-strings.aspx
hint you're not using SQL-Server so it won't work for you
SqlConnection is for MS SQL Server. For MySql you need to use a MySqlConnection class provided by the MySQL connector (http://dev.mysql.com/doc/connector-net/en/index.html)
using MySql.Data.MySqlClient;
using(MySqlConnection myConnection = new MySqlConnection(myConnectionString))
{
myConnection.Open();
// execute queries, etc
}
The tutorial you're using is for Sql Server, not MySQL.
This is not the first time I have used databases using the C# in asp.net, but I can't seem to make it work in a Winforms app.
This is a test face, so there is not a real database but a SQL Server database file that I created.
What I have is this:
public AddControl SaveResearcher(string name)
{
using(SqlConnection conn = new SqlConnection("")){
SqlCommand cmd = new SqlCommand("INSERT INTO Personell VALUES (#name, #function)", conn);
cmd.Parameters.Add("name",SqlDbType.VarChar).Value = name;
cmd.Parameters.Add("function", SqlDbType.VarChar).Value = "Researcher";
conn.Open();
cmd.ExecuteNonQuery();
}
return AddControl.OK;
}
What do I have to put in the connection string?
Thanks in advance.
The connection string for at sql server db file without username/password
Server=.\SQLExpress;AttachDbFilename=c:\pathtodb\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
You may find more connection string options at
http://www.connectionstrings.com/sql-server-2008
You can check there,
Connection strings for SQL Server 2005
Do you mean soemthing like this?
"Data Source[SERVER_NAME];Initial Catalog=[DATABASE_NAME];Integrated Security=True;MultipleActiveResultSets=True"
connectionString="Data Source=computerName\sqlexpress;Initial Catalog=DatabaseName;Integrated Security=True"
My code is as follows:
string constring = "Data Source=132.186.127.169"+ "Initial Catalog=CadPool1;" + "Integrated Security=True";
SqlConnection con;
con = new SqlConnection(constring);
con.Open();
string query="SELECT * from CadPoolProjectTable1";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
MessageBox.Show("selected");
con.Close();
I am getting error at the line con.Open();. The error is:
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)
You are missing a ';' after the server name in the connection string.
string constring = "Data Source=132.186.127.169"+ "Initial Catalog=CadPool1;" + "Integrated Security=True";
It should be
string constring = "Data Source=132.186.127.169;"+ "Initial Catalog=CadPool1;" + "Integrated Security=True";
The error says that your app was not able to connect to the server. I would do the following.
Check for the server address (on a quick look it looks good)
Connect using management studio and in your case it should have worked.
It means the issue is with the code. Since you are concatenating the string I would debug the code and see what the end result for the connection string is.
Tip:If it is a web application add the connection string to web.config file. More info here How to: Read Connection Strings from the Web.config File
You're missing a semicolon in your connection string
Data Source=132.186.127.169;"+ "Initial...
^
If you need to build the connection string yourself you can use the SqlConnectionStringBuilder class. That way you won't to be as troubled by these subtle mistakes.
Your connection string is wrong:
string constring =
"Data Source=132.186.127.169;Initial Catalog=CadPool1;Integrated Security=True";
You don't need to concatenate the strings together, but more importantly, you were missing the semi-colon ";" between the data source and the initial catalog settings.
First, you are missing a ; (semicolon) between Data Source and Initial Catalog.
Second, if this is a newly installed SQL Server instance, you may need to go into SQL Server Configuration Manager, and enable the protocol(s) you'll need.
Please check if you can ping the server mentioned via cmd
Also try telnet to the server from your machine.
One more thing to check would be port the server is configured for if its not the default one you will have to add the port as 132.186.127.169,XXX
Servername in the connection string is wrong. and also since there are no dynamic values you don't need string concatenation. Change it to:
string constring = "Data Source=132.186.127.169;
Initial Catalog=CadPool1;
Integrated Security=True";