I am developing a Winforms application in which I am using SQL Server 2008 Express Edition as backend. But I am getting error:
Additional information: An attempt to attach an auto-named database for file D:\Hardik\Hardik\dotnet\TestApplication\TestApplication\bin\Debug\MyDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
My code is:
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select * From MyTable";
cmd.CommandType = CommandType.Text;
da = new SqlDataAdapter();
da.SelectCommand = cmd;
dt = new DataTable();
ds = new DataSet();
da.Fill(ds, "Login");
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
}
and my app.config file is:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyConnection"
connectionString="Server=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True; User Instance=True"
providerName="System.Data.Client"/>
</connectionStrings>
</configuration>
Where I am wrong?
use double slash instend of single slash.
A UNC path uses double slashes or backslashes to precede the name of the computer.
<connectionStrings>
<add name="MyConnection" connectionString="Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True; User Instance=True" providerName="System.Data.Client"/>
</connectionStrings>
for instance failure
As you got the error "instance failure", that might be the error with your SQL Server instance..
Make sure your SQL Server instance(MSSQLSERVER) is running, where you can check in: Services list. TO get into services list: open run dialog box and type: "services.msc" (without quotes) and hit Enter. That takes you to services management console, where you can check whether your instance in running or not..
If the problem still persists, then try using: Data Source=.\SQLEXPRESS instead.. :)
Related
I am trying to have a personalized database connection string for the machines i install the C# application into. I have created a database using Visual Studio but that only points the location of the database to my personal directory and that is not something general.
Now when i try to publish the application and try to install it in some other computer, the database gives me an error that it wasnt found, which makes sense because the connection string is pointing to my personal computers directory.
Here is part of my code:
private void button13_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;");
sda = new SqlDataAdapter(#"SELECT [Panel Progress].*
FROM [Panel Progress]", con);
fill_grid();
}
catch (Exception error)
{
label6.Text = error.Message;
}
}
Can anyone please guide me towards the right path to solve this issue and to generate a personalized connection string for every computer the database gets installed to?
In your app.config or web.config file (Whichever is relevant to you) add the following connection string under configuration tag.
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;" />
</connectionStrings>
If you already have a connection strings section then add only the
<add name="DbConnection" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;" />
Then in your C# code instead of hard coding the connection string you can use the config value.
string connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
private void button13_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(connectionString);
sda = new SqlDataAdapter(#"SELECT [Panel Progress].*
FROM [Panel Progress]", con);
fill_grid();
}
catch (Exception error)
{
label6.Text = error.Message;
}
}
Build it. Then when you deploy the application in to another machine all you have to do is change your connection string in the app.config or web.config(whichever is relevant for you) to the new file location without changing hard coded values and rebuilding the application again.
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();
}
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.
protected void Page_Load(object sender, EventArgs e) {
SqlConnection scon = new SqlConnection("Data Source = .\\SQLEXPRESS; Database = populate.mdf; Integrated Security = true; Initial Catalog = populate");
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 SQL Server 2008 R2 Express if these information are of any help.
Here's part of the error message:
SqlException (0x80131904): Cannot open database "populate" requested
by the login. The login failed.
Any help would be greatly appreciated.
Quoted from https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#sse, if you want to use .mdf file as a database, you should use the following connection string containing AttacheDbFileName.
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />
I solved it. All the connection string and other code was correct. The database just needed connecting to the Management Studio with some extra attention.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have a windows forms application which begins with the Login form
The Login form has been fine for past few day while i was working on rest of the application
I get an error now that
I have two database one DB.mdf and one MYD.sdf
NullReferenceException was unhandled
Object reference not set to an instance of an object.
for this particular lines of code --- >
private void button1_Click(object sender, EventArgs e)
{
string path=#"C:\Users\Srinath\Documents\Visual Studio 2010\Projects\TESTFEE\TESTFEE\DB.mdf";
SqlConnection con =new SqlConnection(#"Data Source=.\SQLEXPRESS; AttachDbFilename='"+path+"';User Instance=True");
string constring=ConfigurationManager.ConnectionStrings["ConnectionStringFMS"].ConnectionString;
//SqlConnection con=new SqlConnection(constring);
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from LOGIN where USERNAME='" + textUser.Text + "' and PASSWORD='" + textPass.Text + "'", con);
DataTable dt = new DataTable();
try
{
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
e1.Show();
}
else
{
HoldButton();
MessageBox.Show("Please Enter Your Right Credentials");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}//![The error i get ][1 -]
I tried using the Configuration File for connection string
before i directly used the SqlConnection for connection
I am using Sql server 2008 r2 with the Management studio
I first recieved the Failed to connect to the default database inititally
Doubts - >
is it the Problem because of using two different types of db in one application
I tried reinstalling sql server 2008 but no use
please help
Put your connection string in webconfig, If you have the *.mdf placed in App_Data folder, using this format works
<connectionStrings>
<add name="ConnectionName"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I developed an application. It loads sql database on my pc with this connection string:
Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Database\Books.mdf;Integrated Security=True;User Instance=True
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Database\Books.mdf;Integrated Security=True;User Instance=True");
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("SELECT * FROM Lessons", con);
da.Fill(ds);
grdPersonnel1.DataContext = ds.Tables[0];
con.Open();
}
but, my Database data doesn't load in another pc!
Do you have SQL server instance Running on that Computer?
Try to Run your Application/Solution on the other P.C on Debug Mode you will see what exactly is the error...make sure you have try and catch in each of your methods/ events.
check this SO post :
Is it possible to run a mdf database without SQL Server program? (c#)
Connecting to sql server database mdf file without installing sql server on client machine?
Regards