Data not saved on application Close [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public static string cs = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+Application.StartupPath+"\\TestDB.mdf;Integrated Security=True;User Instance=True";
I have tried the above code for making the string global. The problem is that the data is saved until the application is open. As soon as I restart the application, the changes are not reflected in the database file. Also help me where to keep the database during deployment. I am using SqlServer 2008 and the database location is the Application folder
I have this code:
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True");
cn.Open ();
string ins = "insert into table1 values ('"+textBox1.Text+"')";
SqlCommand c = new SqlCommand(ins, cn );
c.ExecuteNonQuery();
string exts = "select * from table1 where kri='"+textBox1.Text+"'";
SqlDataAdapter adp = new SqlDataAdapter(exts,cnn);
DataTable dt = new DataTable();
adp.Fill(dt);
MessageBox.Show(dt.Rows[0][0].ToString());
cn.Close ();

The first issue here is that you kind of misunderstand a connection string. Think of a connection string like your address. It's not you, but it's where you reside. That connection string is just stating where the data you want to manipulate resides.
With that understanding we can answer the question about what to do in deployment pretty easily. During deployment you will load the database on to a real SQL Server. That SQL Server will reside somewhere, and thus be the address to that database. Therefore, when deployed, you'll change that connection string because the data you want to manipulate will reside somewhere else.
As far as persisting changes to the database. I guess that really depends on what framework you're using to make changes to the database. But let's just work out an example with the plain old ADO classes. Let's assume we have a table named tbl. And in that table there is an ID and a Name, and we want to UPDATE that name. So, we might do it like this:
using (SqlConnection c = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("UPDATE tbl SET Name = #Name WHERE ID = #ID"))
{
cmd.Parameters.AddWithValue("#Name", someName);
cmd.Parameters.AddWithValue("#ID", someId);
cmd.ExecuteNonQuery();
}
In this example, someName and someId may come from text boxes. They may be stored somewhere else. That's up to you on where to get those from. But that would persist the changes to the database.
Now let's work on housing that connection string. We definitely don't want that hard coded like that. The most common approach is to put it into the app.config/web.config file. So, let's do that. In the app.config/web.config file add a key to the <connectionStrings> section:
<configuration>
<connectionStrings>
<add name="Default"
connectionString="{Enter Connection String Here}"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Alright, now that we've done that, let's get that connection string from there instead. First add a reference to System.Configuration. Next, modify that line of code to be this:
public static string cs = ConfigurationManager.ConnectionStrings["Default"]
And so now, when you deploy this application, you just fix up the connection string during deployment.

Related

connecting to sql database from ASP.NET master page using c#

i Have this piece of code connecting to the database
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["savingsConnectionString"].ConnectionString);
string c = "select VersionName ,updated from dbo.DBVersionControl where id = (select max(id) from DBVersionControl)";
SqlCommand cmd = new SqlCommand(c, conn);
conn.Open();
SqlDataReader read = cmd.ExecuteReader();
while(read.Read())
{
Label1.Text = Convert.ToString(read["VersionName"]);
Label2.Text = Convert.ToString(read["Updated"]);
}
conn.Close();
read.Close();
it works when its is located in a normal page but it doesnt work when placed on a master page, no errors are reported though. Is there a way to make this work??
Place this in your Web.config, with the correct configuration you can use your database in all your Controller's and classes. It is a much cleaner way and edible after you upload your ASP.NET application to a web-server. You can edit the Web.config every time you want. You can't change your connection this easy when you hard-code it in your programm.
<connectionStrings>
<add name="NorthindConnectionString"
connectionString=" Server=MyDataServer;Integrated Security=SSPI;Database=Northwind;"
providerName="System.Data.SqlClient" />
</connectionStrings>
See this webpage
See this video how you make the connection

Best way to handle connection when calling a function from a Console App or SQLCLR object with ("Context Connection=true")

