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;
Related
I have the following code.
private void CreateDBFFile()
{
string connection = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (OleDbConnection dbconnection = new OleDbConnection(connection))
using (OleDbCommand command = dbconnection.CreateCommand())
{
dbconnection.Open();
command.CommandText = "CREATE TABLE Test (Id Integer, Changed Double, Name Text)";
command.ExecuteNonQuery();
}
}
My web.config file has connection string
<connectionStrings>
<add name="conn"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=k:\temp1"
providerName="System.Data.OleDb" />
</connectionStrings>
I am trying to create a dbf file on my K drive. I keep getting an error on my dbConnection.Open() statement saying:
The Microsoft Jet database engine cannot open the file 'k:\temp1'. It is already opened exclusively by another user, or you need permission to view its data.
K:\ is not a mapped drive. I gave network service userName to temp1 folder by going under security tab. I also gave modify rights to the Network service. Still keep getting this error. I also tried to put the entire above code in console application, that didn't work either. I keep getting the same error.
Any help will be greatly appreciated.
I need to make a connection setting in my system (changing the connection string in run time). I mean the user can set up and connect to any server they want. My question is, how can I retrieve the last connection string the user made in the connection setting and use it when the user re run the program?
So far this what I've made :
connect = "Data Source=" + Class1.DS.ToString() + ";Initial Catalog=" + Class1.IC.ToString() + ";Integrated Security= True;pooling=false;Connection Timeout=0;";
MessageBox.Show("Connection Made!");
this.Close();`(this is for the settings form)
frmSettings settings = new frmSettings();
connectString = frmSettings.connect.ToString();
dbconnection = new SqlConnection(connectString);
dbconnection.Open(); //<--(and this is where I call the connection string after the set-up)
What will I do to retrieve the last connection string the user made? Any suggestions please help me..
I assume you are using WinForm. There are many options about saving settings such as registry, custom ini...etc. The easiest one I always try before going elsewhere is config file.
Add "System.Configuration" into your project reference. Right click your project and "Add New Item", search for "config", you will see "Application Configuration File", add it. Now you have a App.Config.
You can add items into the file like:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="Config1" value="Foo" />
<add key="Config2" value="Bar" />
</appSettings>
</configuration>
And to use it, you can do:
Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var conf = configManager.AppSettings.Settings;
string val1 = conf["Config1"].Value;
You can play with the OpenExeConfiguration call to look for different locations depending on your YourApp.exe.config file, but you get the idea...
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.
iv'e got copy of NORTHWND.mdf along with NORTHWND.LOG in my App_Data folder
MY CONNECTION STRING :
<add name="northwind_connection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|NORTHWND.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
when i attempt to open and close the connection everything works out fine.
string connStr = WebConfigurationManager.ConnectionStrings["northwind_connection"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand command = new SqlCommand("Select * From Products");
command.Connection = conn;
conn.Open();
SqlDataReader reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
conn.Close();
now beside this code i want to add SqlCacheDependency to the page
when i place the code : Shown in msdn
SqlDependency.Start(connStr);
I GET THE FOLLOWING ERROR :
An attempt to attach an auto-named database for file C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\NORTHWND.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
any ideas why this happens , what do i need to configure for the SqlCacheDependency to work.
thanks in advance
eran.
in addition i would like to add that if i change my connection string to a specific one
<add name="northwind_connection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\NORTHWND.MDF; Integrated Security=True" providerName="System.Data.SqlClient" />
everything works as it should but that seems wrong since i don't expect users to change the connection string to their path , that's why i would like to put it in App_Data
or at list give a relative path to .\SQLEXPRESS
which also doesn't work :
<add name="myConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=NORTHWND;Integrated Security=True;" providerName="System.Data.SqlClient"/>
please shed some light on this issue there must be some configuration that makes this possible .
thanks in advance.
eran.
I don't think you can use SqlCacheDependency with an auto-attach (SQLEXPRESS) type connection string.
You need to attach the database in Management studio, and change your connection string to look like:
server=(local);database=Northwind;Integrated Security=SSPI;
Then you need to execute ALTER DATABASE NORTHWIND SET ENABLE_BROKER
If you need to provide this kind of setup for users then you can write a SQL Script that will do it for them.
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.