Cannot connect to MySQL server using connectionString - c#

I am probably missing something silly...but iv'e been trying to figure it out all day so I give up.
can anyone spot the error?
App.config
<connectionStrings>
<add name="linkednDb" connectionString="Server=.;Database=linkedin.usernames;Uid=root;Pwd=1234;" providerName="System.Data.SqlClient"/>
Query method :
public void AddUser(string username)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.Connection("linkednDb")))
{
connection.Query<User>($"INSERT INTO usernames (UserName) VALUES ('{username}')");
Console.WriteLine("adding" + username);
}
}
Helper class:
public static class Helper
{
public static string Connection(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
FORGOT TO ADD 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)'

System.Data.SqlClient is the ADO.Net provider for Sql Server, which is a different database platform entirely from MySql.
You need a MySql provider. This provider is not included with .Net out of the box, but there are a few options out there you can install and reference in Visual Studio.
While I'm here, that string substitution in the SQL code is NOT OKAY. String-substitution in SQL queries are crazy-vulnerable to SQL injection issues. This is one of the big ways applications end up hacked. Less-malicious issues can occur, too; it doesn't take an attack by a l33t hacker for this cause problems. Regular old Joe user can break an app doing this just by putting in real data. You need to learn how to use parameterized queries.

Related

Visual Studio connects to database, but application within using the same connection string cannot

Using SSMS and Visual Studio 2015's Server Explorer tab under Data Connections, I can execute queries on remote server KOSH without issue. Why is the MVC application running locally in Visual Studio/IIS Express unable to do the same?
Using VS2015's connection Properties, I get its connection string:
Data Source=123.456.78.9;Persist Security Info=True;User ID=Foo;Password=Bar
Using that connection string, the MVC application is greeted with:
"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)"
Inner exception message:
"The network path was not found"
I know the server/firewall/network settings are correct. That leaves the application.
using(var connection = Database.Connection(conInfo.ConnectionString, provider)) {
// rowCountSql: SELECT SUM(rows) TM_ROWCOUNT FROM sys.partitions
// WHERE object_id = object_id(#tableName) and index_id IN (0,1)
// Any other SQL yields same error
var countTask = connection.QueryAsync(rowCountSql, new { tableName = Editor.TableName });
}
Async is used because the Oracle version of the query can take several seconds to return.
The application should be correct because it connects to the same server from home (also the server's location) and to identical databases in remote data centers running 2008R2 to 2014 without a problem.
Database.Connection() is:
// This is unlikely to be the problem as it is very well tested
public static DbConnection Connection(string connectionString, string databaseProvider) {
DbProviderFactory databaseFactory = DbProviderFactories.GetFactory(databaseProvider);
DbConnection connection = databaseFactory.CreateConnection();
if(connection != null)
connection.ConnectionString = connectionString;
return connection;
}
I bet I am missing something simple, but I would be grateful for help on what that could be.
As I said in comments, maybe the piece of your code:
conInfo.ConnectionString
does not contains the correct connection string you want.
Check it out

Connection Error in SQL Server Compact with ASP.Net

I am trying to access a database, using a DataSet. I am using Visual Studio for Web Express 2013, ASP Web Forms project with SQL Server Compact 4.0. I created the database from Database Explorer, added 3 tables, now my code has getData, setData methods which will use Dataset to get data.
But the SqlConnection object is throwing exception at runtime.
[SqlException (0x80131904): 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)]
I guess this is due to connection string since error is at line:
SLQCon.Open();
I have tried more than one method but none of them has worked yet. These are few of them,
msdn link
Connection Strings
The other things work fine (web form controls), only problem is when I do something related to database, any fixes?
My code is as follows:
void setData(string tableName) {
string ConString = #"Data Source=" + "F:\\Github\\JournalClassifier\\WebApplication1\\WebApplication1\\App_Data\\KeywordsDB.sdf" + ";Connect Timeout=30";
SQLCon.ConnectionString = ConString;
SQLCon.Open(); // Exception here
// insertion code
}
Make sure your database inside App_Data folder on your root application. and change the connection string to this one
<add name="ConnectionStringName"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=\KeywordsDB.sdf;Connection Timeout=30" />
things you need to concern is you are using SQL Server Compact, so the provider name need use System.Data.SqlServerCe.4.0 otherwise it will confused with SQL Server Client

Two database connection strings in app.config with EF code first approach causing error

I have code first entity model designed and working fine as follows:
<add name="DemoEntities" connectionString="metadata=res://*/DemoDataModel.csdl|res://*/DemoDataModel.ssdl|res://*/DemoDataModel.msl;provider=System.Data.SqlClient;
provider connection string="data source=myservername;initial catalog=DemoDB;user id=demouser;password=abcd123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="SecondDemoEntities" connectionString="metadata=res://*/SecondDemoDataModel.csdl|res://*/SecondDemoDataModel.ssdl|res://*/SecondDemoDataModel.msl;provider=System.Data.SqlClient;
provider connection string="data source=myservername;initial catalog=SecondDemoDB;user id=demouser;password=abcd123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
But first connection string is working fine and i am able to read the data. But second connection string is throwing 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: SQL Network Interfaces, error: 50 - Local Database Run time error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.''
Please help, I have done this:
Used separate entity files and declared them in the constructors:
public Application1Entities()
: base("DemoEntities")
{
}
public Application2Entities()
: base("SecondDemoEntities")
{
}
Looks like you're trying to create the second on the wrong server. At a glance, it looks like both of these reside on the same server but are using different server names.
data source=myservername;
data source=secondDemoDB
Both of those data source lines need to be the same if they are hosted on the same server. The Initial Catalog determines which database on the server that EF will draw from.
I figured out the issue. I have to declare the same connection string in UI application also. That whole thing was in my DAL library. When i declared the same connection string in my UI application everything worked well..

Connection string to SQL by EntityFramework and MVC

I write web page in MVC, which use Entity Framework as ORM mapper. I put my connection string to web.config file. Here is it:
<add name="JP_CMS" connectionString="Data Source=.;Initial Catalog=JP_CMS;
User Id=CmsWebUser;Password=abcd1234abcd1234;"
providerName="System.Data.SqlClient"/>
I try to get data by this C# code
public DataBaseContext()
: base("JP_CMS")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DataBaseContext>());
}
//------------------------------
var db = new DataBaseContext();
var result = db.Articles.ToList(); //<- here is thrown exception
//------------------------------
My local SQL server is running, this table is exists, but I get excepion like in this:
I think it is the most important expection: "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)"
Could you help my by give some idea what I make wrong?
"The system cannot find the file specified" error. Check carefully your connection string.
hi Error indicates EF tried to connect to the server but failed.
Could you Checkk,
1) SQL Server should be up and running.
Go to All Programs >> Microsoft SQL Server 2008 >> Configuration Tools >> SQL Server Configuration Manager >> SQL Server Services, and check if SQL Server service status is “Running”.
In addition, ensure that your remote server is in the same network. Run “sqlcmd -L” in your command prompt to ascertain if your server is included in your network list.
2) Enable TCP/IP in SQL Server Configuration
For more info you can go here
Instead of DataSource =. try DataSource = .\sqlInstanceName. Also DataSource=(local) might work.

Error when connecting to .mdf from ASP.NET (C#)

When trying to connect to a .mdf databse in ASP.NET (using c#) I am given this 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: SQL Network
Interfaces, error: 26 - Error Locating
Server/Instance Specified)
Does this mean my connection string is wrong? What should it be?
Aside from that, I am very new to ASP.NET. I am trying to connect to this database in the same way I would in c# normally (using data adapters and SqlCommands). Is this the right way to go about it, or is there a different way? When I started a new website adding user accounts worked (there was a wizard or something?) but I couldn't work out how to add more user information. What is the best way to connect to an SQL database and add user accounts with login and personal details in ASP.NET?
EDIT: My Connection String is data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Users.mdf;User Instance=true
If I read your connection string properly, you're never specifying a database to use!
data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\Users.mdf;User Instance=true
Add the database to the connection string - and also, loose the extra backslash after the |DataDirectory|:
server=.\SQLEXPRESS;database=YourDatabase;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|Users.mdf;User Instance=true
OK, I've fixed it. For reference for anyone else:
The correct connection string was given in the Web.config file.
The connection string I needed was Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Users.mdf;Integrated Security=True;User Instance=True

Categories

Resources