I have the following type of code in my data layer, which can be called from a console app, windows app, etc, with the proper connection string being read from the corresponding caller's App.Config file:
public static udsDataset GetDataset(int datasetID)
{
string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sql = #"select * from Dataset WHERE DatasetID=#datasetID";
using (SqlConnection conn = new SqlConnection(connectionString))
{
// Dapper query:
return conn.Query<udsDataset>(sql, new {datasetID } ).First();
}
}
I now want to call this same code from a SQLCLR stored procedure (within the database where these tables exist), where you would typically use a context connection:
using(SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
// etc etc etc
}
The most obvious approach that comes to mind is to overload the function:
public static udsDataset GetDataset(int datasetID)
{
string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
return GetDataset(datasetID, conn);
}
}
public static udsDataset GetDataset(int datasetID, SqlConnection conn)
{
// caller is responsible for closing and disposing connection
string sql = #"select * from Dataset WHERE DatasetID=#datasetID";
return conn.Query<udsDataset>(sql, new {datasetID } ).First();
}
So apps with an App.Config could call the connection-less version and SQLCLR could call the version requiring a SqlConnection.
This "seems ok", but having to write the exact same style of overload for every single similar function makes it feel wrong.
Taking the question (and comments on it) at face-value, why do you need:
the option of passing in an existing connection when calling from a SQLCLR procedure
? You should treat the Context Connection the same as any other connection with regards to Open and Dispose. It sounds like you are thinking that the SqlConnection, when using a Connection String of "Context Connection = true;", needs to be opened only once and then not disposed until completely done, whereas you would Open / Dispose of it several times otherwise. I don't see any reason to have differing behavior in these two scenarios.
All of that aside, how to best handle detecting the change in environment (between Console App and SQLCLR object)? You have two choices, both being probably easier than you are expecting:
Make no changes to the app code, but rely on an additional config file:
You can create a file named sqlservr.exe.Config in the C:\Program Files\Microsoft SQL Server\MSSQL{SqlVersion}.{SqlServerInstanceName}\MSSQL\Binn folder (e.g. C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn, where the 11 in MSSQL11 is for SQL Server 2012). The format of this file, as should probably be expected, is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="CoolioAppDB" connectionString="Context Connection = true;" />
</connectionStrings>
</configuration>
This might be considered "cleaner" code, but does introduce an external dependency that your DBA might be ok with, might dislike but tolerate, or might ask your manager to write you up for ;-).
Make a very minor change to the app code, but don't rely on an additional config file:
You can easily auto-detect whether or not you are currently running in SQL Servers's CLR host by using the IsAvailable property of the SqlContext class. Just update your original code as follows:
string connectionString = "Context Connection = true;"; // default = SQLCLR connection
if (!SqlContext.IsAvailable) // if not running within SQL Server, get from config file
{
connectionString =
ConfigurationManager.ConnectionStrings["CoolioAppDB"].ConnectionString;
}
This usage, by the way, is noted in the "Remarks" section of that linked MSDN page for the IsAvailable property.

ConfigurationManager.ConnectionStrings.ConnectionString Issue

I am trying to pull in data from a Microsoft Access database file, in order to populate several textboxes. (The textboxes are all done in XAML.) I'm quite sure I'm missing something, because the database file isn't accessed.
Here is my code:
DataTable tblVFWPostManagers = new DataTable();
string connString2 = ConfigurationManager.ConnectionStrings**/*["\\Documents\DatabaseFile.accdb"]*/**.ConnectionString;
string query2 = #"SELECT Manager ID, Manager FName, Manager LName, Manager Address, Manager City, Manager State, Manager Zip Code,
Manager Home Phone Number, Manager Cell Phone Number, Manager Email FROM tblVFWPostManagers";
//Fill the VFWPostManagers Set with the data
using (SqlConnection conn2 = new SqlConnection(connString2))
{
SqlDataAdapter da2 = new SqlDataAdapter(query2, conn2);
da2.Fill(tblVFWPostManagers);
}
Note: I'm sure the bolded is incorrect. However, I'm not really sure what goes in those brackets. I assumed, at first, that it was where the filepath went. When I commented that section out, the error disapperead though.
How can I pull in the data from my database using the above method? What am I missing?
A couple of errors in your code:
ConfigurationManager.ConnectionStrings references a specific section of your app config where are stored the informations to access your databases (one or more). The Section contains lines like these
<connectionStrings>
<add name="MyDataBase" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\myFolder\myAccess2007file.accdb;
Persist Security Info=False"/>
</connectionStrings>
(To create a valid connectionstring for your app look at www.connectionstrings.com)
So your code refers to these section voices using the 'name' key with
string connString2 = ConfigurationManager.ConnectionStrings["MyDataBase"].ConnectionString;
Said that now the text of your query will fail because you use extensively columns names with spaces. In this case every column name should be enclosed in square brackets.
string query2 = #"SELECT [Manager ID], [Manager FName], [Manager LName], .....
In your app.config or web.config file you have a ConnectionStrings section :
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="..."/>
</connectionStrings>
...
</configuration>
You can access it in your code :
string connString2 = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

