GetDatabase from Curent directory - c#

I try to open a connection with a database from curent directory, and I searched on google and I found that I need to use " System.IO.Directory.GetCurrentDirectory() ". and I recive this error
Database 'D:\Work\C#\DatabaseLoginPassProj\DatabaseLoginPassProj\Database1.mdf' already exists. Choose a different database name.
Cannot attach the file 'C:\Users\Mihai\AppData\Local\Temporary Projects\BazaDeDataIndependenta\bin\Debug\Database1.mdf' as database 'Database1.mdf'.
this is my code
private void InregistrareBTN_Click(object sender, EventArgs e)
{
string connstring = #" server=.\sqlexpress;
Database = Database1.mdf;
trusted_connection = true;
AttachDBFileName = " + System.IO.Directory.GetCurrentDirectory() +
#"\Database1.mdf;";
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
}
Thanks.
Ps: I don't want to specify the full path of the DB because I need to make the program working on every pc.

Related

embedded database connection string

I got two problems:
First, i'm trying to connect my windows form app with my embedded database (.dbf) and i keep getting this message no matter what i do to the connection string:
"error isam instalable cant be found"
Second, i would like to make the path relative to the executable.
Thanks, here is the code i'm using to test the whole thing:
private void bGuardar_Click(object sender, EventArgs e)
{
try
{
string cadena = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source =D:\\; Extended Properties = dBASE IV; UserID =; Password =;";
OleDbConnection con = new OleDbConnection();
con.ConnectionString = cadena;
con.Open();
MessageBox.Show("conected");
con.Close();
}
catch (OleDbException exp)
{
MessageBox.Show("Error: " + exp.Message);
}
}
For the second part, you can get the path of your executable using System.IO.Path.GetDirectory(Application.ExecutablePath). There are more ways do this based upon your need (see Best way to get application folder path).
To avoid further difficulties instead of
'OleDbConnection con = new OleDbConnection();'
try
using (OleDbConnection con = new OleDbConnection())
{
; // your command and executes here
}
this way you call the dispose / close method always (using generally wraps up your code so that the part between { and } is wrapped in a try / catch block with finally that calls a dispose() / close() on the OleDbConn object.

SQL Server CE connecting string not allowing for data insertion

OK, I've been working on this since late last night and early this morning. I am trying to insert some data into a SQL Server CE database. I am at the end of my rope.
Here is the code I am trying to implement:
public static void InsertData(string sqlStatement)
{
try
{
//string strConn = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
//string StartupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6); // remove file:\\
//string connectionString = #"Data Source=Database1.sdf";
//string connectionString = #"Data Source = |DataDirectory|\Database1.sdf";
//string connectionString = #"Data Source = C:\Users\My\Documents\Visual Studio 2012\Projects\VIN_Decoder\VIN Decoder\VIN Decoder\Database1.sdf"
//string connectionString = string.Format("Data Source={0}; Persist Security Info=False;", Path.Combine(Application.StartupPath, "Database1.sdf"));
//THIS ONE ACTUALLY WORKS!!!!!!!!!!!! :
//string connectionString = #"Data Source = C:\Users\My\Documents\Visual Studio 2012\Projects\VIN_Decoder\VIN Decoder\VIN Decoder\Database1.sdf"
string connectionString = Properties.Settings.Default.Database1ConnectionString;
SqlCeConnection sqlceCon = new SqlCeConnection(connectionString);
sqlceCon.Open();
SqlCeCommand sqlCeCom = new SqlCeCommand(sqlStatement, sqlceCon);
sqlCeCom.ExecuteNonQuery();
sqlCeCom.Dispose();
sqlceCon.Close();
}
catch (Exception e)
{
}
}
You can see all of the commented connection strings to see what I have tried. The strange thing is that I can simply use the following connection string in another method (a SELECT statement, not an INSERT INTO statement) that gets a single value from the data and it works fine.
string connectionString = #"Data Source = |DataDirectory|\Database1.sdf";
I have tested the query directly and like the comment says, the static path does work so that tells me my query is good. But of course I need something relative for publishing and multi-developer development.
Most of the connection strings I have tried allow the try block to complete with no errors, but the data doesn't get inserted.
Any suggestions?
I searched my heart out before posting this question, but Simon is right about similarity. However, we're going to have a better answer here. Corak is correct. I set property to not copy, deleted copy in bin\debug folder and app wouldn't run in debug mode because it couldn't find db even though paths all point to other file location. App is looking for copy in bin\debug. Ultimately, it was working all along. I recommend someone to make a connection to the copy in bin\debug so they can test values in the Server Explorer. Thanks for your help Corak and everyone else.
/*If your solution is web application, make sure Database1.sdf location path is under the
* App_Data folder
* Web.Config <add name="LocalDB" connectionString="Data Source=|DataDirectory|\Database1.sdf"/>
*/
protected string ConnString
{
get
{
return ConfigurationManager.ConnectionStrings["LocalDB"].ToString();
}
}
/*
* or you can use try absolute path as connectionstring
* modify your directory path as PhysicalApplicationPath result
*/
public string BaseDirConnString
{
get
{
if ((HttpContext.Current == null) || (HttpContext.Current.Request == null))
{
throw new ApplicationException("...");
}
return #"Data Source=" + HttpContext.Current.Request.PhysicalApplicationPath + "VIN Decoder\\Database1.sdf";
}
}
protected SqlCeConnection SqlCeConnection
{
get
{
var connection = new SqlCeConnection(BaseDirConnString);
connection.Open();
return connection;
}
}

Sqlite connecting to remote file using url C#

ive been trying to get my sqlite to read a remote file but is just flatout tells me this isnt supported is there a workaround for this ?
here is the function that gives the error
public void Run(string sql,string check,string file)
{
SQLiteConnection m_dbConnection;
string test = "Data Source=" + file + ";Version=3;";
m_dbConnection = new SQLiteConnection(test);
m_dbConnection.Open();
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
if (check == "0")
{
while (reader.Read())
comboBox1.Items.Add(reader["name"] + "." + reader["TLD"]);
comboBox1.SelectedIndex = 0;
}
else
{
proxy = reader["proxyip"].ToString();
check = "0";
}
}
error i get is "URI formats are not supported"
the file variable is filled by one of 2 values.
string filelocal = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\unblocker\\sites.db";
or
string remotefile = "http://127.0.0.1/test.db";
the one that gives the error is the remote file.
The Connection string uses as a datasource the db file which is expected on your local file system, take a look at this example code.
You can transorfm this using:
Uri uriFormatted = new Uri(file);
uriFormatted.AbsolutePath; // Try to use this value instead to call your function
EDIT
SQLite is a local standalone database, that is used for standalone software
Consider using SQLitening:
SQLitening is a client/server implementation of the popular SQLite database.

Binding csv file outside virtual path to datatable

I'm developing a ASP.NET 4.5 application which reads a log file of another application which is in server My Documents folder.
It works well when I run in debug mode but not once deployed.
Gives following error :
'C:\Users\Performance\My Folder\Log\' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
I have given Network Service and IISUSER read/write access to this file.(only this file and not folder)
This my code :
protected void lstArea_TextChanged(object sender, EventArgs e)
{
//create instance foe oledb connection class
OleDbConnection con = new OleDbConnection();
//Your datasource Location path currently i placed csv file in server location
string dsource = lstArea.SelectedValue;
//Put your datasource path in the connection string for example if you have csv files in C:\ directory change datasource= C:\
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dsource + ";Extended Properties='text;HDR=No;FMT=Delimited';";
try
{
con.ConnectionString = constr;
//create instance for command object
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
// set your file name in the below query
cmd.CommandText = "select * from [wksplog.txt]";
//Open Oledb Connection to read CSV file
con.Open();
//Create one datatable to store data from CSV file
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader(), LoadOption.OverwriteChanges);
//Bind data in the Gridview
gvMain.DataSource = dt;
gvMain.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
I'm passing the directory as C:\Users\Performance\My Folder\Log\
What is going wrong? BTW am using anonymous/ forms authentication. This machine is not in the domain.
The user the application is running as needs read access to all parent folders of the log file otherwise you will receive an access violation.

How can I connect to a SDF database? No connection string I try seems to work

I've tried literally 50+ different attempts at my connection string for my local database and nothing seems to work. I'm essentially just trying to open a connection the database file so I can dump in the data I've pulled out of my excel spreadsheet. I'm using Visual C# making an offline winform application.
No matter what connection string I try in my app.config, it always fails when it tries to write "dReader" to the database.
The error is usually this depending on what string I try:
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
I've gone through many online examples and resources and none seem to work. I'm hoping someone here can point out why it's failing.
Here is my app.config in its latest form:
<connectionStrings>
<add name="DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"
connectionString="Data Source=E:\Other DDP Projects\DDP_Project_SDF\DDP_Project\DDP_Database.sdf;"
providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
Here is my form code:
private void Profiles_Click(object sender, EventArgs e)
{
profilesDialog.FileName = "[YOUR_UPLOAD_FILE_HERE]";
var result = profilesDialog.ShowDialog();
if (result == DialogResult.OK)
{
HandleFileSelection();
}
}
private void HandleFileSelection()
{
var file = profilesDialog.FileName;
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\DDP_Database.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
string strConnection = ConfigurationManager.ConnectionStrings["DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"].ConnectionString;
//Create connection string to Excel work book
string excelConnectionString = string.Format(
#"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=""{0}"";
Extended Properties=""Excel 8.0;HDR=YES;""", file
);
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("SELECT [ID],[STATUS],[FAN_NUM],[PROFILE_NAME],[DESTINATION_HOST],[USER_ID],[USER_PASSWORD],[PROTOCOL],[PORT],[PATH],[CONTACT_NAME],[CONTACT_EMAIL],[CONTACT_PHONE],[CONTACT_ALT_PHONE],[CONTACT_CITY],[CONTACT_STATE],[CONTACT_CONTACT_TIME] FROM [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Profiles";
sqlBulk.ColumnMappings.Add("ID", "ID");
sqlBulk.ColumnMappings.Add("STATUS", "STATUS");
sqlBulk.ColumnMappings.Add("FAN_NUM", "FAN_NUM");
sqlBulk.ColumnMappings.Add("PROFILE_NAME", "PROFILE_NAME");
sqlBulk.ColumnMappings.Add("DESTINATION_HOST", "DESTINATION_HOST");
sqlBulk.ColumnMappings.Add("USER_ID", "USER_ID");
sqlBulk.ColumnMappings.Add("USER_PASSWORD", "USER_PASSWORD");
sqlBulk.ColumnMappings.Add("PROTOCOL", "PROTOCOL");
sqlBulk.ColumnMappings.Add("PORT", "PORT");
sqlBulk.ColumnMappings.Add("PATH", "PATH");
sqlBulk.ColumnMappings.Add("CONTACT_NAME", "CONTACT_NAME");
sqlBulk.ColumnMappings.Add("CONTACT_EMAIL", "CONTACT_EMAIL");
sqlBulk.ColumnMappings.Add("CONTACT_PHONE", "CONTACT_PHONE");
sqlBulk.ColumnMappings.Add("CONTACT_ALT_PHONE", "CONTACT_ALT_PHONE");
sqlBulk.ColumnMappings.Add("CONTACT_CITY", "CONTACT_CITY");
sqlBulk.ColumnMappings.Add("CONTACT_STATE", "CONTACT_STATE");
sqlBulk.ColumnMappings.Add("CONTACT_CONTACT_TIME", "CONTACT_CONTACT_TIME");
sqlBulk.WriteToServer(dReader);
sqlBulk.Close();
excelConnection.Close();
}
private void profilesDialog_FileOk(object sender, EventArgs e)
{
}
}
}
Try this...
First:
Create first a test method which you may check if you can connect to sqlcedatabase.
private void testconnection()
{
string strConnection = ConfigurationManager.ConnectionStrings["DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"].ConnectionString;
using (var conn = new SqlCeConnection(string.Format("Data Source={0};Max Database Size=4091;Max Buffer Size = 1024;Default Lock Escalation =100;", strConnection)))
{
conn.Open();
try
{
//your Stuff
}
catch (SqlCeException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
Second:
Just Load your excel file Data into a Datatable and use foreach then save it on your sql ce database file..
//Something like
//oledbcon
//oledb dataadapter
//datatable
// dapt.Fill(dt);
foreach(DataRow excel in dt.Rows)
{
ceCmd.Parameters.AddWithValue("ID",excel["ID"]);
ceCmd.ExecuteNonQuery();
}
Regards
I think the problem you are seeing is that you are trying to use a SqlConnection to connect to a SQL Compact database. The .sdf is a compact database and you have to use the SqlCeConnection to connect to it. You create the connection using this but then you don't use it. Instead you pass in the connection string to the SqlBulkCopy object which implicitly creates a SqlConnection from that string. I'm assuming it is on that line where you are getting the error. If you notice the namespace of the SqlBulkCopy is System.Data.SqlClient. The reason you are seeing the error is that its trying to go through SQL Server to make the connection and cannot resolve your connection string to a SQL Server database. Unfortunately, I don't think the System.Data.SqlServerCe has the equivalent to the SqlBulkCopy. Stick to using classes in System.Data.SqlServerCe and things should work as expected. You just will have to do the processing in a more manual fashion.
According to this post, SqlBulkCopy isn't supported with SqlCe.

Categories

Resources