asp.net connecting to an external database - c#

I have a an external database hosted by Strato and I would like to connect my asp.net c# to the external database and insert a new user in to the database but I got an error when I tried to established the connection. The error occured at con.open(); Can anyone help me with this? I am new to asp.net so any sample code may be helpful. For now I am just trying to establish a connection to the database and transfer a static data to the table upon clicking the submit button.
web.config
<connectionStrings>
<add name="ApplicationServices"
connectionString="server=rdbms.strato.de;database=DB33321; UID=abc123; password=pass123"
providerName="System.Data.SqlClient" />
</connectionStrings>
aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("insert into USER"+"(name)values(kim)");
Response.Write("Registration success!");
con.Close();
}
The error i received:
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 probably found examples of connecting to a database without realizing there are several providers for ADO.Net. For MySql you need a nuget package:
https://www.nuget.org/packages/MySql.Data/
You will then change your connection string so the Provider is not System.Data.SqlClient. I believe it should be MySql.Data.MySqlClient
Next you change your code so that it uses the correct Types. Wherever you see "Sql..." you change it to "MySql...". for instance:
SqlConnection becomes MySqlConnection.

Related

Accessing a local SQL Database created in SQL Server Management Studio in a c# windows form?

Here is my Code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=DESKTOP-BPRGRPB/SQLEXPRESS;Initial Catalog=Test;Integrated Security=True");
connection.Open();
MessageBox.Show("connected!");
}
I pulled the ConnectionString from the Server Explorer in VS2022. The following Error occurs after the ConnectionTimeout.
Microsoft.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 network name cannot be found.
This is my first time using a database so I have no idea what I am doing. I just wanted to get it a shot and see if I could get a connection to a database running. I, also, tried using a SQLConnectionStringbuilder to make a Connection String with no luck.
I checked to setting is SQL Server Management Studio and remote connections are allowed.
Thanks for any help.

Problems with SQL Server connection in console app

The SQL server is located on a remote machine.
I can connect to it with MVC app.
I can connect to it with SSMS.
But I can not do it in console app.
Neither entity nor SqlConnection is working.
Connection string is the same as in console and mvc app (which works). What can it be? Any ideas?
Error I am getting
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)'
What can it be?
<add name="DBContext" connectionString="data source=serverip;initial catalog=catalogue;user id=user;password=password;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=serverip;initial catalog=catalogue;user id=user;password=password;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient";
cn.Open();
Console.WriteLine(cn.State.ToString());
The problem is that console app uses 445 and 139 port. In terms of security. But why MVC app doesn't use it. And how I can I use it without opening this port. Even dividing db part in different library didn't work.

I can't connect to SQL Server database with C# code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was trying to create registration form but when I run my project am getting this error message
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
My code:
using System;
using System.Data;
using System.Data.SqlClient;
namespace Registration{
private void Register_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SHAB
SQLEXPRESS;InitialCatalog=Phonebook;Integrated Security=True");
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[registration]([username[fullname],[Password]) VALUES('" + username.Text+"', '"+fullname.Text+"', '"+password.Text+"')");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Congradulation You have been Registered");
}
The error appears on the line con.open();.
Exception thrown: 'System.Data.SqlClient.SqlException' 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
You are missing a comma between [username] and [fullname]. Try like:
INSERT INTO ... ([username], [fullname], ...
Also it is very important to use sql Parameters
First Check SQL Server Service is running.
after that check Data Source value in your Connection String, if you are using SQLExpress then it may be
SqlConnection con = new SqlConnection("Data Source=SHAB\SQLEXPRESS;InitialCatalog=Phonebook;Integrated Security=True");
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.
As the error indicates, your connection unable to reach SQL Server, make sure you are able to do telnet SHAB 1433
If Telnet fails:
Make sure TCP/IP protocol enabled, you can verify it via SQL Server Configuration manager (following screenshot for reference)
Verify the custom port NOT Configured (via SQL Server Configuration manager) for SQL Express service
If the custom port NOT configured
Make sure SQL Browser service is running
Create a rule in Windows Firewall to accept incoming connections on TCP ports 1433 and 1434 (TCP and UDP) - This must be done at the server where SQL Service is running
Restart SQL Browser service
Your connection should work here with DataSource=SHAB\\SQLEXPRESS. You can do telnet SHAB 1433 to verify
If the custom port configured
Create a rule in Windows Firewall to accept incoming connections on Custom TCP ports - This must be done at the server where SQL Service is running
Restart SQL Service
Your connection should work here when you use DataSource = SHAB,<custom port>. However, you can do telnet SHAB <custom port> to verify
SQL Server Configuration manager:
Your connection string must be in app.config file
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=.\SQLEXPRESS;Initial
Catalog=dbname;Integrated Security=True"
providerName="System.Data.EntityClient"
<connectionStrings>
import configuration from
using System.Configuration;
Add DB Connection
public string DbCon =
ConfigurationManager.ConnectionStrings["DbConnection"].ToString();
var Query=#"INSERT INTO [dbo].[registration]([username[fullname],[Password]) VALUES('" + username.Text+"', '"+fullname.Text+"', '"+password.Text+"')"
using (con = new SqlConnection(DbCon))
{
con.Open();
SqlCommand com = new SqlCommand(Query, con);
com.ExecuteNonQuery();
con.Close();
}
I think that you just have omitted the username and the password in your connection string.
Try the following code.
Data Source=YourServer;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=YourPassword

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 to connect to Oracle DB from .NET?

When I open SQL Command Line, I write CONNECT username/password#[//]host[:port][/service_name] and it connects me to the database just fine. However, I'm unable to connect from a .NET project using a connection string. I have tried many things such as <add name="ConnectionString" connectionString="Data Source=username/password#[//]host[:port][/service_name];" /> and <add name="ConnectionString" connectionString="server=tcp:host;Initial Catalog=service_name; user id=username; password=password; Connection Timeout=180;" providerName="System.Data.OracleClient" />, but nothing worked so far. Whenever I get to sconn.Open(); in the following:
var CurrentConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection sconn = new SqlConnection(CurrentConnectionString);
sconn.Open();
I practically always get 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: SQL
Network Interfaces, error: 25 - Connection string is not valid)
How can I connect to the database properly?
Try following connection string
string con = "Data Source=(DESCRIPTION =(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST = 000.00.0.00)(PORT = 0000)))(CONNECT_DATA =(SERVICE_NAME = database)));User ID=User/Schema;Password=password;Unicode=True";
& then use this conection string as follow
using (OracleConnection objConn = new OracleConnection(con))
{
\\ code
}
I highly recommend using the "Official Oracle ODP.NET, Managed Driver".
https://www.nuget.org/packages/Oracle.ManagedDataAccess/
Or the one for Entity framework:
https://www.nuget.org/packages/Oracle.ManagedDataAccess.EntityFramework/
After installing via Visual Studio it opens a readme that I also recommend you read.
Oracle provide massive amounts of documentation. This is where to start:
http://www.oracle.com/technetwork/topics/dotnet/whatsnew/index.html
You use System.Data.SqlClient.SqlConnection which is used to connect to a (Microsoft) SQL Server, it cannot be used for an Oracle connection.
You should use System.Data.OracleClient.OracleConnection or Oracle.ManagedDataAccess.Client.OracleConnection
Have a look at this answer to see other possibilities:
How to connect to Oracle 11 database from . net
You can always use EF, and use create one ADO.Net Entity Data Model
And use the wizard to create and test the connection

Categories