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.
Related
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.
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.. :)
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 am learning to write into a database from a textbox with the click of a button. I have specified the connection string to my NorthWind database in my web.config file. However I am not able to access the connection string in my code behind.
This is what I have tried.
protected void buttontb_click(object sender, EventArgs e)
{
System.Configuration.Configuration rootwebconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Mohtisham");
System.Configuration.ConnectionStringSettings constring;
constring = rootwebconfig.ConnectionStrings.ConnectionStrings["northwindconnect"];
SqlConnection sql = new SqlConnection(constring);
sql.Open();
SqlCommand comm = new SqlCommand("Insert into categories (categoryName) values ('" + tb_database.Text + "')", sql);
comm.ExecuteNonQuery();
sql.Close();
}
I get a tooltip error for
SqlConnection sql = new SqlConnection(constring);
as
System.data.SqlClient.Sqlconnection.Sqlconnection(string) has some invalid arguments.
I want to load the connection string from the web.config in constring
You can simply give a Name to your ConnectionString in web.config file and do this:
web.config:
<add name="ConnectionStringName" connectionString=YourServer"; Initial Catalog=YourDB; Integrated Security=True"/>
Code Behind:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());
That's because the ConnectionStrings collection is a collection of ConnectionStringSettings objects, but the SqlConnection constructor expects a string parameter. So you can't just pass in constring by itself.
Try this instead.
SqlConnection sql = new SqlConnection(constring.ConnectionString);
try this
readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwindconnect"].ToString());
I will suggests you to create a function rather than directly access the web.config file as follow
public static string GetConfigurationValue(string pstrKey)
{
var configurationValue = ConfigurationManager.AppSettings[pstrKey];
if (!string.IsNullOrWhiteSpace(configurationValue))
return configurationValue;
throw (new ApplicationException(
"Configuration Tag is missing web.config. It should contain <add key=\"" + pstrKey + "\" value=\"?\"/>"));
}
And use this function in you application
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SQLiteConnection connString = new SQLiteConnection(connectionString);
using (var command = connString.CreateCommand())
{
try
{
connString.SetPassword(ConfigurationManager.AppSettings["password1"]);
connString.Open();
connString.ChangePassword((String)null);
connString.ChangePassword(ConfigurationManager.AppSettings["password2"]);
connString.Close();
connString.Dispose();
}
catch (Exception e)
{
Console.Write(e.Message + "\n" + e.StackTrace);
}
}
I'm trying to test SQLite by having a simple console application. I'm using an app.config file to read passwords and connection string from. The code is able to set the password the very first time it runs but if I open the connection and try to change password by calling ChangePassWord() method, the password is not changed. I also try to set password to null and then reset it to some new password, but that doesn't work either.
The error is
File Opened that is not a database file. File is encrypted or is not a database
Some other people have the same problem: ChangePassword method problem.
I'm not 100% sure. But for some reason reading the connection string from the app.config could have some bearing on it. I took out the connection string and decided to hardcode it like so
SQLiteConnection connString = new SQLiteConnection("data source=\".\\SomeDatabase\"");
before was like so:
<connectionStrings>
<add name="connection"
connectionString="data source=".\SomeDatabase""
providerName="System.Data.SQLite" />
</connectionStrings>
Hope this helps somebody