Retrieve data from LocalDB in ASP.NET webforms - c#

I am using a simple webforms application to retrieve data to bind in a GridView control from LocalDb\v11.0 locally. I have created MyDb.sdf and a table named info inside App_Data folder. 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: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
Web.config:
<connectionStrings>
<add name="dbcs"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\MyDb.sdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
HTML
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
</form>
Back-end Code
protected void Page_Load(object sender, EventArgs e)
{
string con = WebConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (SqlConnection scon = new SqlConnection(con))
{
SqlCommand cmd = new SqlCommand("select * from info", scon);
scon.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
scon.Close();
}
}

Your connection string and code (using SqlConnection) is for a full-blown version of SQL Server (Express, Web, Standard, Enterprise), while the .sdf database file is for SQL Server Compact Edition.
Those two technologies are NOT compatible. You cannot attach a .sdf database file to your (LocalDB)\v11.0 LocalDB instance - it needs to be a .mdf file.
Either use a real SQL Server (create a database in your SQL Server instance) and your current code - or then you need to switch to using SqlCeConnection and SqlCeCommand in your code

Related

Tested Sql connection via Server Explorer but will not Connect at runtime

The issue at hand: Cannot connect to my sql server database with a connection string that works with the server explorers connection tools but does not work with my WPF application.
I am connecting to a sql server "US06S-SQLSRV" at port 49278, database name is "Solutions". I have created an application that needs to connect to this server but there is concern that the server may move in the future so I am trying to dynamically change this string for future use.
This is the connection string that is generated from the connection tool:
Data Source=US06S-SQLSRV,49278;Initial Catalog=Solutions;Integrated Security=True
I have copied this string into my App.Config file and I try to test the connection after the user logs in as follows:
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<clear/>
<add name ="DatabaseConnStringSO"
connectionString ="Data Source=US06S-SQLSRV,49278;Initial Catalog=Solutions;Integrated Security=True"/>
</connectionStrings>
</configuration>
DatabaseHelper.CS
public static string sql;
public static SqlConnection conn = new SqlConnection();
public static SqlCommand cmd = new SqlCommand(sql, conn);
public static SqlDataReader reader;
public static SqlDataAdapter sqlDataAdapter;
public static string DataSource = #"US06S-SQLSRV";
public static string GetConnectionStrings(string Name)
{
string strConnx = ConfigurationManager.ConnectionStrings[Name].ToString();
return strConnx;
}
public static void OpenConnection()
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.ConnectionString = GetConnectionStrings("DatabaseConnStringSO");
conn.Open();
MessageBox.Show("Solutions Database connection successful press 'OK' to proceed.", "Successful connection", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
//+Environment.NewLine + "Description: " + Exception.Message.ToString()
catch (Exception ex)
{
MessageBox.Show("Solutions Database ( " + DataSource + " connection unsuccessful, please seak a MFG personnel to assist in addressing this issue via the configuration window."
+ Environment.NewLine + "Description: " + ex.Message.ToString(), "Unsucessful database connnection, error: 100",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
This is the error that I'm 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: TCP Provider, error: 0 - A non-recoverable error occurred during a database lookup.)'
Any help at all will be appreciated.
Things I have tried:
Hard coding the string into the commands.
Allowing the Ports via firewall rules
Checking if the server can be reached via Sql Server management studio (it does with both IP address and Server name)
Using IP address in the connection string.
Create a table adapter with this database (generates a different error when I try to preview the data base in that manner but the queries work from the table designer view).
Yes the table adapter is using the same connection string.
TCP/IP is enabled on the server
Ensured that remote connections are enabled on the server
At the end of the day I want to connect to this database with a dynamic string.
Edited to display further actions:
Powershell result
Test-NetConnection -Port 49278-ComputerName US08S-SQLSRV
ComputerName : US06S-SQLSRV
RemoteAddress : 173.18.167.19
RemotePort : 49278
InterfaceAlias : Ethernet 2
SourceAddress : 173.18.168.193
TcpTestSucceeded : True
Thus far it seems that there is a bug with the System.Data.SqlClient library for visual studio 2019. I was able to do this task with the same exact code with Visual Studio 2017.
Integrated security basically means, use Windows security to log on to a sql server. You should create a SQL user specifically for accessing it via your program, and create a connection string based on those values.
See here for details of how to make a connection string for your SQL server.

How to automatically attach SQL Server database in C#?

I am new to C# and SQL Server 2014 Express and I am using Windows forms.
I am building the small application which read/write from/to SQL Server database.
I am trying to automatically attach SQL Server database, then read data from a table named Test_Table and then fill a Datagridview.
The code I used:
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand MyCommand= new SqlCommand();
DataTable DataTable = new DataTable();
SqlDataAdapter Sql_Data_Adapter= new SqlDataAdapter();
private void button1_Click(object sender, EventArgs e)
{
MyConnection.Open();
MyCommand.CommandText = "SELECT * FROM Test_Table ";
MyCommand.Connection = MyConnection;
Sql_Data_Adapter.SelectCommand = MyCommand;
Sql_Data_Adapter.Fill(DataTable);
dataGridView1.DataSource = DataTable;
MyCommand.Parameters.Clear();
Sql_Data_Adapter.Dispose();
MyConnection.Close();
}
App.config:
<connectionStrings>
<add name="MyConnectionString"
connectionString="Data Source=localhost; AttachDbFilename=D:\\DB\\MyDB.mdf;Integrated Security=True"/>
</connectionStrings>
When I click on button1 it throws an error:
An attempt to attach an auto-named database for file D:\DB\MyDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I have no other databases attached and the database path is correct.
I had a look here, here and here but non of them helped.
Any idea how can I automatically attach a SQL Server database file? Thank you
What is the version of SQL Server are you using? This will explain a lot about your error message.
Your Connection String:
"Data Source=localhost; AttachDbFilename=D:\DB\MyDB.mdf;Integrated
Security=True"
You can only use AttachDbFilename with SQL Express. In your connection string, the Data Source is set to localhost. That sounds like you have a full version SQL Server installed.
If you have a full version of SQL Server installed, you can only attach a database via Management Studio.
If you are using SQL Express, change your data source:
Data Source=.\SQLEXPRESS

Getting my sql database to work with my hit counter code in asp.net

I been trying to follow this tutorial to create a hit counter for my website using asp.net/c# and html/css. I'm running this off localhost. I'm having trouble configuring or getting the sql database connectionstring to work. Here is a link to the tutorial I'm using Hit counter in asp.net. So I follow the tutorial and run the code, and i get this error
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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I'm pretty sure it has to do with how i wrote the ConnectionString in the web Config file. Maybe I'm pointing the data source to the wrong place? Maybe it's because i'm not using Initial Catalog in the connection string?
connectionstring in my web config file:
<connectionStrings>
<add name="ConnectionString" connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;
Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
calling my connectionstring from .cs file
/objects we will need to work with the db
SqlConnection conn;
SqlCommand cmd;
//IF PAGE IS NOT A POSTBACK, ADD A HIT
if (!Page.IsPostBack)
{
//connect to the db
conn = new
SqlConnection(WebConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString);
//the sql command to increment hits by 1
cmd = new SqlCommand("UPDATE Hits SET Hits = Hits+1 WHERE
Name=#Name", conn);
cmd.CommandType = CommandType.Text;
//update where Name is 'About' which corresponds to this page
cmd.Parameters.AddWithValue("#Name", "About");
using (conn)
{
//open the connection
conn.Open();
//send the query
cmd.ExecuteNonQuery();
}
I'm still a newbie when it comes to all this database stuff, any help be appreciated.
update fixed: I followed the instructions by user1551066 and found my data source for the database.mdf and then i plugged it in my connectionstring in web config and it WORKED.
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=
(LocalDB)\v11.0;AttachDbFilename=C:\Users\bobdole\Desktop
\VideoWebsite\VideoWebsite\VideoWebsite\App_Data\Database.mdf;
Integrated Security=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>
Try to connect to your .mdf database in visual studio. 1)Go to server explorer tab. 2)You should see your database .mdf file (possibly as DefaultConnection) 3) Click on it. In the Properties window you wil see the section Connection. Unfold it and you will see the ConnectionString property. Copy and paste it in your web.config ConnectionString setting.
Your error is due to SQL connection failure.Please check the connection string which you have passed was correct.For connection string reference please refer here.
Sql Server connection string
connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
If you have a named instance of SQL Server, you'll need to add that as well.
"Server=localhost\sqlexpress"
and for connecting SQL Server
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Please refer [here][2]

ADO.NET : Error occurred while establishing a connection to SQL Server

i am trying to bind data to Gridview and getting this 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)
this is my simple code
string cs = "data source =.; initial catalog= MyDB; integrated security= SSPI";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("select * from tbl_Dept", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
in SQl management studio i have rechecked db name and its same as mentioned in code
I found some related questions but those did not work for me so posting mine one , Please help me with it,
You can define SqlConnection string in your web.config(in web applications) or app.config(in windows form application).
Simply define like this -
<configuration>
<connectionStrings>
<add name="Connection" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DBName;Trusted_connection=yes;User ID=''; Password=''"/
</connectionStrings>
</configuration>
then access this code in you .cs form using
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString.ToString());
and after this you can use SqlConnection object con in you whole form.
When you install SQL Server Express the setup propose to create a named instance, and by default, this named instance, is called SQLEXPRESS.
When you want to connect to this named instance it is required to specify the name.
So, in your case your connection string should be changed to
"Data Source =.\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=SSPI";

Connecting to SQL Server using windows authentication

When I was trying to connect to SQL Server using the following code:
SqlConnection con = new SqlConnection("Server=localhost,Authentication=Windows Authentication, Database=employeedetails");
con.Open();
SqlCommand cmd;
string s = "delete employee where empid=103";
I 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)
A connection string for SQL Server should look more like: "Server= localhost; Database= employeedetails; Integrated Security=True;"
If you have a named instance of SQL Server, you'll need to add that as well, e.g., "Server=localhost\sqlexpress"
Your connection string is wrong
<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Check out www.connectionstrings.com for a ton of samples of proper connection strings.
In your case, use this:
Server=localhost;Database=employeedetails;Integrated Security=SSPI
Update: obviously, the service account used to run ASP.NET web apps doesn't have access to SQL Server, and judging from that error message, you're probably using "anonymous authentication" on your web site.
So you either need to add this account IIS APPPOOL\ASP.NET V4.0 as a SQL Server login and give that login access to your database, or you need to switch to using "Windows authentication" on your ASP.NET web site so that the calling Windows account will be passed through to SQL Server and used as a login on SQL Server.
You have to add a connectionString within your Web.config file as
<connectionStrings>
<add name="ASPNETConnectionString" connectionString="Data Source=SONU\SA;Initial Catalog=ASPNET;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Then Write your SQL connection string as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class WebPages_database : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ASPNETConnectionString"].ToString());
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdmnNumber_Click(object sender, EventArgs e)
{
string qry = "select * from Table";
da = new SqlDataAdapter(qry, con);
ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
For more Information please follow this link
How To:Connect to SQl with windows Authentication
SQL Server with windows authentication
I was facing the same issue and the reason was single backslah.
I used double backslash in my "Data source" and it worked
connetionString = "Data Source=localhost\\SQLEXPRESS;Database=databasename;Integrated Security=SSPI";
This worked for me:
in web.config file;
<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>
Just replace the first line with the below;
SqlConnection con = new SqlConnection("Server=localhost;Database=employeedetails;Trusted_Connection=True");
Regards.
Use this code:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=HOSTNAME\SQLEXPRESS; Initial Catalog=DataBase; Integrated Security=True";
conn.Open();
MessageBox.Show("Connection Open !");
conn.Close();
use this code
Data Source=.;Initial Catalog=master;Integrated Security=True

Categories

Resources