Can't Connect C# with SQL Server - c#

I am trying to write a program which interacts with my SQL Server database. I am programming in C# on Parallels on my Mac and SQL Server is running via Docker.
But I just can't connect. I am just getting the same error every time I try.
I have already tried to allow the remote access on SQL Server with:
EXEC sp_configure 'remote access', 1 ;
GO
RECONFIGURE ;
GO
but this does not solve my problem.
Here is my C# code:
main Class
Database database;
public Form1()
{
InitializeComponent();
database = new Database("localhost\\MSSQLSERVER", "user1", "topsecret", "master"); // \
}
private void connect_button_Click(object sender, EventArgs e)
{
database.Connect();
}
Database class:
class Database
{
SqlConnectionStringBuilder builder;
SqlConnection connection;
public Database(string source, string userid, string password, string initialcatalog){
this.builder = new SqlConnectionStringBuilder();
this.builder.DataSource = source;
this.builder.UserID = userid;
this.builder.Password = password;
this.builder.InitialCatalog = initialcatalog;
}
public void Connect()
{
try
{
// Connect to SQL
Console.WriteLine("Connecting to SQL Server ... ");
this.connection = new SqlConnection(this.builder.ConnectionString);
connection.Open();
Console.WriteLine("Connected");
}
catch(SqlException sqle)
{
Console.WriteLine(sqle.Message);
}
}
}
And I am always getting this error:
Network-related or instance-specific error when connecting to SQL Server. The server was not found or can not be accessed. Verify that the instance name is correct and that SQL Server allows remote connections. (provider: SQL Network Interfaces, error: 25 - connection string invalid)

The MSSQLSERVER is the instance name of the unnamed, default instance on your machine - you must not use this in the connection string.
Instead, try this line of code:
database = new Database("localhost", "user1", "topsecret", "master");
Just specify no explicit instance name at all - just localhost (or (local), or .) for the current machine - that's all you need!

It was Problem with Parallels, because Paralles can not access to localhost. So i had to define the IP from Parallels in Visual Studio like this:
database = new Database("10.211.55.2", "user1", "topsecret", "Time");

Related

How to fix network related errors in visual studio when i tried to connect to database

when i tried to run this program in visual studio 2010 its shows an error. Like this "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)"
public partial class tcregistration : Form
{
SqlConnection conn = new SqlConnection("Data Source=./SQLEXPRESS;AttachDbFilename=C:/Users/dce 3/documents/visual studio 2010/Projects/TC_Maker/TC_Maker/TC_REG.mdf;Integrated Security=True;User Instance=True");
public tcregistration()
{
InitializeComponent();
}
private void insert_Click(object sender, EventArgs e)
{
string gender = string.Empty;
if (rbmale.Checked)
{
gender = "M";
}
else if (rbfemale.Checked)
{
gender = "F";
}
string tcrecieved = string.Empty;
if (rbyes.Checked)
{
tcrecieved = "Y";
}
else if (rbno.Checked)
{
tcrecieved = "N";
}
try
{
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlCommand cmd = new SqlCommand ("TCAddorUpdate",conn);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mode","Add");
cmd.Parameters.AddWithValue("#tcnumber",txttcno.Text.Trim());
cmd.Parameters.AddWithValue("#name",txtname.Text.Trim());
cmd.Parameters.AddWithValue("#dob",dtpdob);
cmd.Parameters.AddWithValue("#religion",txtrelig.Text.Trim());
cmd.Parameters.AddWithValue("#caste",txtcaste.Text.Trim());
cmd.Parameters.AddWithValue("#sex",gender);
cmd.Parameters.AddWithValue("#doa",dtpdoa);
cmd.Parameters.AddWithValue("#regno",txtregno.Text.Trim());
cmd.Parameters.AddWithValue("#dor",dtpdor);
cmd.Parameters.AddWithValue("#dept",txtdept.Text.Trim());
cmd.Parameters.AddWithValue("#sem", combosem);
cmd.Parameters.AddWithValue("#ifqulify",txtqualified.Text.Trim());
cmd.Parameters.AddWithValue("#conduct",txtconduct.Text.Trim());
cmd.Parameters.AddWithValue("#applieddate",dtpdoapp);
cmd.Parameters.AddWithValue("#ifrecieved",tcrecieved);
cmd.Parameters.AddWithValue("#receiveddate",dtpdor);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted Successfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error Message");
}
finally
{
conn.Close();
}
}
}
}
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 not a programming Problem, but a networking/connection string one.
Connection Strings are their own area of experetise, way outside the normal programmers knowledge. Luckily there is a page for it: https://www.connectionstrings.com/sql-server/
It turns out even when attaching, you have to supply a database name: "Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection."
And as others mentioned, you got the wrong kind of slashes too.
Pretty off topic, but exception handling is a pet peeve of mine. And yours has some of the serioues mistakes. Like catching exception and only exposing the message. Those are 2 Cardinal sins. Thee are two article on the thematic I link often:
https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

How to make a connection with MySql database from my CPanel with Visual Studio 2017

