Error connecting to Local Database con.open() - c#

I have the sample database Northwind installed and attached to a C# project
I'm trying to connect to the database and retrieve column names of a table in the database, but I'm getting an error while trying to open the connection, here is the code I'm using to do so:
public void connectToDB()
{
Dictionary<object, object> colns = new Dictionary<object, object>();
List<string> colnNames = new List<string>();
con = new SqlConnection("Data Source = .NorthwindDB.mdf; Integrated Security=True");
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM Products";
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables["Products"];
foreach(DataRow dr in dt.Rows)
{
foreach(DataColumn dc in dr.Table.Columns)
{
colnNames.Add(dc.ColumnName.ToString());
}
}
foreach(string key in colnNames)
{
Console.WriteLine(key.ToString());
}
Console.ReadKey();
}
I'm getting the following error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred 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 Provider, error: 40 - Could not open a connection to SQL Server)
Another thing that may help, I'm noticing that whenever I click start button to execute the code, the green plug that appears over the data connection NorthwindDB.mdf turns into red x.

Your connection string is incorrect it should be something like this:
con = new SqlConnection("Data Source=(local);" +
"Initial Catalog=NorthwindDB.mdf;Integrated Security=True");
// Or Data Source=.\\sqlexpress;
You can read more about connection strings here: Database Connectionstrings.

Related

error 26- error locating server/instance specified

I designed a C# desktop app in visual studio 2019 and for database used sql server express 2019 edition. i am trying to run this app on another pc. i have installed sql server express 2019 in the other pc also MS server management studio 2019 installed and restored the database. everything works fine like login,saving updating,deleting but when i try to fetch data to datagridview it shows "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 instance name is correct and sql server is configured to allow remote connections.(provider: sql network interfaces, error: 26 - error locating server/instance specified)."
all the ports are enabled and firewall rule is also enabled in the client pc.
i am using the below connection string for the connection.
class Connection
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=icon;Integrated Security=True");
public SqlConnection active()
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
return con;
}
}
Please help anyone as i am not able to get what is the problem going on.
Belowcode is working
private void loginBtn_Click(object sender, EventArgs e)
{
Connection con = new Connection();
SqlCommand cmd = new SqlCommand("select * from [user] where
Username='" + usernameTxt.Text + "'and password='" + passwordTxt.Text
+ "'", con.active());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login Successful", "Sucsess",
MessageBoxButtons.OK, MessageBoxIcon.Information);
new dashboard().Show();
this.Hide();
}
but this is not working.it shows the error when i try to fetch the data.
public partial class AllSudent : Form
{
public AllSudent()
{
InitializeComponent();
}
Connection con = new Connection();
public int studentID;
private void AllSudent_Load(object sender, EventArgs e)
{
GetStudentsRecord();
}
public void GetStudentsRecord()
{
SqlCommand cmd = new SqlCommand("Select * From [student]",
con.active());
DataTable dt = new DataTable();
SqlDataReader sdr = cmd.ExecuteReader();
dt.Load(sdr);
sdataGridView.DataSource = dt;
}
Throw your Connection class away, and pass the connection string to the DataAdapter. Don't bother opening or closing the connection; DataAdapter knows how to open a connection if it's closed
Put the connectionstring into the Settings
Use parameters
private void loginBtn_Click(object sender, EventArgs e)
{
using(var sda = new SqlDataAdapter("select * from [user] where Username=#user and password=#pass", Properties.Settings.Default.ConStr)
{
//USE PARAMETERS
sda.SelectCommand.Parameters.Add("#user", SqlDbType.VarChar, usernameTxt.Text.Length).Value = usernameTxt.Text;
sda.SelectCommand.Parameters.Add("#pass", SqlDbType.VarChar, passwordTxt.Text.Length).Value = passwordTxt.Text.GetHashcode(); //DO NOT store your passwords in plain text!!
var dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login Successful", "Sucsess",
MessageBoxButtons.OK, MessageBoxIcon.Information);
new dashboard().Show();
this.Hide();
}
}
}
Use parameters
Just in case you missed it: USE PARAMETERS. Never again, in your life ever, should you concatenate a value into an SQL string. Ever. There is no reason to do it, and doing it will result in the software you create being hacked / you getting fired / both
Also, don't store passwords in plain text, ever. Salt and hash them. I've used string.GetHashcode() for demo purposes, which is not good but better than plaintext
Do the same thing to the not working code:
public void GetStudentsRecord()
{
using(var sda = new SqlDataAdapter("Select * From [student]", Properties.Settings.Default.ConStr)){
var dt = new DataTable();
sda.Fill(dt);
sdataGridView.DataSource = dt;
}
}
this issue also confusing me a few days after the IT guy do some security settings to the SQL Server. i have an EntityFramework for the Web application and a desktop application. after i did some setting on the SQL Server, the Web application comeback to work, but the desktop still with issue. but i used the some connection string for the both application, it make no sense one is work but the other doesn't. then i searched a lot until i found some one said need add a port number 1433 after the $ServerName$DatabaseInstanceName,1433 at here http://www.windows-tech.info/15/9f6dedc097727100.php . after i added it. the exception became: System.Data.SqlClient.SqlException: Login failed for user 'domain\name-PC$'. then i found this link System.Data.SqlClient.SqlException: Login failed for user: System.Data.SqlClient.SqlException: Login failed for user it said need add Trusted_Connection=False;. the whole connection string should be like: data source=XXXXX\SQLSERVER,1433;initial catalog=XXXDB;user id=UserID;password=PWD;Trusted_Connection=False;MultipleActiveResultSets=True;
hope this answer will help the ones out off Generic exception: "Error: 26-Error Locating Server/Instance Specified)

