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

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

Related

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.

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/

asp.net connecting to an external database

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.

C# WebSite connection to a mySQL database

I want to connect my WebSite to a local database.
My connection String is the following:
<connectionStrings>
<add name ="localhost"
connectionString="server=localhost;user id=root;persistsecurityinfo=True;database=doctorappointments"
providerName="MySql.Data.MySqlClient"
/>
I can connect from MySql Workbench and also from Visual Studio if I add a new connection in Server Explorer. The connection String from above is the same as the one from server Explorer.
I checked that my server is running, I also put a firewall rule for the port that it connects to.
This how I am using the connectionString:
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["localhost"].ConnectionString))
{
con.Open();
Response.Redirect("MainPage.aspx");
}
And on the con.Open() it gives me this error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in >System.Data.dll but was not handled in user code
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)
and also:
ServerVersion 'con.ServerVersion' threw an exception of type 'System.InvalidOperationException' string {System.InvalidOperationException}
I am new to this and I have tried everything I found online. I do not know what am I doing wrong...
SqlConnection is for Sql Server.
Make sure you have installed MySql.Data via nuget package and use MySqlConnection instead.

ADO.NET: Open SQL Connection

i want to do some sql code run in my webservice in c#
the code is just
[WebMethod]
public void GetCustomers()
{
SqlConnection MyConn = new SqlConnection("Data Source=./SQLEXPRESS;AttachDbFilename=C:/Documents and Settings/Administrator/My Documents/Visual Studio 2008/Projects/WebService2/WebService2/App_Data/Database1.mdf;Integrated Security=True;User Instance=True");
MyConn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "delete from t1 where name='1'"; //just see ["+month
// [mon+"] it's imp
cmd.ExecuteNonQuery();
}
now i get error like
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)
Correct Format:Server=.\SQLExpress;AttachDbFilename=c:\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
Try:
"Data Source=./SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\WebService2\WebService2\App_Data\Database1.mdf; Database=YourDatabasName;Integrated Security=True;User Instance=True"
For more details see:
http://connectionstrings.com/
You might want to check the configuration of your SQL Server as well.
The error remarks the issue could be the named pipes not being active, this is the default setting.
You can always test this fix by going;
Start -> SQL Server xxxx -> Configuration Tools -> SQL Server
Configuration Manager
Where xxxx is the version of SQL Server you are using.
In the tree look at the
-> SQL Native Client xx Configuration -> Client Protocols
Named Pipes is listed.
Set it to being Enabled
Then under
SQL Server Network Configuration -> Protocols for xxxxxx
xxxxxx Being the name of your SQL Server database instance name.
Check that Named Pipes are Enabled there also.
You will need to restart your SQL Server database in order for it to accept Named Pipe calls.
Might be worth a try.

Categories