Connect to External SQL Database in C# - c#

I've got an SQL server and database setup on an external server (let's call the domain name "hello.com" for the purposes of this), and I want to connect to this server via a C# program. So far I have this (All server/database details are different to the real ones):
private static void SetupSQL()
{
string connectionString = "server=hello.com; database=db1; uid=user1; pwd=xxxxx;";
connection = new SqlConnection();
connection.ConnectionString = connectionString;
try
{
connection.Open();
Console.WriteLine("Connected");
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
}
This is giving me an error message:
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)
I have checked all the connection string, and I am allowed remote access, as I have SQLWorkbench open querying the database right now on the same computer.
Any ideas?

You'll need the MySQL driver:
http://dev.mysql.com/downloads/connector/net/
You can then use the the MySqlConnection connection class to connect.
MySqlConnection connection = new MySqlConnection(connectionString);
http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL

You can't use SqlConnection object to connect to MySQL database, you should use MySqlConnection instead after you import its dll

Related

C# MySQL error System.Data.SqlClient.SqlException:

Hello i get this error every time when i click on button. I tried running it on both local host and my remove mysql server.
Visual studio 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)'
I tried putting this into mysql console:GRANT ALL PRIVILEGES On movedb TO root#localhost IDENTIFIED BY ''; FLUSH PRIVILEGES;
Any ideas what do do with it?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Server=localhost;Database=movedb;Uid=root;Pwd=;");
SqlCommand cmd = new SqlCommand("SELECT usertype FROM table1", cn);
cmd.Parameters.AddWithValue("usertype", usertype.Text);
cn.Open();
string usertype123= cmd.ExecuteScalar()?.ToString();
if (usertype123 == "admin")
MessageBox.Show("yes");
else
MessageBox.Show("You can't access this part of the program. For questions call 867-5309.");
cn.Close();
}
You need install MySql.Data for MySQL by Install-Package MySql.Data
And use MySqlConnection instead of SqlConnection
Refer How to connect to MySQL Database?

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.

I am running a local mysql database on my computer using wampserver. I have made a c# console application that I want to use to update values in a table. However I am having issues connecting to the database. My password is an empty string.
string user = "John Doe";
string queryString = "UPDATE users SET is_awesome=1 WHERE user=#a1";
string connectionString = "Server=localhost;Database=mydatabase;User Id=root;Password=;";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand(queryString, connection);
cmd.Parameters.Add("a1", user);
cmd.ExecuteNonQuery();
However when I attempt to run this code I get the following error:
System.Data.SqlClient.SqlException
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)'
Inner Exception
Win32Exception: The system cannot find the file specified
I believe my database allows remote connections because I am able to connect to it using a different php application I am running. How can I connect to a sql database from c# and run my query?
You must connect to MySql witch is specific for MySql Like MySqlConnection for more look this tutorial
or this

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

SDF Local database Connection error: 40

Hi I am trying to connect to a local SQL Server Compact database (.sdf) in a Windows forms project and have been facing this problem for quite some time. I am not allowed to use datasets for the project, all the queries and connections are written in the application.
System.Data.SqlClient.SqlException
A network-related or instance-specific error occurredwhile 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)
Code:
SqlConnection _Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["restaurant"].ToString());
SqlCommand _Command = _Connection.CreateCommand();
_Connection.Open(); // <- throws exception
To connect a Sql Server Compact you need a different set of classes contained in the namespace SqlServerCe (SqlCeConnection, SqlCeCommand and so on....)
SqlCeConnection _Connection = new SqlCeConnection(ConfigurationManager.ConnectionStrings["restaurant"].ToString());
SqlCeCommand _Command = _Connection.CreateCommand();
_Connection.Open();
of course, you need to reference the assembly that contains the above mentioned classes.
System.Data.SqlServerCe.dll (ADO.NET provider)
and add the using statement
using System.Data.SqlServerCe;

Creating database in SQL Server Express using SMO

I'm trying to create a database in SQL Server Express using WinForms and C#
Here is what I'm trying to do
Microsoft.SqlServer.Management.Smo.Server srv = new Microsoft.SqlServer.Management.Smo.Server srvServer();
int i = srv.Databases.Count;
just to get the count at the start. But I get the 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) this is the stack track
at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
at Microsoft.SqlServer.Management.Common.ConnectionManager.get_ServerVersion()
at Microsoft.SqlServer.Management.Smo.ExecutionManager.GetServerVersion()
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.GetDbComparer(Boolean
inServer)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.InitializeStringComparer()
at Microsoft.SqlServer.Management.Smo.AbstractCollectionBase.get_StringComparer()
at Microsoft.SqlServer.Management.Smo.SimpleObjectCollectionBase.InitInnerCollection()
at Microsoft.SqlServer.Management.Smo.SmoCollectionBase.get_InternalStorage()
at Microsoft.SqlServer.Management.Smo.SmoCollectionBase.InitializeChildCollection(Boolean
refresh)
at Microsoft.SqlServer.Management.Smo.SmoCollectionBase.get_Count()
at CreateDB.CreateDB.btnCreateDB_Click(Object sender, EventArgs e) in C:\Users\Guest1\Downloads\CreateDB\CreateDB\CreateDB.cs:line 82
What should be done?
If you're using SQL Server Express, and you've installed with all the defaults, then your server instance will be called .\SQLEXPRESS. You need to use that in your code:
using Microsoft.SqlServer.Management.Smo;
Server srv = new Server(".\\SQLExpress");
int i = srv.Databases.Count;
If you create a new Server instance without specifying an instance name, it tries to connect to the default instance (with no name) - which you don't have, if you've installed just SQL Server Express.
First make the connection by using the SqlConnection object. you should do this
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLExpress;Initial Catalog=master;Integrated Security=True");
Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(new ServerConnection(conn));
int i = server.Databases.Count;

Categories

Resources