connection string from c# to msql

I am new to msql and i am working on MySQL Workbench 8.0 CE
I am trying to bind data from database to datagridview as show below but i am getting error below
but I am able to connecto my database using MySQL Workbench 8.0 CE so the connection to up so what I can do ?
public void GetPersonData()
{
string connstr = "Server=localhost;Database=newsequesterdb;Uid=reser;Pwd=00";
string query = "SELECT * FROM NEWSEQUESTERDB.PERSON;";
using (SqlConnection conn = new SqlConnection(connstr))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dgv_data.DataSource = ds.Tables[0];
}
}
}
error message
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)
SqlConnection is specific to MS SQL Server. Use MySqlConnection (and associated command and data adapter classes) instead.
Note that MySqlConnection is not built in to the .NET Framework - you'll need to install it separately.
The thing is that you cannot use an SqlConnection instance nor SqlAdapter, those are intended to be SQL Server connection classes. And this you can see by the exception itself.
...(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
So, what's next? You should really look up to this question and may solve a few doubts.
From that question we can see that is using other references to connect to MySQL. Specifically Oracle's nugget package: MySQL.Data
using MySql.Data;
using MySql.Data.MySqlClient;
From that question example:
var dbCon = DBConnection.Instance();
dbCon.DatabaseName = "YourDatabase";
if (dbCon.IsConnect())
{
//suppose col0 and col1 are defined as VARCHAR in the DB
string query = "SELECT col0,col1 FROM YourTable";
var cmd = new MySqlCommand(query, dbCon.Connection);
var reader = cmd.ExecuteReader();
while(reader.Read())
{
string someStringFromColumnZero = reader.GetString(0);
string someStringFromColumnOne = reader.GetString(1);
Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
}
dbCon.Close();
}

Database Connectivity with oracle database using c#

While trying to connect the oracle database I am getting 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"}
Problem may be silly one but this is my first time with database so need help:
My code is:
static void Main(string[] args)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=ORCL_BOA; database=BOANEWDOC;User Id=BOANEWDOC;Password=BOANEWDOC;Trusted_Connection=true";
conn.Open();
//code
}
you may need to reference Oracle.ManagedDataAccess.dll on ODTwithODAC121012.zip you can download from oracle site.
do not use System.Data.OracleClient as it is obsolete.
var connection = new OracleConnection(YourConnectionString);
try
{
connection.Open();
//AMK: Do some stuff with the db
}
catch (Exception exception)
{
//AMK: do some other stuff in case of error
}
finally
{
if(connection !=null && connection.State==ConnectionState.Open)
connection.Close();
}

Connecting to SQL Server database using C#

I am using VS 2012 Express for web, I have created a website project and I am trying to connect integrated SQL Server with on the .aspx page of the website but I am 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I have gone through various websites and tried to connect via web.config as well as c# but its does not seem to be possible.
What I have tried so far
web.config file:
<connectionStrings>
<add name="CnStr"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
C# code:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CnStr"].ConnectionString;
SqlConnection conn = new SqlConnection("connectionString");
SqlCommand cmd = new SqlCommand("select * from user_login ",conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
conn.Close();
The other way I have tried is:
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\v11.0;Database=Visual Studio 2012\\App_Data\\Database.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select * from user_login ",conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
conn.Close();
I have made database using following steps
right click on project
selecting SQL Server database to App_Data folder with name Database.mdf
Also If I try using add connections from data connections in database explorer, it's not accessing the database.mdf file and load only the templates e.g master, temp etc and not the folder in my App_Data folder and giving same error.
I have gone through many questions in stack overflow and tried using them as well
This is not code error, but a SQL configuration error. Follow steps in this excellent article for troubleshooting.
http://blog.sqlauthority.com/2009/05/21/sql-server-fix-error-provider-named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server-microsoft-sql-server-error/
try this code instead!!!
string str = "Data Source=(LocalDB)\\v11.0;Database=Visual Studio 2012\\App_Data\\Database.mdf;Integrated Security=True";
using(SqlConnection conn = new SqlConnection(str));
{
conn.Open();
using(SqlCommand cmd = new SqlCommand("select * from user_login ",conn);
{
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
}
conn.Close();
}

asp.net sqlconnection won't open

I'm using the following to retrieve data from a database but the sqlconnection won't open. It throws an error at scon.Open(). I'm sure it's elementary but I can't work it out.
public partial class populate : System.Web.UI.Page
{
SqlConnection scon = new SqlConnection("Data Source = localhost; Integrated Security = true; Initial Catalog = populate");
protected void Page_Load(object sender, EventArgs e) {
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
}
I'm using this link
https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx
as one of my references. I'm also using SQLEXPRESS 2008 R2 if these information are of any help. Here's part of the error message:
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)
Would appreciate if I could get past this and move on. Thanks in advance.
If you have user instances configured on SQL Server (which is the default), you need to change your connection string to this:
Data Source=.\SQLExpress;Integrated Security=true;
initial catalog=database_Name
select * from table_name
Is your database name and table name same?

Categories