Connection string ASP.NET LocalDB - c#

I currently have a problem where I can't connect a database on my server but it works fine when running locally. I am using this connection string in the controller:
#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='|DataDirectory|\Test.mdf';";
Controller code:
namespace PathTest.Controllers
{
public class HomeController : Controller
{
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='|DataDirectory|\Test.mdf';";
public ActionResult Index()
{
DataTable daTbl = new DataTable();
using(SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Numbers", sqlCon);
sqlDa.Fill(daTbl);
}
return View(daTbl);
}
}
}
Error when running on server:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: 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: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Specified LocalDB instance name is invalid.)
Any help would be appreciated

First of all, I believe that you don't want to run the localdb on production server. You should deploy, if not did yet, a SQL Server instance on your server, so the connection string should be:
"Server=[Server IP/Name];Database=MSSQLLocalDB;User Id=[Some User Created];Password=[Password of User Created];"
If I'm wrong, and you want the localdb on server, you need to check if the SQL Server Express Service is running.
If so, check if the database file exists, if not, you can create an local database for express instance with the tool sqllocaldb.
And for the last, you can keep the two connection strings, using the Configuration Manager by the .config files (you can use the local db on Debug profile and the server db on Release profile).
I hope it helps you!

Related

Unable to connect to MySql Server in Visual C#

I am trying to create a local database using MySql in Visual C# but connection is not getting established in the code but when i add the server in the server explorer under data connections its working. I tried test connection it says connection succeeded but its not working in the code.
string connStr = "server=localhost;user=root;database=entry_database;password=superadmin";
con = new SqlConnection(connStr);
This throws an error saying
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 cannot use the SqlConnection class to connect to a MySQL server; that is for Microsoft SQL Server only.
Instead, install the MySqlConnector NuGet package and use the following code:
string connStr = "server=localhost;user=root;database=entry_database;password=superadmin";
using (var con = new MySqlConnection(connStr))
{
// ...
}
Your connection string is wrong.. change keys "user" to "Uid" and "password" to "Pwd".
follow eg:
string connStr = "server=localhost;Uid=root;database=entry_database;Pwd=superadmin";
con = new SqlConnection(connStr);
Correct, the format used by you to create the connection string is incorrect, giving you the error you mentioned above.
Actually, the way the connection string is written in MS-SQL is very different from MY-SQL. Every database has its own way of connecting and its individual connection tags:-
Please find the list of connection details for MS_SQL below. This would help you not only in the current mentioned scenario but also will provide a reference for future changes:-
https://www.connectionstrings.com/mysql/

How can I connect to a local MySQL database using System.Data.SqlClient.SqlConnection? Using C# .Net 4.6.1

I'm designing a WPF form that needs to connect to a local MySQL database. I've installed mysql on my local machine and created a database, with a username and password to connect to it. See two screenshots below for more information.
My code currently looks like this:
public static bool InitialConnection()
{
try
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = "Server=127.0.0.1;Database=StudentTravelPlannerDB;Uid=STPUser;Pwd=CORRECT_PASSWORD;";
con.Open();
}
return true;
}
catch
{
return false;
}
}
However, when I run my WPF form, which calls this function, it always freezes for a few seconds, and the above function will return false.
Removing the try/catch statements, the application fails and gives me an error pointing to the 'con.Open()' line, stating:
"An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: 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)"
So what could be the problem here? My password is definitely correct. I think I laid out the connection string right, and I've tried different variants and it's always the same response, adding the port doesn't help either.
Any guidance or solutions appreciated, thank you.

provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server, pgsql

I am using Dapper to connect to pgsql database. The below code was working few days back. But don't know why its not working now. The same credentials are working with pgadmin3 but not with the c# code.
here is the controller method, for simplicity I wrote all db code in Get method.
the below code was
public IEnumerable<Item> Get()
{
string connString = "Server=192.168.1.11;Database=db_alpha1;Uid=postgres;Pwd=xxxxxx";
using (IDbConnection db = new SqlConnection(connString))
{
db.Open();
return db.Query<Item>("Select * From items").ToList();
}
}
Here is the error on line db.Open();:
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)
Also, I already configured pg_hba.conf file, added my system ip address.
Thanks to #Steve. The issue has resolved, it was a silly mistake, I replaced
SqlConnection with NpgsqlConnection, and added npgsql package.

ASP.NET Failing to enter data into database

I recently uploaded my data driven ASP.NET application to a asp hosting service called SmarterAsp.com.
Everything in the website works fine, all but 1 feature, data can't be entered into the database.
However when using a gridview control to see data in the database the data is displayed perfectly and I can even insert, update and delete data through the gridview.
I uploaded my database in a separate space on the hosting service and I was provided with a connection string, I replaced all connection strings in my application with the provided connection string.
It works fine in my IDE, the problem only came once I uploaded the website to the hosting service.
Here is my C# code for inserting data into my database:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(#DataSource=SQL5004.Smarterasp.net;Initial Catalog=DB_9DE115_hmkdatabase;User Id=DB_9DE115_hmkdatabase_admin;Password=YOUR_DB_PASSWORD;"))
{
SqlCommand cmd = new SqlCommand(#"INSERT INTO Clients(ClientName)VALUES(#ClientName)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#ClientName", TextBox1.Text.ToString());
connection.Open();
cmd.ExecuteNonQuery();
}
}
And here is the error I get when attempting to insert the data:
Server Error in '/' Application.
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: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
Description:
An unhandled exception occurred during the execution of the current
web request. Please review the stack trace for more information about
the error and where it originated in the code.
Exception Details:
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: SQL Network Interfaces, error: 26
- Error Locating Server/Instance Specified)
My first thought was that it's a problem with the connection string, but the connection string works fine with the rest of the application. I can enter data into my database through the gridview add function but I cannot enter data using the C# codebehind page. As I said it works fine in my IDE, the problem only came once I uploaded the website to the hosting service.
Thanks in advance for the help guys. You guys are real life heroes!
I sorted out the problem. My problem was where I initialized the connection string and where I opened the connection. I initialized the connection string at the top where the page is initialized. And then replaced where the connection string was with connection.open();
Thanks for all the help guys!

ASP.NET Connection string error when using ip address

I'm trying to debug an ASP.NET page I have trying to connect to a local SQLServer DB, when the connection string I'm using has the name of the local machine, it works fine like in below
string ConnectionString = "Integrated Security=SSPI;" +
"Initial Catalog=ARTICLEDB;" +
"Data Source=MYMACHINENAME\\MYSQLSVR;";
... later on...
conn = new SqlConnection(ConnectionString);
// Open the connection
try
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
//don't work here when using ##.##.##.##\MYSQLSVR as datasource
}
return true;
}
catch
{
return false;
}
when I use the IP machine as the value for the datadource such as: ###.###.###.###\\\MYSQLSVR the I get an exception saying:
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: SQL
Network Interfaces, error: 28 - Server doesn't support requested
protocol)
This problem originated from trying to run the site from IIS and getting a similar error where the connection was not opened.
How can I reference the DB in the connection string so that IIS can find the DB?
I've also tried adding the connection string in IIS for the site but not sure how to reference that IIS connection string from my project/site
go to SQL Server Configuration Manager and turn on "Named Pipes" and "TCP/IP"
and your connection string should look like below
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;
Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;
http://www.connectionstrings.com/sql-server-2008
Check the following it is working for me.
Data Source=190.190.200.100,1433;Initial Catalog=DBName;Integrated Security=False;user id=userid;password=password

Categories