Proper way to connect to a local .mdb file using SqlDataReader? - c#

The connection always times out without generating an error message even though it is within trycatch. I suspect there is something wrong with the connection string. This is what I currently have:
string path = #"C:\PATH\TO\wantedDB.mdb";
if (!File.Exists(path))
throw new FileNotFoundException("File not found.");
else
Console.WriteLine("File found."); // File is found, so nothing wrong with that.
string connectionstring = "Database=wantedDB;AttachDBFilename=" +
path + ";Server=(local)";
using (SqlConnection conn = new SqlConnection(connectionstring))
{
Console.WriteLine("Opening connection...");
conn.Open();
Console.WriteLine("Connection opened."); // Program never gets here.
I have also tried a relational path in connection string like:
string connectionstring = "Database=wantedDB;AttachDBFilename=\"wantedDB.mdb\";Server=(local)";
The db is not protected by a password. I have MS Access installed, does that affect this somehow? What am I missing?

To connect to a mdb file you should use the OLEDB connector:
var con = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=C:\\wantedDB.mdb;");

Related

How to test for database availability in c# script task for an oledb connection

I have to check for database availability using c# scripting for an "oledb" connection in an ssis package.
Since my connection is oledb I'm not able to use AcquireConnection method.
I tried using ConnectionString property of ConnectionManager but I get the connection string even when database is offline.
Any idea how to go about with unmanaged Objects here oledb.
You can find the complete documentation here https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ado-net-code-examples
what you may need to test the oledb connection is then something like this:
string connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ "c:\\Data\\Northwind.mdb;User Id=admin;Password=;";
OleDbConnection connection = new OleDbConnection(connectionString);
try
{
connection.Open();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return true;

SQL server backup to shared folder

I'm trying to make a backup to a network shared folder with the following code:
string filePath = ("\\pc-usuario\folder\backup\backup.bak")
string connectionString = String.Format(#"Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=True", server, database);
using (var connection = new SqlConnection(connectionString))
{
var query = String.Format("BACKUP DATABASE [{0}] TO DISK='{1}'", database, filePath);
using (var command = new SqlCommand(query, connection))
{
connection.Open();
command.CommandTimeout = 1800;
command.ExecuteNonQuery();
}
}
Got the following error:
The backup device cannot be opened. Operating system error 5(Access denied.).
If I try it with SQLExpress the same error happens. What am I missing?
You havent given the database backup a file name, only a file path
E.g. the final code should read
backup database wibble to disk = '\\pc-usuario\folder\backup\wibble.bak'

How to do backup in C# application?

I will try to do a backup database from C# application. I found more tutorials how do that. In the new project copy some solution and run. All the time I got one connection error like:
"backup failed for server ".
In this line:
source.SqlBackup(server);
Do you know how I resolve this? I think that problem concerns connection to server (it's broken?).
Below you can see a Backup method:
public static void BackupDatabase(string backUpFile)
{
ServerConnection con = new ServerConnection(#".\SQLEXPRESS");
Server server = new Server(con);
Backup source = new Backup();
source.Action = BackupActionType.Database;
source.Database = "DB";
BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
source.Devices.Add(destination);
source.SqlBackup(server);
con.Disconnect();
MessageBox.Show("Kopia wykonana!");
}
Couple of things for you to try.
Make sure your database name is correct
source.Database = "DB"; // Check the database name is actually 'DB'.
I had some issues in the past using ServerConnection with a connection string, even though the syntax allows you to do so. What i did was to create an SqlConnection from the connection string and then give that to ServerConnection.
string connectionString = "Your connection string goes here";
SqlConnection sqlCon = new SqlConnection(connectionString);
ServerConnection connection = new ServerConnection(sqlCon);
I would also try initializing the backup object.
source.Initialize = true;
Added full control for PC Users to the backup folder on C:\ drive helped! Thanks all for help! But just I have one question: how I can modify above C# code that program should be yourself create backup folder on C:\ and do a copy database? Currently I must do it manually.

Troubles reconnecting to MySQL database from C#

I can successfully log on to the database with this:
MySqlConnection conn = new MySqlConnection();
MySqlConnectionStringBuilder connString = new MySqlConnectionStringBuilder();
connString.Server = textEditServer.Text;
connString.UserID = "root";
connString.Password = textEditServerPassword.Text;
connString.Database = "geysercontrol";
conn.ConnectionString = connString.ConnectionString;
try
{
conn.Open();
Properties.Settings.Default.Properties["ConnectionString"].DefaultValue = conn.ConnectionString;
conn.Close();
}
catch (MySqlException)
{
XtraMessageBox.Show("No connection could be established");
}
But when I try to use the ConnectionString property to reconnect with different class, I get an MySQLException saying
Access denied for user 'root'#'localhost' (using password: NO)
What can be the possible causes to this? The page on possible causes on the MySQL website doesn't include my situation.
The code I use to reconnect is:
connection = new MySqlConnection();
connection.ConnectionString = (String)Properties.Settings.Default.Properties["ConnectionString"].DefaultValue;
connection.Open();
And the connectionString definitely is the same in both cases. It is:
server=localhost;User Id=root;database=geysercontrol;password=password
Add persist security info = true to the connection string I think.
If it were me though I wouldn't put connection string with a password in it in there. If you ever call Save, it will be exposed in the config file.

File upload control error-Access denied used by another person

when upload the same file for the multiple times i am getting this error......
"The process cannot access the file 'd:\MarketingSystem\ExcelImport\Sample.xls' because it is being used by another process."
getting error in this line
RevenueDumpFileUpload.PostedFile.SaveAs(Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName);
This is my full code.....
protected void btnImport_Click(object sender, EventArgs e)
{
if (RevenueDumpFileUpload.HasFile)
{
string strFilePathOnServer = ConfigurationManager.AppSettings["RevenueDumpFileLocation"];
String sConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName + ";Extended Properties=Excel 8.0;";
string strPostedFileName = RevenueDumpFileUpload.PostedFile.FileName;
if (strPostedFileName != string.Empty && RevenueDumpFileUpload.PostedFile.ContentLength != 0)
{
//Delete Old file before uploading new file.
if (System.IO.File.Exists(strFilePathOnServer))
{
System.IO.File.Delete(strFilePathOnServer);
}
//Save-Upload File to server.
RevenueDumpFileUpload.PostedFile.SaveAs(Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName);
RevenueDumpFileUpload.FileContent.Dispose();
}
OleDbConnection Exlcon = new OleDbConnection(sConnectionString);
try
{
Exlcon.Open();
}
catch
{
return;
}
finally
{
RevenueDumpFileUpload.PostedFile.InputStream.Flush();
RevenueDumpFileUpload.PostedFile.InputStream.Close();
}
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", Exlcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(objDataset1, "XLData");
methodtosave();
}
}
In my web config file:
<appSettings>
<add key="RevenueDumpFileLocation" value="~/ExcelImport/"/>
How to resolve this?
Help me..
Thanks in advance
Well, if the OleDbConnection acts anything like the SqlConnection object, you've got this line:
Exlcon.Open();
which is opening the connection, but you don't have a matching line to close the connection. Which means the Jet database provider is going to continue to keep this file open until the connection object is garbage collected. It would be far better to wrap this line:
OleDbConnection Exlcon = new OleDbConnection(sConnectionString);
In a using statement, whose body extends over the remainder of the function, so that you're guaranteed that it's closed/disposed.
Next, have you considered what happens if multiple users upload files with the same name simultaneously - this method will be broken. It may be better to use a new file name on the server, related to the user ID or session ID, and wrap a try/finally around the whole method to ensure the file is deleted after use.
The above may be the cause of your current issues, if this is an error coming out of production - if two people attempt an upload at the same time, then both of their requests may go past the "delete if it exists" part of the code, then one request manages to save the file and open a connection, then the other request will fall over when trying to save the same file name.
You forget to pass the File Name and File Extension when you are trying to delete the file.
if (System.IO.File.Exists(Server.MapPath(strFilePathOnServer) + strPostedFileName+
System.IO.Path.GetExtension(RevenueDumpFileUpload.FileName)))
{
System.IO.File.Delete(Server.MapPath(strFilePathOnServer) + strPostedFileName +
System.IO.Path.GetExtension(RevenueDumpFileUpload.FileName) );
}

Categories