Creating an SQL Server connection string without importing a datasource in C#

I am going off of this tutorial: http://www.dotnetperls.com/sqlclient . Instead of adding a data source and a having visual studio compile my connecting string - I want to do it myself. The reason being is that the database will not always be the same and I want this application to be able to use different databases depending on which I point it to.
So how can I manually create the connection string? I am using SQL Server 2005.
Step 1: Go to connectionstrings.com and find the proper format for your database.
Step 2: Plug in the appropriate values to the connection string.
Step 3: Pass that string to the constructor of SqlConnection.
I would also suggest storing your connection string in your app.config/web.config file. You can then modify them easily if needed. The proper format can be found at MSDN - connectionStrings element. You then change your code to:
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString);
I don't see where the connection string is "compiled".
In the code
SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString)
ConsoleApplication1.Properties.Settings.Default.masterConnectionString is a field and it can be replaced with any other appropriate string.
for SQL Server format of the connection string is
"Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = **;"
save this connection string in a string variable and use with connection object.
either way you can add in web.config file.
<ConnectionString>
<add name = "name_of_connecctionString" ConnectionString = "Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = ****;" ProviderName = "system.Data.SqlClient"/>
</ConnectionString>
you can change the provider as needed by you.
then in code behind file access this particular connection string using configuration manager.

C# Access DB Queries [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How can I perform queries on access using the C#? I want to create tables, and Insert/Select data from my access database.
You should check out all things you can do with OdbcConnection and OdbcCommand.
You can even steal the Connection String for your connection from:
Access 2007 Connection String Samples
...that should be enough to get you started.
Here's a tutorial to get you started.
http://www.csharphelp.com/2006/01/ms-access-application-with-c/
Depending on your version of Access, you may want to check out differenc connection strings as well.
http://connectionstrings.com
Here are 2 pretty good starting tutorials
Here is a good intro into what is actually going on.
Here has some pretty helpful example code.
Protip: Make sure you have the correct ODBC Drivers installed if they
are not already. I felt SOOOO stupid for not figuring that out from
the start lol ;p
As far as dealing with you db assuming your not creating a access db on the fly all you would have to do is create your db in access, save it, and add it as a data source to your application.See here
Example Insert:
var insertStatement = #"insert into familytree (firstname, lastname, city, Tel, Email) values (#firstname, #lastname, #city, #tel, #email); SELECT ##IDENTITY";
//Open your connection and command
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand cmd = new OleDbCommand(insertStatement, connection))
{
//set parameters and values
var identityQuery = #"SELECT ##IDENTITY";
var identity = -1;
cmd.Parameters.Add("#firstname", 'foo');
cmd.Parameters.Add("#lastname", 'foo');
cmd.Parameters.Add("#city", 'foo');
cmd.Parameters.Add("#tel", '6666666');
cmd.Parameters.Add("#email", 'foo#foo.com');
connection.Open();
try{
var numberOfRowsEffected = command.ExecuteNonQuery();
//we should have 1 row effected.
if(numberOfRowsEffected>0){
cmd.CommandText = identityQuery;
//get the identity
identity = (int)cmd.ExecuteScalar();
}
}catch(InvalidOperationException ex){
//log and throw:
//cant open connection or Cannot execute a command
//within a transaction context that differs from the
//context in which the connection was originally enliste
}
return identity;
}
Same thing applies if you were wanting to create a table. just write your create table statement. see here for example and execute. But as far as common approaches go you generally want to have you table structures already set up for most simple apps and let your Application handle inserts, updates, and possibly deletes. Not saying you shouldn't do it that way but I would consider KISS whenever possible.
Oh and here is an msdn ref to the OleDbCommand class if you were wondering else you can do. OleDbCommand

Categories