I'm creating a very basic CRUD desktop winforms application in C#/.NET 4.0.
Letting Visual Studio auto-generate the fields for the table I'd like to perform my CRUD operations on works just fine, but I'm running into problems when I try and interact with it manually with my own SQL queries.
The auto-generated fields are using the connection string:
Data Source=|DataDirectory|\Data Analysis.sdf
If I try and do:
SqlConnection conn = new SqlConnection(#"Data Source=|DataDirectory|\Data Analysis.sdf");
conn.Open();
It just hangs. What am I missing?
That's a connection string for a SQL Server Compact Edition (CE) database (everything stored inside a single .sdf file) - is that what you're using?
If so : in that case, you'd have to use SqlCeConnection (not a SqlConnection - that's for "grown-up" SQL Server version - not CE)
Maybe try adding some more options to the connection string:
Persist Security Info=False;
File Mode=shared read;
Believe you've specified a relative path to the .sdf file, where you might need to get the executable's runtime folder from System.Environment.CurrentDirectory and prepend it to the filename.
Related
I tried too many times but insertion doesn't work!
Please help me..
codes:
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO mytbl(Id, Nav) VALUES('yek','du')", conn); //yek and du are examples
//Following command doesn't work, too
//"INSERT INTO mytbl(Id, Nav) VALUES('"+tb.Text+"','"+tb2.Text+"')"
cmd.ExecuteNonQuery();
conn.Close();
The whole User Instance and 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. VictoryDatabase)
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=VictoryDatabase;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.
Your code is working but the db(.mdf) is getting copied to \bin\debug directory first and the app is using that one(\bin\debug\Database1.mdf). Use the following code to get the db (.mdf) path which is present at your App root directory.
string path = AppDomain.CurrentDomain.BaseDirectory.ToLower().Replace("\\bin", "").Replace("\\debug", "").Replace("\\release", "").TrimEnd('\\');
string conStr = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=" + path + "\\Database1.mdf;Integrated Security=True";
I created a database name="records" with the help of SQL Server Management Studio (SSMS). Now my question if I uninstall SSMS then can I still access the database from a C# program? If yes, then then is the process for connectivity still same as given below?
SqlConnection cnn ;
string connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
cnn = new SqlConnection(connetionString);
Management Studio is just a GUI client for interacting with a database. It is separate from the actual database.
In other words: you don't need Management Studio to programmatically access a MS SQL database.
Shortest answer, yes.
The management tools are an optional extra, all you really need is the database server.
I'm currently working on a wpf application where I tried to create a database.
I used data sources > add new datasource > dataset and copied the query string for its properties, but it is giving me the following exception:
What might be the problem? This is a local database... and when I click on the test connection button it writes "test connection succeeded"
Thanks
You are connecting to an SDF file. This means that you are using Sql Server Compact, not the full fledged Sql Server.
The classes to be used are named
SqlCeConnection
SqlCeCommand
The one you are using (SqlConnection) cannot understand the connection string used for a Sql Server Compact
Of course you need to add the reference to the assembly and the appropriate using directives
Assembly: System.Data.SqlServerCe.dll
using System.Data.SqlServerCe;
....
You are using a SqlConnection rather than the SqlCeConnection that you require. SqlConnection is for connecting directly to a "real" sql server.
Take a look at the MSDN for more information.
I created a new database using SQL Server 2008 R2 by using the Management Studio. The connection says (local) and I am using Windows Authentication (though I installed with mixed mode).
My questions are:
How do I connect to the DB via my C# application -
The only time I ever have done this before I just used VS Menu > Tools > Connect to DB and the drop down saw my database and connected, then right clicked on it and grabbed the connection string for use in connecting. However I'm thinking because its (local) I don't have that option.
As per Q#1 I am assuming the database file is being stored somewhere locally - I am wondering how to find that location and how I can include it with my application
Edit** Per comment: VSMenu-> View-> Server Explorer and then use add connection to connect to your local SQL Server instance and then use the database you created from the databases dropdown, and from advance settings copy the connection string created by the connection dialog
This is what I am looking for but I am missing the step during "add connection" where do I find my SQL Server I created locally? As mentioned before I have no idea where it is stored or how to find it
MSDN has an example in the SQLConnection documentation
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(queryString, connection))
{
command.Connection.Open();
command.ExecuteNonQuery();
}
You can then optionally use a SqlDataAdapter.
You need to use ADO.NET, which is comprised of a connection object (SqlConnection), command object (SqlCommand), parameters objects (SqlParameter) and data sets (DataSet) or data readers (SqlDataReader).
Read A Beginner's Tutorial for Understanding ADO.NET.
newbie here.
I have a local db in my program. Whilst I was developing the program I used the SQL
Connection string :
SqlConnection sconn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\leemk_000\Documents\......Integrated Security=True;User Instance=True;");
Now If I want to load this program onto a different computer I am sure that this connection will no longer work simply because it will still be looking for Users\Lee_000\
I have tried to remove Lee_000 but I get this following error:
An attempt to attach an auto-named database for file C:\Users\Documents..... failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
What can I do to get a connection string to work on different computers.
With many thanks
The whole User Instance and AttachDbFileName= approach is flawed - at best - especially when you want to share your database amongst multiple clients!
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. YourDatabase)
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=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
If it's a local db you should be placing it within the app folder and carry it with the app right?
Put the database in the App_data folder of your app and use that in your connection string
<add name="YourConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\yourfile.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
You need to use a database server and let your users use it via your connection string like this;
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
"myServerAddress" should be the ip adress of your server machine.