473,763 Members | 1,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to change connection string for database class?

26 New Member
Dear all

i wrote one class to deal with sql database to insert and read data from that class only...and based on that one of the parmeters or the class is the sqlconnection

SqlConnection connection = new SqlConnection(@ "Data Source=.\SQLEXP RESS;AttachDbFi lename= {0};Integrated Security=True;C onnect Timeout=30;User Instance=True") ;

so the connection string is defined indepented of the class objects of the class (i mean class objects used by the other class)

but I need to change the database file or I want to change the connection string

so how can I change the connection string for the whole class ...

What I did

i define the connection in the beginning of the class

SqlConnection connection = new SqlConnection() ;

then I wrote a method

public void conntstr(string r)
{
connection = new SqlConnection(r );
}

and I passed the connection string to it...however it doesn't worte?

what can I do
Mar 6 '09 #1
6 6446
little83
26 New Member
ok I tried the following solution however i got error

ok
i tried the following solution

Expand|Select|Wrap|Line Numbers
  1.  
  2. class sqldatabase
  3. {
  4. public static String connectionString;
  5. SqlConnection connection = new SqlConnection(connectionString);
  6.  
  7. }
  8.  
in my application I made the following
Expand|Select|Wrap|Line Numbers
  1. if (open.ShowDialog() == DialogResult.OK)
  2. {
  3.                 connectionstr = string.Format(@"Data Source=.\SQLEXPRESS;AttachDbFilename= {0};Integrated Security=True;Connect Timeout=30;User Instance=True", open.FileName);
  4. }                                 
  5. sqldatabase.connectionString = connectionstr;
  6.  
however I got the following error when I start to access my database

The ConnectionStrin g property has not been initialized.

any ideas?
Mar 6 '09 #2
Plater
7,872 Recognized Expert Expert
Is your connection string following the formats listed here:
http://www.connectionstrings.com/sql-server-2005

It looks like you are missing the database name when attaching a db file?


It also looks like if you say cancel in your open file dialog, the connectionstrin g is still assigned to the object
Mar 6 '09 #3
vekipeki
229 Recognized Expert New Member
First problem is that you shouldn't be creating a database connection just like that, "in the middle of nowhere".

Create a private string field which contains the connection string only, and then create a connection only when you need to do a transaction.

Expand|Select|Wrap|Line Numbers
  1. // add this to your class, but not as a static field
  2. private string connectionString = null;
  3.  
  4. if (open.ShowDialog() == DialogResult.OK)
  5. {
  6.     // create the string using the specified name
  7.     connectionString = CreateConnectionString(open.FileName);
  8. }
  9.  
Then, just before sending a SQL query, create your connection:

Expand|Select|Wrap|Line Numbers
  1. using (SqlConnection connection = new SQLConnection(connectionString)
  2. {
  3.     // do something with database
  4. }
This way you are sure that SqlConnection will be closed and disposed after use. It is also obvious that you have to define your connection string before creating a connection.

The second problem is, the way it is implemented now, you expect from a caller to set that static field before creating a new instance of your 'sqldatabase' class. That is not a common practice in OOP, and you should always try to follow common programming patterns.

Third suggestion would be to try to follow C# naming conventions (you can google it, here is one example). Classes are never named in lower case (i.e. sqldatabase should be SqlDatabase), to distinguish them from variables and class fields.
Mar 6 '09 #4
little83
26 New Member
but I create the connection string in one class and the methods which deal with the sql database on other class...ur solution available if both on the same class..
Mar 6 '09 #5
vekipeki
229 Recognized Expert New Member
but I create the connection string in one class and the methods which deal with the sql database on other class
Nevertheless, you need to pass the connection string to SqlConnection to create it. I didn't say that the second part of the code needs to be in the same class as the first part, but you need to have the connection string ready before creating SqlConnection (that's what the error is telling you, after all).

Your class doesn't enforce that in any way - you are creating an SqlConnection from a static string, without knowing if it was initialized first. If you wrote it like this:

