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
Related
I have as ASP.net project with localDB in it.
The database file name is ProjectDB.sdf and I placed him in the App_Data folder.
My connection string is:
<add name="ProjectConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\ProjectDB.sdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
I try to use the database in my cs file like this:
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ProjectConnection"].ConnectionString;
using(SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select JobTitleId, JobTitleText from LuJobTitle where JobTitleText like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
The application falls in the conn.Open(); command.
The error message I get says:
An attempt to attach an auto-named database for file d:\user\documents\visual studio 2012\Projects\RealMatchSite\RealMatchSite\App_Data\ProjectDB.sdf failed.
A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
What am I doing wrong?
Thank you in advance!
Your db server already has database attached with that name so you are getting that error. If this is not the case then try adding this to your connections string:
User Instance=True
Try using Initial Catalog to call your database.
I hope this helps.
connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=ProjectDB;Integrated Security=True"
I am not sure what I am doing wrong, If I use the connection string shown here, my application works fine.
SqlConnection conn = new SqlConnection();
string DbPath = Application.StartupPath;
DbPath = DbPath.Substring(0, DbPath.LastIndexOf("\\bin"));
DbPath = DbPath + "\\MyDatabase.mdf";
conn.ConnectionString = "Data Source=.\\EXPRESS2008;AttachDbFilename=" + DbPath + ";Integrated Security=True;User Instance=True";
but if I use connection string here, it's not inserting data into MyDatabase table
conn.ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString;
My app.config is
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="ERPSystem.Properties.Settings.MyDatabaseConnectionString"
connectionString="Data Source=.\EXPRESS2008; AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated
Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
INSERT statement and preceding code:
comm = new SqlCommand("CreateUser", MyConnection.MyConn("Open"));
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("#UserName", SqlDbType.VarChar).Value = userName.Text;
comm.Parameters.Add("#Password", SqlDbType.VarChar).Value = userPassword.Text;
comm.Parameters.Add("#UserRole", SqlDbType.VarChar).Value = UserRole.SelectedItem.ToString();
comm.ExecuteNonQuery();
This is the code to get the connection
class MyConnection
{
public static SqlConnection MyConn(string str)
{
SqlConnection conn = new SqlConnection();
try
{
//get application path
string DbPath = Application.StartupPath;
if (Program.RunFrEn == true) //bool var
//remove string after bin folder
DbPath = DbPath.Substring(0, DbPath.LastIndexOf("\\bin"));
//add database name with new path
DbPath = DbPath + "\\MyDatabase.mdf";
//generate new connection string for database
conn.ConnectionString = "Data Source=.\\EXPRESS2008;AttachDbFilename="
+ DbPath
+ ";Integrated Security=True;User Instance=True";
//conn.ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString;
if (str == "Open")
{
if (conn.State == ConnectionState.Closed)
conn.Open();
}
else
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return conn;
}
}
I am not getting any error
Thank you
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
I also had fighted long time with same problem. And I saw many same questions & answers.
You're using |DataDirectory|. I assume you can get values from the DB file and you don't get error to run insert command but the values are not inserted into the DB file.
This is absolutely my private idea and my private conclusion is that this behavior is normal as |DataDirectory| does. I mean a data file of an application should be protected from manipulation once after deployment. The 'Data' file should provide data inside the file so that we can read the data.
Therefore, I coded to create a localDB .MDF file (SQL Server 2014) from users' side so that my applications can utilize the localDB to write and read data. My application automatically downloads data from cloud server which are we need to update frequently. On the other side, I put big and already fixed data into |DataDirectory| .MDF file, I mean inserted big data for read only and add the .MDF file to my project before deployment.
Hope my experience helps.. But, please keep in mind again that this is really my private opinion and I might be totally wrong and my experience is limited only to localDB. But again, I couldn't find a Microsoft's official document mentioning this behavior.
Do you have only 1 option like |DataDirectory|? Did this work to insert before? Is this code by you wrote on your own? If possible, try to find another option rather than |DataDirectory| to connect to the SQL Server database. I use a cloud SQL server with IP address but I can't understand why you use |DataDirectory|. There might be many various options as connection strings to SQL Server Express.
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.
This is not the first time I have used databases using the C# in asp.net, but I can't seem to make it work in a Winforms app.
This is a test face, so there is not a real database but a SQL Server database file that I created.
What I have is this:
public AddControl SaveResearcher(string name)
{
using(SqlConnection conn = new SqlConnection("")){
SqlCommand cmd = new SqlCommand("INSERT INTO Personell VALUES (#name, #function)", conn);
cmd.Parameters.Add("name",SqlDbType.VarChar).Value = name;
cmd.Parameters.Add("function", SqlDbType.VarChar).Value = "Researcher";
conn.Open();
cmd.ExecuteNonQuery();
}
return AddControl.OK;
}
What do I have to put in the connection string?
Thanks in advance.
The connection string for at sql server db file without username/password
Server=.\SQLExpress;AttachDbFilename=c:\pathtodb\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
You may find more connection string options at
http://www.connectionstrings.com/sql-server-2008
You can check there,
Connection strings for SQL Server 2005
Do you mean soemthing like this?
"Data Source[SERVER_NAME];Initial Catalog=[DATABASE_NAME];Integrated Security=True;MultipleActiveResultSets=True"
connectionString="Data Source=computerName\sqlexpress;Initial Catalog=DatabaseName;Integrated Security=True"
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.