I am trying to make a connection to MySQL database from my cpanel with Visual studio, but I keep getting an 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)
I have installed both MySql for Visual studio and Connector/net. I have tried with both Server Explorer and through the code using the connection string. I have added my ip to the access host list on Remote MySql in CPanel. But nothing worked.
namespace Program
{
public partial class WebForm1 : System.Web.UI.Page
{
string connectionString = #"SERVER=mydomain.net;DATABASE=mydatabasename;UID=myuser;PASSWORD=mypass";
protected void Page_Load(object sender, EventArgs e)
{
FillDropDown(DropDownList1);
}
public void FillDropDown(DropDownList dropDown)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
SqlCommand sqlCmd = new SqlCommand("Select * from MyTable", sqlCon);
sqlCon.Open();
dropDown.DataSource = sqlCmd.ExecuteReader();
dropDown.DataBind();
dropDown.DataTextField = "Name";
dropDown.DataValueField = "Id";
}
}
catch(Exception ex)
{
lblError.Text = ex.Message;
}
}
}
}
The SqlConnection-object may only be used for connections to MS-SqlServers. You have to use MySqlConnection to connect to MySql-server. This also applies to the SqlCommand.
Furthermore the used connection-string is not valid for MySql ('Password' should be 'Pwd') Compare your string to https://www.connectionstrings.com/mysql/

Linq Windows Form C# System.Data.SqlClient.SqlException

I'm a student doing an assignment which is an appointment system, I'm using Management Studio for the database, I detached it and linked Visual Studio with the .mdf file.
I can't find where the error is and never solved this type of error before.
Code:
DataClasses1DataContext db = new DataClasses1DataContext();
public frmAccountCreation()
{
InitializeComponent();
}
private void btnCreateAccount_Click(object sender, EventArgs e)
{
string email = txtEmail.ToString();
string fullname = txtFullname.ToString();
string username = txtUsername.ToString();
string password = txtPassword.ToString();
int userlevel;
string contactnumber =txtContactNumber.ToString();
if(ckbAdmin.Checked)
{
userlevel = 1;
}
else
{
userlevel = 0;
}
tblUserAccount account = new tblUserAccount
{
Username = username,
Passcode = password,
UserPrivelage = userlevel
};
tblVet vet = new tblVet
{
Email = email,
FullName = fullname,
ContactNumber = contactnumber
};
db.tblUserAccounts.InsertOnSubmit(account);
db.tblVets.InsertOnSubmit(vet);
db.SubmitChanges();//Error Is here
}
}
Error:
An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in System.Data.Linq.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
Looking at this line:
DataClasses1DataContext db = new DataClasses1DataContext("C:\\Users\\Luke\\Desktop\\OOP Assignment\\OOP_Database.mdf");
You are trying to open the MDF file directly. You cannot do that. You need a running SQL server instance (which can be on your development machine, like SQL Express), and you will need a connection string to connect to that server.
I solved the problem by uninstalling everything related to visual studio community 2015 and my antivirus avg after i reinstalled everything worked perfectly fine
It seems your SQL Server Service is not running.
In Windows, search for "Services" and there should be a Windows application with the same name.
In the application keep scrolling untill you find "SQL Server (MSSQLSERVER)" and make sure it's running.

cannot Connect to online Mysql Database (c#)

My MYsql database is on "https://www.lima-city.de/" when i try to connect to it :
private string mysqlConnectionString = "Server= 10.246.16.74:3306; Port=3306;Database=test;Uid=myname;Pwd=pwd;";
MySqlConnection connection = new MySqlConnection(mysqlConnectionString);
connection.Open();
i get -> Unable to connect to any of the specified MySQL hosts.
but why?
Try this as your connection string
private string mysqlConnectionString = "Server=10.246.16.74;Port=3306;Database=test;
User=myname;Password=pwd;Option=3";
I have removed the port number from the server address.
Use following code
MysqlConn.ConnectionString = "Server=localhost;Database=My_Mysql_Database;Uid=root;Pwd=root;"

How can i connect remote sql server by Entity Framework?

I have no enough experience on database systems. I have to connect to remote sql server and process some queries on it. How can i connect remote server by Entity Framework ?
1) Check if remote sql server is allowed remote connetions
2) In Visual Studio use Entity Framework wizard (add new connection)
Same as you would with any other database connection tool: Make sure the server and all firewalls/proxy servers between you and the server accepts the connection, and then supply EF with a correct connection string.
However, if you're only going to process some sql queries, I would suggest using SQL Server Management Studio instead. Entity Framework is an ORM, not a database management tool.
Here how I connect programmatically (no xml/appconfig file) to a remote server:
First check that your remote server is correctly parametrised. In particular one port has to be open. See this MSDN post for details.
Create the connection string as follow (see SqlConnectionStringBuilder):
public static string GetRemoteConnectionString()
{
SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
{
DataSource = $"{IP},{PORT}", // ex : 37.59.110.55,1433
InitialCatalog = "MyDatabaseName", //Database
IntegratedSecurity = false,
MultipleActiveResultSets = true,
ApplicationName = "EntityFramework",
UserID = "MyUserId",
Password = "MyPassword"
};
return sqlString.ToString();
}
Then connect via the DbContext :
public class MDBContext : DbContext
{
public MDBContext () : base(GetRemoteConnectionString())
{
}
......
}
Extra :
You can also easily check connection (before to create the DbContext) as follow :
try
{
using (SqlConnection con = new SqlConnection(GetRemoteConnectionString()))
{
con.Open();
}
success = true;
}
catch (Exception ex)
{
success = false;
...
}

Categories