Expand|Select|Wrap|Line Numbers
  1. class SqlDatabase
  2. {
  3.     /// <summary>
  4.     /// Contains the connection string.
  5.     /// THIS FIELD CAN ONLY BE INITIALIZED 
  6.     /// IN CONSTRUCTOR.
  7.     /// </summary>
  8.     private readonly string _connectionString;
  9.  
  10.     public SqlDatabase(string connectionString)
  11.     {
  12.         _connectionString = connectionString;
  13.     }
  14.  
  15.     public void DoSomeQueries()
  16.     {
  17.         using (SqlConnection connection = new SqlConnection(_connectionString))
  18.         {
  19.             // do something
  20.         }
  21.     }
  22. }
Now it is obvious that you can only create SqlDatabase object like this:

Expand|Select|Wrap|Line Numbers
  1. SqlDatabase sqlDatabase = new SqlDatabase(connectionString);
Mar 6 '09 #6
little83
26 New Member
thanks very much..now it works
Mar 9 '09 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

0
4748
by: JWM | last post by:
I am trying to implement Oracle connection pooling for the following code, which was written by someone else. Here is my main question -- this java file creates code that is executed every hour, but once per week, the oracle server is brought down for backup. At that time, I get an error that looks like I have the wrong credentials for the database. For every subsequent attempt to run the hourly process, I am getting a broken pipe error,...
4
14027
by: rcmail14872 | last post by:
I have MS SQL Server 2000 evaluation version on my desktop PC. I have the SQL Server client tools (only) on the laptop. The two computers are networked. I had an Access MDB database on my laptop, but I converted it with the Access upsizing wizard to an Access ADP database with the Access front-end on the laptop connecting to the SQL Server on the desktop. Now I want to move from this test environment to the "real" server. How do I go about...
6
2619
by: craigkenisston | last post by:
How to change database name on the fly? I have an asp.net application in which a user connects to a sql server, where there's a centralized database with the users table and general settings. Then, each user also has a database in which his particular information is stored. There will be a few hundreds of this databases. Certain groups of users will share a database, all tables in this database have a userid column for identification...
1
6066
by: Sankalp | last post by:
Hi, I am using VB 2005. My application has many data bound controls. The connection is stored in the app.config file. I want the application to start with a default connection string and while during the runtime, the user can click on a button and change the connection string without exiting the application. I would really appreciate any sort of help.
2
3267
by: Orit | last post by:
Hello . Please find below my questions - I hope some of the ASP.NET experts of this forum will answer to those beginner's questions : My Web site should be able to work with either SQL Server or Access database as following : It will connect first to the Master database (SQL or Access, connection String of this database should be read from the C:\WINDOWS
6
8163
Cintury
by: Cintury | last post by:
Hi all, I've developed a mobile application for windows mobile 5.0 that has been in use for a while (1 year and a couple of months). It was developed in visual studios 2005 with a back-end sql server mobile ce database. Until recently I was synching everything thru a com port serial cable. The devices would connect to the computer thru activesync and are able to acquire an internet connection. The sync for the program occurs thru a website...
1
2619
by: dellis | last post by:
Problem: My project was initially created without putting passwords in the connection string. When I added the password in the connection string, it disappears when performing a database fill. I have stepped through the code in debug and the connection string is correct up til the Fill command. Once the fill executes, the password disappears from the connection string. This particular Fill is performed to check that the user is valid for this...
7
10113
OuTCasT
by: OuTCasT | last post by:
I know how to change the database and sqlserver for a crystal report Dim report As New ReportDocument Dim connection As IConnectionInfo Dim oldServerName As String = ".\SQLEXPRESS" Dim oldDatabaseName As String = oldDatabaseName Dim newServerName As String = newServerName Dim newDatabaseName As String = newDatabaseName Dim UserID As String = "" Dim Password As String = ""
0
9389
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10149
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10003
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9828
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8825
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7370
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5271
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5410
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.