How to connect to local sdf file? - c#

I'm creating a simple windows C# form application. but I cannot connect to local database file (.sdf)
i'm using
using System.Data.SqlServerCe;
This is my app.config file
<add name="ConnectionString1"
connectionString="Data Source=D:\Work Place_VS\Dilshan_Hardware\Dilshan_Hardware\Database\AppDB.sdf"
providerName="Microsoft.SqlServerCe.Client.3.5" />
<add name="ConnectionString2"
connectionString="Data Source=|DataDirectory|\Database\AppDB.sdf"
providerName="Microsoft.SqlServerCe.Client.3.5" />
I am trying to connect database file through following code.
try
{
using (SqlCeConnection cn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ToString()))
{
SqlCeCommand cmd = new SqlCeCommand("SELECT routeName FROM tbl_route", cn);
cn.Open();
SqlCeDataReader reader1 = cmd.ExecuteReader();
while (reader1.Read())
{
MessageBox.Show("Result :" + reader1[0]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.ToString());
}
Even I use ConnectionString1 or ConnectionString2 it always jump into catch block while try to make connectionString.
Please help me to find the error of this code.

I think you need to add a Persist Security Info value
Try the following:
<add name="ConnectionString1"
connectionString="Data Source=D:\Work Place_VS\Dilshan_Hardware\Dilshan_Hardware\Database\AppDB.sdf;Persist Security Info=false;"
providerName="Microsoft.SqlServerCe.Client.3.5"

Related

ConnectionString with external file for SqlConnection

C# on VisualStudio 2017. Windows Forms Application.
Hi all. I've read on the web that is not possible to use an .udl file in which write a ConnectionString for a SqlConnection. Is that true at today? And, if yes, there is an alternative way to use an external file for a ConnectionString in SqlConnetion?
I have to run project in 5 PCs that have different connection strings, for example:
PC1) Data Source=PCNAME\SQLEXPRESS;Initial Catalog=DBNEW;User ID=sa;Password=123;
PC2) Data Source=SERVER\SQLEXPRESS;Initial Catalog=DB;User ID=sa;Password=999;
[...]
Currently I use a string inside the project
string connSQL = "Data Source=.\\SQLEXPRESS;Initial Catalog=DBNEW;Persist Security Info=True;User ID=sa;Password=123;";
that I have to change five times for the five PCs' different connection.
I've tried anyway to connect with an .udl file
string connSQL = "Data Source=.\\SQLEXPRESS;AttachDbFile=C:\\connstring.udl";
that contains this
[oledb]
; Everything after this line is an OLE DB initstring
Data Source=PCNAME\SQLEXPRESS;Initial Catalog=DBNEW;Persist Security Info=True;User ID=sa;Password=123;
but of course it doesn't works.
Any ideas for an alternative solution?
Finally I found a solution. Thanks also to MethodMan's comment I later realized that you can use an external file to compile the connectionString, that is MyProjectName.exe.config, which is saved in the same directory as the software exe, and which has the same functions and settings of the App.config.
So what I did is create a new FormConn where you manually enter data for the connectionString, overwrite them in MyProjectName.exe.config and link this file to Form1 for SQL database management. Below the code.
In the Form1.cs:
using System.Configuration;
public Form1()
{
//Check if a connectionString already exists
//To the first slot there is a system configuration so 1 = no custom connectionString
if (ConfigurationManager.ConnectionStrings.Count == 1)
{
FormConn frmConn = new FormConn();
frmConn.ShowDialog();
try
{
//Restart Form1 in the case connectionString has changed
Application.Restart();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Associates the custom connectionString to the string I will use in the code for operations that are connected to the DB.
StringSQL = ConfigurationManager.ConnectionStrings[1].ConnectionString;
}
In the FormConn.cs:
using System.Configuration;
using System.Reflections;
string appPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string appName = Environment.GetCommandLineArgs()[0];
string configFile = System.IO.Path.Combine(appPath, appName + ".config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
var sezione = (ConnectionStringsSection)config.GetSection("connectionStrings");<br>sezione.ConnectionStrings["MyProjectName.Properties.Settings.MyDataSetConnectionString"].ConnectionString = "Data Source=" + txtDataSource.Text + ";Initial Catalog=" + txtInitialCatalog.Text + ";Persist Security Info=True;User ID=" + txtUserID.Text + ";Password=" + txtPassword.Text + ";";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
this.Close();
And that's what I have inside my MyProjectName.exe.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="MyProjectName.Properties.Settings.MyDataSetConnectionString"
connectionString="Data Source=MyPcName\SQLEXPRESS;Initial Catalog=DB-1;Persist Security Info=True;User ID=sa;Password=123psw321"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
This worked for me!

Personalized database Connection string for C# application

I am trying to have a personalized database connection string for the machines i install the C# application into. I have created a database using Visual Studio but that only points the location of the database to my personal directory and that is not something general.
Now when i try to publish the application and try to install it in some other computer, the database gives me an error that it wasnt found, which makes sense because the connection string is pointing to my personal computers directory.
Here is part of my code:
private void button13_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;");
sda = new SqlDataAdapter(#"SELECT [Panel Progress].*
FROM [Panel Progress]", con);
fill_grid();
}
catch (Exception error)
{
label6.Text = error.Message;
}
}
Can anyone please guide me towards the right path to solve this issue and to generate a personalized connection string for every computer the database gets installed to?
In your app.config or web.config file (Whichever is relevant to you) add the following connection string under configuration tag.
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;" />
</connectionStrings>
If you already have a connection strings section then add only the
<add name="DbConnection" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;" />
Then in your C# code instead of hard coding the connection string you can use the config value.
string connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
private void button13_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(connectionString);
sda = new SqlDataAdapter(#"SELECT [Panel Progress].*
FROM [Panel Progress]", con);
fill_grid();
}
catch (Exception error)
{
label6.Text = error.Message;
}
}
Build it. Then when you deploy the application in to another machine all you have to do is change your connection string in the app.config or web.config(whichever is relevant for you) to the new file location without changing hard coded values and rebuilding the application again.

Connect to SQL Server 2008 Express database using C#

I am developing a Winforms application in which I am using SQL Server 2008 Express Edition as backend. But I am getting error:
Additional information: An attempt to attach an auto-named database for file D:\Hardik\Hardik\dotnet\TestApplication\TestApplication\bin\Debug\MyDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
My code is:
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select * From MyTable";
cmd.CommandType = CommandType.Text;
da = new SqlDataAdapter();
da.SelectCommand = cmd;
dt = new DataTable();
ds = new DataSet();
da.Fill(ds, "Login");
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
}
and my app.config file is:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyConnection"
connectionString="Server=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True; User Instance=True"
providerName="System.Data.Client"/>
</connectionStrings>
</configuration>
Where I am wrong?
use double slash instend of single slash.
A UNC path uses double slashes or backslashes to precede the name of the computer.
<connectionStrings>
<add name="MyConnection" connectionString="Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True; User Instance=True" providerName="System.Data.Client"/>
</connectionStrings>
for instance failure
As you got the error "instance failure", that might be the error with your SQL Server instance..
Make sure your SQL Server instance(MSSQLSERVER) is running, where you can check in: Services list. TO get into services list: open run dialog box and type: "services.msc" (without quotes) and hit Enter. That takes you to services management console, where you can check whether your instance in running or not..
If the problem still persists, then try using: Data Source=.\SQLEXPRESS instead.. :)

