Error: Could not open a connection to SQL Server - c#

I'm new to Asp.Net and now I'm facing this problem. I've tried many way as possible I get from google and here. But I still cannot find a solution for this. I've tried to change the Data Source to 127.0.0.1, but I still get the same error. It actually works to connect to database when I'm using MySql.Data.MySqlClient. But fail when I'm using System.Data.SqlClient
Can you all help me? Thank you very much.
Code Behind:
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["WebAppConnStringSql"].ConnectionString;
using (SqlConnection cons = new SqlConnection(constr))
{
using (SqlCommand cmds = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmds.CommandType = CommandType.Text;
cmds.Connection = cons;
sda.SelectCommand = cmds;
**sda.Fill(dt);** //Error occurs here
}
}
return dt;
}
Web.config
<connectionStrings>
<add name="WebAppConnStringSql"
connectionString="Data Source=localhost;Initial Catalog=vbsite;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
The 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)*
SqlException was unhandled by user code

You should open connection SqlConnection.Open():
using (SqlConnection cons = new SqlConnection(constr))
{
cons.Open();
using (SqlCommand cmds = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmds.CommandType = CommandType.Text;
cmds.Connection = cons;
sda.SelectCommand = cmds;
**sda.Fill(dt);** //Error occurs here
}
}
return dt;
}

Related

C# local database error

i am having an error while connecting the local service database of C# in VS 2017. The app is just for testing and the error i am having the con.open() line. I have placed a data gridview in the app with dataset and it is showing all the values inside the db in gridview but when i use my button to execute the INSERT Query it shows up an error. This is the error below
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: SQL Network Interfaces, error: 50
- Local Database Runtime error occurred. Specified LocalDB instance name is invalid. )'
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C: \\Users\\Shahrukh Khan\\source\\repos\\checkingsetup\\testingdb\\Database123.mdf;Integrated Security=True");
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table1 values('"+textBox1.Text+"')";
cmd.ExecuteNonQuery();
cmd.CommandText = "select * from table1";
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}

Creating social website in asp.net

I'm creating a social Networking Website for that I used "Social Networking Website in ASP.NET - Open Source" from
http://www.c-sharpcorner.com/UploadFile/rahul4_saxena/social-networking-website-in-Asp-Net-open-source-project/
When I tried to run the project on my Visual Studio 2012 edition it is showing error like below,
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)
Source Error:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Summary description for DataBaseClass
/// </summary>
public class DataBaseClass
{
SqlDataAdapter da;
SqlConnection con;
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public DataBaseClass()
{
//
// TODO: Add constructor logic here
//
}
public void ConnectDataBaseToInsert(string Query)
{
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public DataSet ConnectDataBaseReturnDS(string Query)
{
ds = new DataSet();
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return ds;
}
public DataTable ConnectDataBaseReturnDT(string Query)
{
dt = new DataTable();
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return dt;
}
}
Visual studio pointing the error here da.Fill(dt).
I have spent 2 days to debug this error but still I couldn't. Please help me.
It is very simple. Your code is not able to connect to the database. Open Server Explorer in Visual Studio and connect to your database to confirm you are able to connect. And then get your connection string right.
And you do have a database, right?

connecting to database in c# via IP\DEV

Im Trying to connect to a database on a SQL server Located on 192.168.100.42\DEV but i keep getting a network related error see below by code and then the error , If any one can help it would be appreciated
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = "Data Source=192.168.100.42\Dev;Initial Catalog=UNIS;User ID=sa;Password=Password1!";
using (SqlCommand scmd = new SqlCommand("dbo.searchName"))
{
scmd.CommandType = CommandType.StoredProcedure;
scmd.Parameters.Add(new SqlParameter("#name", cbUserName.Text));
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter dataAdapter = new SqlDataAdapter(scmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
conn.Open();
scmd.Connection = conn;
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView2.ReadOnly = true;
dataGridView2.DataSource = ds.Tables[0];
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)

Cant Export to XML

I have a sql compact database connected to my website called Sort.sdf, with a table called "sort". I need to export all the records from the table to an XML file, but I keep getting the following error and cannot find a solution:
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 used the same connection to successfully insert data into the database, so I don't think there is a problem there.
SqlCeConnection conn = new SqlCeConnection("Data Source=|DataDirectory|Sort.sdf");
conn.Open();
DataSet ds = new DataSet();
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("Select * from Sort", conn.ConnectionString);
da.Fill(ds); //error on this line
ds.WriteXml(#"c:\temp\output.xml", XmlWriteMode.WriteSchema);
SqlCeConnection cnn = new SqlCeConnection("Data Source=|DataDirectory|Sort.sdf");
cnn.Open();
SqlCommand cmd = new SqlCommand("select * from sort", cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds=new DataSet();
da.Fill(ds);
StreamWriter xmldoc=new StreamWriter(Server.MapPath("~/Testdo.xml"), false);
ds.WriteXml(xmldoc);
xmldoc.Close();

Not able to connect to database with connection string in app.config

DataSet ds = new DataSet("Transactions");
using (SqlConnection conn = new SqlConnection("myConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("[dbo].[GetFullTransactionList]", conn);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
return ds;
Relevant content of app.config:
<configuration>
<connectionStrings>
<add name="myConnectionString"
connectionString="Data Source=LAPTOP-LT;Initial Catalog=myDb;User ID=sa;Password=abc"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
I'm getting this exception:
Format of the initialization string does not conform to specification
starting at index 0. Description: An unhandled exception occurred
during the execution of the current web request. Please review the
stack trace for more information about the error and where it
originated in the code.
Exception Details: System.ArgumentException: Format of the
initialization string does not conform to specification starting at
index 0.
Source Error:
Line 44: DataSet ds = new DataSet("Transactions");
Line 45: using (SqlConnection conn = new SqlConnection("myConnectionString"))
The correct way to refer a connection string in the app.config is:
string cnnString = ConfigurationManager.ConnectionStrings["yourCnnString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(cnnString))
{
}
do not forget the final property ConnectionString
To use connection string from config file, you need to access it ConfigurationManager.
So it will be:
using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"]))
{
...
}
Refer to documentation to get more info
SqlConnection expect a real connection string not the key from app.config. Try to read it with
ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString

Categories