Does every Form in c#.net needs a new connection to be established with sql database? - sql

I am creating a c#.net winforms application which uses sql server2005 express. I have three forms in the application.
So, first i connected to the database with windows authentication when Form1 is displayed which is the main form.It uses the connection string from app.config file.
Then i changed to the application role by executing sp_setapprole on a button click on form1.
Then, Form2 opens and i want that it uses the same application role which was set in form1 to connect to the database.
How do i do it?
Does every Form needs a new connection to be established with sql database?
I have created the application role beforehand in SQL Server.

No, I'd say that in general, for a thick (single-threaded) client, you probably want only one connection open (probably for the lifetime of the client).
You can keep the parameterless constructor for Form2 (which will be needed for the VS designer to continue to work), but you can create a second constructor for Form2 that is passed the open connection and continues to work with it, e.g.:
public Form2()
{
InitializeComponent();
}
private SqlConnection _conn;
public Form2(SqlConnection conn)
: this()
{
_conn = conn;
}
Otherwise (if you're a multi-threaded application), I'd recommend that you only open connections when required, perform your work, then close the connection again. Connection pooling will ensure this isn't as inefficient as it sounds, and trying to share a single connection among multiple threads can get very messy. If you're doing this, you might want to create an extension method on SqlConnection, something like OpenAndSetAppRole that will open a new connection and call the sp_setapprole proc before returning

As a starting point have a look at this article:
http://msdn.microsoft.com/en-us/library/ms971481.aspx
is a collection of best practices in using ADO.NET. An extract about connection is:
Using Connections
High performance applications keep connections to the data source in use for a minimal amount of time, as well as take advantage of performance enhancing technology such as connection pooling. The following topics provide you with tips to help you achieve greater performance when using ADO.NET to connect to your data source.
In other word you should connect to the database when you are issuing a conversation ( filling a page in a grid, updating a record and so on ).

Related

VB.Net Window Programming database coonection open close

I am working on a window project using VB.net. On every form of my project I opened Microsoft access database connection on form load and closed on form closing event. So I want to ask that this is good practice to open/close database connection on every form.
Consider the followings:
Would the db connection be used to update or only query?
How many users would open the form and connect to db at the same time?
If the users are many and they update db, I think it's not a good idea to keep connected while opening the form. Usually you may query some data upon opening and then close the connection immediately, and the same for updating.
It is good practice to create/open/close db connection every time you execute some query.
Notice that by create/open/close I mean instantiating new instance of SqlConnection.
Under the hood ADO.NET will open real, physical connection to the database server only once and re-use it every time you will open new connection by your code.
So every query should be execute with own new connection
Using connection As SqlConnection = new SqlConnection(yourConnectionString)
Using command As SqlCommand = new SqlCommand(sqlQuery, connection)
return command.ExecuteNonQuery();
End Using
End Using
If you open connection in Form_Load and close it in Form_Closing it possible that when exception thrown while form is opened your connection will remain opened.
By reducing amount of time when connection is "opened" in your code you can handle this situation by using Using keyword and avoid using of "ugly" try .. catch everywhere
And I hope you are using sql parameters (SqlParameter) in your queries.

Effects of connecting to the database manually in vb.net

I am coming from a php background background where we remotely connect to the database and manipulate everything with php code. Now in vb.net, will the performance of my desktop application be affected in anyway if i connect manually in the form_load event event instead of vb.net database source connection?
i come from both backgrounds.
yes you can manually open database BUT
you should specify the database you are using to make the best performance in your desktop application, for example:
in access database (mdb files), you should open the database once in form_load, and use it all the time, then close it before exitting the application in form_closing (this is for better performance)
while in SQL Server, you should open the database for each function then do your queries then close it after you finish.
Create a DataAccessClass.
Do your db functions in this class (update functions, select functions etc)
Connect to the db on class instantiation.
give your class the necessary work to do, and receive answers back from the class.
In essence, extract your data access from your forms, so that you can reuse your data class anywhere in your app

Global Connection from SQL Server Database to VB.NET

I want to create a global connection class from Sql server database to vb.net to make it easy in later editing the connection. Could anyone guide me the way to code both creating and calling to individual form?
Any help would be appreciated. Thanks
Keep your connection string in your web.config file. (this gives you a single point where you can change the connection string without needing to recompile your application, it also allows you to encrypt it in the future to protect your DB server).
I'd advise against using a single "connection" object for reuse. Open and close a connection for each query or transaction.
Check out the Repository pattern instead. http://msdn.microsoft.com/en-us/library/ff649690.aspx

Updating Datatable to EXISTING global database connection

I am using Microsoft Visual Basic 2010 Express. I have a WPF-based project. I have a successful connection to a database in Database Explorer, and a working existing Data Source in Data Sources.
I created a datatable from the datasource using this code:
Dim roster_table As New DataTable("AGENT_ROSTER")
I can manipulate this datatable just fine, but I cannot figure out how to save its data to my database (agentroster.sdf) since the connection is on a global level, and isn't declared in this particular window.
How do I update this database from the datatable on this window?
By the way, I tried creating a connection on this window's code, using the exact same connection string as the successful globally-connected database, yet it said that it couldn't connect.
Tough to say given the limited information you provided. You should also note that there are a lot of ways to do this. However the most basic way is to use a table adapter. Once you've set the Update, Insert and Delete commands you call its Update method.
Here's an MSDN article that might help you further

Creating Simple desktop database application

I am here to write a small database application that will be running in desktop (offline mode).
I am using MSAccess 2007 as my database file and trying to write code in vb.net.
I used to write the code vb6 an usually had global variables for storing database connection and executing every query from that.
I am trying to upgrade myself from vb6 to vb.net.
do i need to read some more simple starter books also?
In .NET, talking to a database is handled with ADO.NET, which uses something called "connection pooling". The connection pool is basically a collection of open connections to your database that ADO.NET manages for you. In your code, when you create and open a Connection object, ADO.NET first looks in the connection pool to see if it already has an open connection to your data source, and if it finds one it uses that (instead of actually creating and opening a new connection). When you close your connection, ADO.NET does not really close it, but instead returns it to the connection pool.
Therefore, you do not need (and in face do not want) to maintain open connection objects inside your application (in a global variable or anywhere). The correct approach with data access in ADO.NET is to create and Open a Connection object, do whatever you need to do with the database, and then Close and Dispose your Connection.
Store the connection string in the config file (in the solution explorer, open the My Project folder and doubleclick on Settings.settings).
I'd suggest that you create one or more classes to contain your database code and let those classes convert between the database data and your application objects, most VB6 projects I saw had the GUI hard linked to the DB which can make future maintenance or new features very difficult and limits the possiblity of code reuse.
If you've got VB6 experience I'd thought that you could probably start trying to create the application right away but you should definitely read either a good book or good articles about it at the same time so that you pick up things like that you need to Dispose of your database objects after user etc.
It's probably a good idea to get a book, a lot has changed since VB6.
Also consider using a more robust db, like SQL compact or SQLite. It will allow you you use the Entity Framework which will make writing your app a whole lot easier.