I'm fight with a strange error occurs a couple of day ago and I'm not able to find a solution.
I have a C# Form application that talks with a SQL database made by Visual Studio Express (.mdf file). Everything works fine if my connection string points to the database in the root directory (where the DB has been automatically created by VS). I can compile the executable in Debug and Release.
To do a test in a different machine (where I copied the executable file and the database .mdf)I have changed the connection string in order to point to the database in the same executable directory and, in this case, it doesn't work (both release and debug).
I come to my PC and I use the same connection string above pointing not to the DB in the root directory bu to DB in Release directory.
The strange thing is that it works in debug but not in release.
The error occurs is the following one
Exception: One or more files do not match the primary file of the
database. If you are attempting to attach a database, retry the
operation with the correct files. If this is an existing database,
the file may be corrupted and should be restored from a backup. Could
not open new database 'C:\USERS\TEST\VISUAL
STUDIO\PROJECTS\LEONARDO\LEONARDO
0.1.1.1\LEONARDO\BIN\RELEASE\DB.MDF'. CREATE DATABASE is aborted. An attempt to attach an auto-named database for file C:\Users\Test\Visual
Studio\Projects\Leonardo\Leonardo 0.1.1.1\Leonardo\bin\Release\DB.mdf
failed. A database with the same name exists, or specified file cannot
be opened, or it is located on UNC share. Log file
'C:\Users\Test\Visual Studio\Projects\Leonardo\Leonardo
0.1.1.1\Leonardo\bin\Release\DB.ldf' does not match the primary file. It may be from a different database or the log may have been rebuilt
previously.
and the code is
string Result = string.Empty;
SqlConnection conn = new SqlConnection(Settings.DataBasePath);
try
{
conn.Open();
}
catch (Exception ex)
{
string Errore = String.Format("Exception: {0}", ex.Message);
MessageBox.Show(Errore);
throw;
}
SqlDataReader leggi = null;
//SqlCommand comando = new SqlCommand("SELECT " + "Database Version" + " FROM Data", conn);
SqlCommand comando = new SqlCommand("SELECT * FROM Data", conn);
leggi = comando.ExecuteReader();
while (leggi.Read())
{
Result += leggi["Database Version"].ToString().TrimEnd();
}
conn.Close();
Best regards
Your problem is here:
Log file 'C:\Users\Test\Visual Studio\Projects\Leonardo\Leonardo 0.1.1.1\Leonardo\bin\Release\DB.ldf' does not match the primary file.
You should make sure your debug and release folders contain the same .mdf and .ldf files.
Related
The file does exist at this path, it is a mdb file. However the system is saying that it does not recognise the file, the following error is coming up
System.Data.OleDb.OleDbException: 'Could not find file 'C:\Users\shera\Desktop\repos\Elevator\Elevator\bin\Debug\net6.0-windows\elevator-Records.mdb
var DBPath = "elevator-Records.mdb";
conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + DBPath);
conn.Open();
System.Windows.Forms.MessageBox.Show("Connected successfully");
My suggestion for you is ADO.NET wey
You should go to your database and write
Insert commands or update or delete an paste in your string
In this wey you should using SQL commands
In top of your class
You should go search in net to know ADO.NET
I am trying to write an application that will create a local database if it's not found in the application's folder. I run this query after deleting the .mdf
IF EXISTS (SELECT * FROM sys.databases WHERE name = N'Test_db')
BEGIN
DROP DATABASE Test_db
END
CREATE DATABASE Test_db
ON PRIMARY (NAME=Test_db, FILENAME='...\Test_db.mdf')
My command.ExecuteNonQuery() throws an exception, even though it drops the database and creates a new one. The error comes from the DROP DATABASE part of the command.
Additional information: Unable to open the physical file
"...\Test_db.mdf". Operating system error 2: "2 (The system cannot
find the file specified.)".
File activation failure. The physical file name
"...\Test_db_log.ldf" may be incorrect.
I found this question, but it has no solution to the problem.
The solution to the problem was to sp_detach_db because it removes the database from the server without deleting files from the file system
EXEC sp_detach_db 'Test_db'
If you are worried about the file being deleted, try File.Exists
if (File.Exists(pathname))
{
// Execute your SQL
}
else
{
// Error processing
}
I am using C# for a WPF application in Visual Studio Express 2012. I followed the tutorial found here.
I created a testDb.mdf local Service-based database. I open the application, enter text, hit add, and the data adds to the db. I only know this because I have the one field setup as a primary key and unique. If I try to add the same thing again I get an error saying it already exists.
When I exit my application nothing shows in the database. The data I entered is gone. Why is the data not permanent?
Here is the code I'm using for my button click:
private void Add_Click(object sender, RoutedEventArgs e)
{
SqlConnection cn = new SqlConnection(global::testdb.Properties.Settings.Default.testDBConnectionString);
try
{
string sql = "INSERT INTO Test (TestInsert) Values('" + txtName.Text + "')";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Added new record", "Message", MessageBoxButton.OK);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"Error", MessageBoxButton.OK);
}
finally
{
cn.Close();
}
}
Connection String:
<connectionStrings>
<add name="testdb.Properties.Settings.testDBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\testDB.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
It is a common scenario. You have a connection string that uses the substitution string |DataDirectory|. In a desktop application this directory is usually the same directory where your program runs. Inside Visual Studio, your program runs in the BIN\DEBUG (or x86 variant) directory. Thus the Visual Studio copies your MDF file from the project directory to the BIN\DEBUG folder. You add records to this copy, not to the one in the project folder. However, the Visual Studio Server Explorer window has a connection that points to the Project Folder database that, of course, remains empty.
You could add another connection to the Server Explorer pointing to the folder BIN\DEBUG and check that your database has been updated or not.
To complicate the matter, there is the property Copy to the Output Directory associated with the MDF file. If this property is set to Copy Always everytime you start a new session within Visual Studio, the file is copied again from the project folder to the output directory (BIN\DEBUG) overwriting the copy already there with a new empty one. So the first run succeds, the second one fails.
The symptoms that you observed are a clear sign of this situation.
Simply change the property Copy to the Output directory to Copy if newer, the code works well.
(Peraphs it is too early, but remember to change your query to a parameterized query. As is, you could break your code simply inserting a single quote in the txtName textbox like O'Malley, not to mention the Sql Injection hack)
I think your issue is not with the insert code. It's with the way you're checking the database/table yourself. Particularly because you say you're getting primary key errors so something's being added to the table.
Are you sure you're refreshing your view of the table properly? Are you sure you're checking the right table in the right database?
Make sure your initial catalog is set in your connection string, and be sure you are pointing to the right server/ instance of SQL. You may have multiple instances of SQL Server on the same server or whatever DB Server you are using. Also ensure you're going to the right table, of course.
using (SqlConnection cn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=testDB;server=(local)"))
{
string sql = "INSERT INTO Test (TestInsert) Values('" + txtName.Text + "')";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Added new record", "Message", MessageBoxButton.OK);
}
Check in SQL Server Studio that the database exists. I don't recommend using the filename mdf in your code directly using AttachDbFilename. Use the initial catalog.
Well, i found the solution. I solved it by installing SSDT(SQL server data tools) for visual studio. Install it according to your visual studio version. Go to following link to download the SSDT for visual studio.
https://msdn.microsoft.com/en-us/mt186501
In the following of the Steve's answer you can get your database full path in properties window and substitute it with |DataDirectory| in string connection.
your code will be like
conn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=G:\MhD\c#\phonebook\phonebook\phonebook\tellbook.mdf;Integrated Security=True";
It is a follow-up question to my previous question in the same forum.
I would like to take a backup of my SQL Server database. Here is the code, for the backup in C#.
userConn = new SqlConnection(userdatabase);
userConn.Open();
string UserString;
UserString = "BACKUP DATABASE #DBName TO DISK = #FilePath";
String destPath = DestDirectory + "\\UserDataTable.bak";
SqlCommand cmd = new SqlCommand(UserString, userConn);
cmd.Parameters.AddWithValue("#dbName", userConn.Database);
cmd.Parameters.AddWithValue("#FilePath", destPath);
cmd.ExecuteNonQuery();
cmd.Dispose();
However, it throws an SQLException,
"Cannot open backup device
'D:\BookKeeping\Database\11_01_2013_21_15\Database\UserDataTable.bak'.
Operating system error 3(failed to retrieve text for this error.
Reason: 15105). BACKUP DATABASE is terminating abnormally."
Any Idea, what could be wrong ?
Thanks a lot for your time and your help.
"Operating system error 3" means that the directory was not found. SQL will not create the backup directory for you; you have to manually create it before running the backup command.
Make sure your SqlServer and the location where you want to create a backup is the same system. If you are using sqlServer remotely(Not located in your system) then you can not create a backup in your machine or you can not restore the database taking a .bak from your machine also.
My C#.Net windows Application connects to a SQLServer2005 database and implements database backup functionality.
In my Application,
I try to perform a file copy like this:
<!-- language:lang-csharp -->
File.Copy(Application.StartupPath + "\\dbSTK.mdf", "D:\\dbSTK123.mdf",true);
but it throws an exception with the following message:
" The Process cannot Access the File, because it is being use by another Process"
How can I copy the db file which is already in use?
You cannot copy mdf file while SqlServer is running. Just temporary shut SqlServer down or Detach that database (here) before copying.
Rather that copy the actual MDF, it's probably a better idea to backup the MDF using SQL Server's built in BACKUP command.
The suggestions to detach the database and then copy it are problematic because it takes your database offline.
The server denies inteprocess access to data files. Once it has opened a data file no other process can open one too. That's why your function fails.
You should close all open connections to DB to access the DB file. But generally, you should not touch the database file. You'd better use SQL command to back up the database.
string backupCommandText = "BACKUP DATABASE [<YOUR_DB_NAME>]" +
"TO DISK = N'<BACKUP_PATH>' WITH NOFORMAT, NOINIT, " +
"NAME = N'Web-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = backupCommandText ;
cmd.Connection = conn;
cmd.ExecuteNonQuery();