connection between asp.net , c# and sql server ( both versions are 2012)

i wrote a connection string in asp.net i.e add 2 data through 2 textboxes into the sql server database . but after pressing submit button i face to an error .
Details:
web.config:
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="myconectionstring"
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
try
{
///string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
SqlCommand cmd = new SqlCommand("INSERT INTO Table_1 (name,fathername) VALUES('" + txt1.Text + "','" + txt2.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
String ErrorMsg = ex.ToString();
}
finally
{
con.Close();
}
}
}
}
Error message :
Server Error in '/' Application.
Keyword not supported: 'initial catalogue'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Keyword not supported: 'initial catalogue'.
Source Error:
Line 21: {
Line 22: string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
Line 23: SqlConnection con = new SqlConnection(cs);
Line 24:
Line 25: try
Source File: c:\Users\Admin\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\WebForm1.aspx.cs Line: 23
Your connection string should start as follows:
Server=myServerAddress;Database=myDataBase;
instead of your current
data source=.\SQLEXPRESS;initial catalogue=test;
This should resolve your issue.
Use:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
And whenever you forgot a connection string of any database, go to:
http://www.connectionstrings.com
You misspelled Catalog wrong. Its
Initial Catalog
its a type at Initial Catalog correct the spelling and it should work !!
for more information :-
http://www.connectionstrings.com/sql-server-2012/

Autocomplete textbox in C# for windows application

when i run this code this error comes..
object reference not set to an instance of an object.
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{
SqlCommand cmd = new SqlCommand("SELECT NAME FROM CUSTOMER", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
AutoCompleteStringCollection MyCollection = new AutoCompleteStringCollection();
while (reader.Read())
{
MyCollection.Add(reader.GetString(0));
}
txtcname.AutoCompleteCustomSource = MyCollection;
con.Close();
}
Make sure your connection string in web.config something like
<connectionStrings>
<add name="ConString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Problem : i'm sure that you didn't declare the connection string in your config file under <ConnectionStrings> section.
OR
you might have declared it with some defferent Key name but not ConString.
Solution: you should declare the proper Connection String with Name ConString in your config file under <ConnectionStrings> section.
Make sure that your config file either App.Config or web.config has ConnectionString similar to following:
<connectionStrings>
<add name="ConString" connectionString="Data Source=ServerName;Intial Catalog=DatabaseName;UID=userID;Password=password;Integrated Security=True;" />
</connectionStrings>

Categories