Issue with .mdf and installshield - c#

I have a program that connects to .mdf using SQL Server 2014 localdb. It needs to install to program files so it can't use click once. That being said, when I build it with click once. it works perfectly np.
However when I install it via install shield i get this exception
The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:\Program Files (x86)\King Canine\King Canine Software\CanineDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I have the SQL Server 2014 LocalDB as part of the redistrib selected and it is installed on the computer I'm testing it on.
Has anyone ever had this issue before or have any idea?

Based on the error message you posted, it can mean either of the following:
A database with the same name exists
this means that the database you are trying to attach already exist on the database.
specified file cannot be opened, or it is located on UNC share
you can try to check if the folder of the .mdf file you are trying to attach has enough folder access rights, you can see this on the folder's properties, in the security section.

Change the connection string like this:
string connectionStr = #"Data Source=(LocalDB)\MSSQLLocalDB; Database=CanineDatabase.mdf;Integrated Security = True";
Make a T-SQL query for make Database in server:
USE [master]
GO
IF NOT EXISTS(SELECT * FROM sys.databases WHERE name = 'CanineDatabase.mdf')
BEGIN
EXEC sp_attach_db #dbname = N'CanineDatabase.mdf',
#filename1 = 'C:\Program Files (x86)\King Canine\King Canine Software\CanineDatabase.mdf',
#filename2 = 'C:\Program Files (x86)\King Canine\King Canine Software\CanineDatabase_log.ldf';
END
GO

Related

Failed to update database "C:\Program Files (x86)\folder\dbRecords.mdf" because database is read-only

I am creating a C# WinForms Application along with SQL LocalDB. I am new to SQL. I have also added a setup project to create install the application to other PCs. When I installed the application, it is giving the error:
I do not want user to manually change the permissions and I am not in control of the location whether user will install on C: or any other drive. Is there any way I can update the settings while creating the setup file? The ReadOnly property of the database in Setup is already False.
Is there any other way I can achieve this?
I have checked many posts regarding the same issue which are not working for me:
Unable to update database .MDF is Read Only
Failed to update .mdf database because the database is read-only (Windows application)
Edit:
Following #John's solution I added the below code. Please let me know if this is the right way or there is anything more optimized.
var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\AgeCalculator";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
File.Copy(Directory.GetCurrentDirectory() + "\\dbUserRecords.mdf", path + "\\dbUserRecords.mdf");
}
string conn = Properties.Settings.Default.dbUserRecordsConnectionString;
//Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbUserRecords.mdf;Integrated Security=True
conn = conn.Split('|')[0] + path + conn.Split('|')[2];
Edit 2:
I found the better way to do the above Edit :
connectionstring to Access sql localDB in appdata folder
https://stackoverflow.com/a/8354765/10975845

How to package .sdf Database Application on CD and run without installing on machines

I am having a challenge that is specifically unique to me. I have browse the questions and answers catalog and what i found does not specifically address my scenario.
I created Windows Application on C#.Net with SQL Server CE at the back-end. I want the Application to be packaged in CD in such a way that my User will not install it rather will just insert and use the Application.
I have build the Application and copied the DB file, Application File, Configuration Files, Manifest Files and the .dll files to a folder and zipped it. Then copied the zipped folder to a CD ROM and run on a different system.
On the System I installed SQL Server CE Runtime installer. The Application executed successfully but when I attempted to submit a Form that is connected to the .sdf database the following exception was thrown:
The path is not valid. Check the directory for the database. [Path = C:\Users\John\AppData\Temp\Temp2_App.zip\App\Data\abc.sdf]
My Application Connection String at App.Config is:
<connectionString>
<add name="MyApp.Properties.Settings.MyAppConnectionString"
connectionString="DataSource =|DataDirectory\\abc.sdf|"
providerName="Microsoft.SqlServerCe.Client.3.5 />"
</connectionString>
The Connection Strings I used in my codes is:
string conString = "Data Source=|DataDirectory|\\Data\\abc.sdf";
Please what is it that I am getting wrong. Please help me.
Well, in the quest to finding a solution to the problem I have modified the App.Config Connection String to:
<connectionString>
<add name="MyApp.Properties.Settings.MyAppConnectionString"
connectionString="DataSource =|DataDirectory|\\Data\\abc.sdf"
providerName="Microsoft.SqlServerCe.Client.3.5 />"
And when I executed the Application on a user Machine it flag the exception - Access to the database file is not allowed. [File name = E:\App\Data\abc.sdf].

Windows form SQL Server connection string issue

I have a Windows Forms application written in C# using SQL Server 2012 Express as its database.
I need a connection string to work on any PC.
I try to put the .mdf file in DataDirectory or drive C: or C:\ProgramData
DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\mydb.mdf;Pooling=False;
In this case the error is:
Failed to update .mdf database because the database is read-only
If I try to use
user instance=True;
in the connection string, I get the following error :
System.Data.SqlClient.SqlException (0x80131904): Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
If I try to put the .mdf file in user application data AppRoaming folder it's not supported and returns error :
An attempt to attach an auto-named database for file failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
So how to set my connection string and where should the .mdf file be stored?
Please help me
And thanks in advance

Can't connect to SQL Server in visual studio 2012

I am trying to connect to an SQL server database in visual studio 2012 but having no luck. I have the following code.
var db = Database.Open("anagram_database");
var shows_data = db.Query("SELECT * FROM sorted_words");
the database name is correct without any typo's, I am receiving the following error
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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I am completely out of my depth with this and don't even know where to start. I cant seem to find anything with googling.
From the documentation:
name
Type: System.String
The name associated with the database to open. name can specify an .sdf or .mdf database file that is in the App_Data folder. (Do not include the file-name extension.) Alternatively, name can specify the name of a connection string in the Web.config file.
Here, App_Data means the logged in user's Application Data folder (or actually, the user running the application, which is probably the same). Type %APPDATA% in the address field of a Windows Explorer and press enter. The folder that opens is where you should place the anagram_database.mdf database file.

How to create a SqlServer database backup with .Net?

I want to make a database backup with this C# code:
connect = new SqlConnection(con);
connect.Open();
// Execute SQL
SqlCommand command = new SqlCommand
(
#"backup database MY_database to disk='d:\SQLBackup\wcBackUp1.bak' with init, stats=10",
connect
);
command.ExecuteNonQuery();
connect.Close();
When I run it, the following error message shows up:
Cannot open backup device 'd:\SQLBackup\wcBackUp1.bak'.
Operating system error 3(The system cannot find the path specified.).
If I change the path to d:\wcBackUp1.bak it seems to be ok, is without error, but the file does not exist, it was not generated.
If I run in SQL the command I have the message that it was 100% processed, but I didn`t see the file.
Could someone help me please?
Make sure the location "d:\SQLBackup\" exist in your database server and not on your client machine.
Two things to check.
The Sql Service may not have access to the d:\sqlbackup folder. Old Sql installs used to default to install the service with full access to the machine, but newer instances tighten that up. You could try changing the path to the directory where the default backups are stored.
Secondly, if the sql server is not on the same machine that you are running this program, then you must remember that the D: will be the D: on the sql server and not your local machine
Fundamentally, the Windows account that the SQL Server service runs under must have write permissions on the specified folder.
You can check what account this is by looking in SQL Server Configuration Manager, under SQL Server Services (look at the Log On As column)
Check what permissions that account actually has on the target folder using Explorer -> right click folder -> properties -> security -> advanced -> effective permissions.
One way to check that this is the problem is to change your code to back up to your SQL instance's backup folder, where the permissions are likely to be correct. For example
C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup

Categories

Resources