How to connect to local database and update a dataset in C#? - c#

I have stored some products (a product contains: unique id - primary key, name, price, quantity) in a local database file (Stock.mdf, table for the products is called 'table').
The file is in my project folder in Visual Studio. When someone call an action in the form (WPF), a entry should be updated (new quantity).
In my C# code file i use the following code to connect to the database:
System.Data.SqlClient.SqlConnection con;
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = #"Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Stock.mdf; |
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
//Do i need the connect timeout? Found it somewhere in the web
I know that I can update the table in SQL with this command:
UPDATE table
SET Quantity=newQuantity
WHERE Id=GivenId;
How can I connect to the local dataset and update a product with the new quantity in c#?

First of all, please make use of using statements. They will ensure that IDisposable.Dispose() is called.
Written from memory:
string cs = #"Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Stock.mdf; |
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
using (SqlConnection con = new SqlConnection(cs))
using (SqlCommand cmd = new SqlCommand("UPDATE table SET Quantity=#q WHERE Id=#Id", con))
{
cmd.Parameters.AddWithValue("#q", newQuanity);
cmd.Parameters.AddWithValue("#Id", GivenId);
con.Open();
cmd.ExecuteNonQuery();
}
Do i need the connect timeout? Found it somewhere in the web
The default is fine for most circumstances.
Note that it is better practice to place the connection string in your app.config (or web.config, for web apps).
<connectionStrings>
<add name="MyConnectionName" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Stock.mdf; |
Integrated Security=True;
Connect Timeout=30;
User Instance=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Then access it like:
string cs =
ConfigurationManager.ConnectionStrings["MyConnectionName"].ConnectionString;

To connect to the Sql database using C# in Microsoft Visual studio,you have to manually add the System.Data.SqlSeverCe.dll name reference as follow:
Right-click on your Project >>> Add Reference
Browse >>> C:\Program Files\Microsoft SQL server Compact edition\v3.5\Desktop
Load >>> the System.Data.SqlSeverCe.dll >>> Add

Related

Connect LocalDB to ASP.net Project

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"

ConnectionString Database c#

I am create a database utility and I seem to not be able to get my connectionstring correct.
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|ConfigurationData.mdf;";
I believe this is in the correct format. As for the data source, my sql server is SQLExpress which runs sql server 2008 R2. My database is named ConfigurationData. Am I missing something?
When I run it, it opens the database - I assume it does since it does not through exception - but when I try inserting into a table, it does not actually insert it yet it executes the command.
conn.Open();
try
{
SqlCommand comm = new SqlCommand("INSERT INTO Test " + "(id,number) " + " VALUES(" + 10 + " , " + 12 + ")", conn);
comm.ExecuteNonQuery();
Console.WriteLine("Database is created successfully", "MyProgram");
}
catch (Exception ex)
{
}
finally
{
if ((conn.State == ConnectionState.Open))
{
conn.Close();
}
}
EDIT
Just remembered that I had answered a similar question a while back. Check it out:
Why can't I insert data into local database (SQL Compact Edition) with C#?
I don't think it is the connection string issue. But for your reference, a good site to refer to is http://www.connectionstrings.com/sql-server-2008/
You would need one of these:
Attach a database file, located in the data directory, on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;
Trusted_Connection=Yes;
Attach a database file on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;
Trusted_Connection=Yes;
Using an User Instance on a local SQL Server Express instance
The User Instance functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL
Server instance to a user with limited administrative rights on the computer.
Data Source=.\SQLExpress;Integrated Security=true;
AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;
To use the User Instance functionality you need to enable it on the SQL Server. This is done by executing the following command: sp_configure 'user instances enabled', '1'. To disable the functionality execute sp_configure 'user instances enabled', '0'.
try (local) instead of dot, dot is not recognized in Win XP
conn.ConnectionString =
"Data Source=(local)\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|ConfigurationData.mdf;";
You're SQL Statement isn't right also, and you should use parameters, but here is what you should have
SqlCommand comm = new SqlCommand("INSERT INTO Test (id, number) VALUES('" + 10 + " ', '" + 12 + "')", conn);
Why not just use the SqlConnectionStringBuilder class?:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = #"(local)\SQLExpress";
builder.UserInstance = true;
builder.IntegratedSecurity = true;
builder.AttachDBFilename = "|DataDirectory|ConfigurationData.mdf";
SqlConnection conn = new SqlConnection(builder.ConnectionString());
The output:
"Data Source=(local)\\SQLExpress;AttachDbFilename=|DataDirectory|ConfigurationData.mdf;Integrated Security=True;User Instance=True"
One of the way to do this is to add your connection string in web.config file as shown below:
Jus click on the properties of database on the database explorer. There you will find connectionstring in its properties. Jus add it in connectionstring below.
<configuration>
<connectionStrings>
<add name="ConnectionName" connectionString="your connection string" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Then in the page you can store it in string or directly refer to your connection as shown below:
Connection con=new SqlConnection();
con.ConnectionString=ConfigurationManager.ConnectionStrings["connString"].ToString();
and I suspect your insert statement is not properly declared.
Just try this:
SqlCommand comm = new SqlCommand("INSERT INTO Test (id,number) VALUES('10' ,'12')", con);
That's all from my part... Hope it helped you..

Connecting to local SQL Server database using C#

Suppose I have created a SQL Server database called Database1.mdf in the App_Data folder in Visual Studio with a table called Names.
How could I establish a connection to read the table values using C#?
So far I've tried something like this:
SqlConnection conn = new SqlConnection("Server=localhost;Database=Database1;");
conn.Open();
// create a SqlCommand object for this connection
SqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from Names";
But I get an error:
database not found/error connecting to database
In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there
If you use SQL authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you use Windows authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you're using SQL Server express, change
SqlConnection conn = new SqlConnection("Server=localhost;"
+ "Database=Database1;");
to
SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;"
+ "Database=Database1;");
That, and hundreds more connection strings can be found at http://www.connectionstrings.com/
SqlConnection c = new SqlConnection(#"Data Source=localhost;
Initial Catalog=Northwind; Integrated Security=True");
You try with this string connection
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;
I like to use the handy process outlined here to build connection strings using a .udl file. This allows you to test them from within the udl file to ensure that you can connect before you run any code.
Hope that helps.
Visual Studio 2019 (and probably a few previous versions).
View -> SQL Server Object Explorer
Top of the tree is 'SQL Server'
Under 'SQL Server', are couple of '(localdb)....'
Expand the (localdb)... -> Databases until you find your db.
Database Name (eg. Database1) -> Right-click -> Properties, and scroll the many properties (eg. "ANSI
NULL Default"). Find the "Connection string" property, copy the value
into your code, and you're running.

Connection string for C# winapp with a SQL Server database file

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"

SqlDependency.Start An attempt to attach an auto-named database for file failed

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.

Categories