I have Database file .mdf which is installed with setup where application installed.
All database operation Insert,Update delete works fine but only problem arise in back up.
Now i want to make back up of attached mdf file to application installed path when i click on backup button.
Following is my connection string.
<add name="MyConstring" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Database=Database;Integrated Security=True;User Instance=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
Code which create back up.
string serverName = "";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ToString();
string server = builder.DataSource;
string attachDBFilename = builder.AttachDBFilename;
string DatabaseName = "[" + builder.InitialCatalog + "]";
string SQLBackUp = #"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + #"d:\Data\" + "Aa.bak" + #"'";
string svr = "Server=" + server + ";Database=master;Integrated Security=True";
SqlConnection cnBk = new SqlConnection(svr);
SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);
cnBk.Open();
cmdBkUp.ExecuteNonQuery();
Above code give following error only if i use database file attached.
But is gives error
"Database does not exist"
Your database service engine account must have access to that physical file. As error suggest it's a operating system error. So You need to give proper permission on that folder or file.
See following link.
http://dbamohsin.wordpress.com/2009/06/03/attaching-database-unable-to-open-physical-file-access-is-denied/
Write click on folder and goto security and give proper permission to the data folder so that your SQL server user can access that folder.
Related
I have to send my C# Windows Forms project (using SQL Server LocalDB on vs server explorer) to my teacher but if I send her my project with localDB as my database, it doesn't work on her system. What should I do? I really appreciate it if someone helps me.
You can send your database script to your teacher. You can do for Microsoft Sql Server like that:
Right click on your db > Tasks > Generate Scripts... > next > next > Advanced > You should change "Types of data to script" area as "Schema and data". > Click "Open in new query window" radio button. > next > next > finish.
After this process, you can save this script file and send to your teacher.
I have experienced the same scenario. I just did in this manner,
Create a database on SQL Server Management Studio and add all the tables and funcs to it
Just copy and paste the created database from C:\Program Files\Microsoft SQL Server\MSSQLSERVER\MSSQL\DATA\YourDatabase.mdf and YourDatabase_Log.ldf files to your debug folder.
Lastly, Change your SQLConnection String to connect the database on the location of the CurrentFolder which of format,
Connection String
string path = Path.GetFullPath(Environment.CurrentDirectory);
string databaseName = "YourDatabaseName.mdf";
string fullpath = path + #"\" + databaseName;
if (File.Exists(fullpath))
{
SqlConnection con = new SqlConnection(#"Data
Source(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + path + #"\" + databaseName +
"");
return con;
}
else
{
throw new Exception("Database Not Found :(");
}
Im receiving a MySqlException was unhandled on a line: conn.Open();
MySqlConnection conn = new MySqlConnection("host=fdb5.freehostingeu.com;user=1477630_one;password=******;database=1477630_one;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM users WHERE name = '"+name+"'AND surname = '"+ surname +"';");
cmd.Connection = conn;
conn.Open();
I think the format of my connection string is wrong. and I've tried altering the values to see whether it's the problem but I'm still unable to connect.
what am I doing wrong?
According to their live support, they do not offer Remote Connection to MySQL on the free packages.
ConnectionStrings.com shows this as the correct standard format:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Adjusting yours accordingly:
Server=fdb5.freehostingeu.com;Uid=1477630_one;Pwd=******;database=1477630_one;
See this other answer if you need to allow remote connections to MySQL.
Shared web hosts almost never allow remote access to shared resources such as MySQL. What you will need to do is install a copy of MySQL in your local environment to do you development and testing. Then push your schema out through whatever tools they provide to you - these are usually web based. Then when you push your site to the shared host you the connection string you are using should work fine.
1) Be sure to add a reference to MySQL.Data
2) Include using MySql.Data.MySqlClient
3) Your connection string should be formatted as such:
connectionString = "SERVER=" + yourserver + ";" + "DATABASE=" + databasename + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
4) Do a try-catch statement to catch the errors
I am create a database utility and I seem to not be able to get my connectionstring correct.
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|ConfigurationData.mdf;";
I believe this is in the correct format. As for the data source, my sql server is SQLExpress which runs sql server 2008 R2. My database is named ConfigurationData. Am I missing something?
When I run it, it opens the database - I assume it does since it does not through exception - but when I try inserting into a table, it does not actually insert it yet it executes the command.
conn.Open();
try
{
SqlCommand comm = new SqlCommand("INSERT INTO Test " + "(id,number) " + " VALUES(" + 10 + " , " + 12 + ")", conn);
comm.ExecuteNonQuery();
Console.WriteLine("Database is created successfully", "MyProgram");
}
catch (Exception ex)
{
}
finally
{
if ((conn.State == ConnectionState.Open))
{
conn.Close();
}
}
EDIT
Just remembered that I had answered a similar question a while back. Check it out:
Why can't I insert data into local database (SQL Compact Edition) with C#?
I don't think it is the connection string issue. But for your reference, a good site to refer to is http://www.connectionstrings.com/sql-server-2008/
You would need one of these:
Attach a database file, located in the data directory, on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;
Trusted_Connection=Yes;
Attach a database file on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;
Trusted_Connection=Yes;
Using an User Instance on a local SQL Server Express instance
The User Instance functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL
Server instance to a user with limited administrative rights on the computer.
Data Source=.\SQLExpress;Integrated Security=true;
AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;
To use the User Instance functionality you need to enable it on the SQL Server. This is done by executing the following command: sp_configure 'user instances enabled', '1'. To disable the functionality execute sp_configure 'user instances enabled', '0'.
try (local) instead of dot, dot is not recognized in Win XP
conn.ConnectionString =
"Data Source=(local)\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|ConfigurationData.mdf;";
You're SQL Statement isn't right also, and you should use parameters, but here is what you should have
SqlCommand comm = new SqlCommand("INSERT INTO Test (id, number) VALUES('" + 10 + " ', '" + 12 + "')", conn);
Why not just use the SqlConnectionStringBuilder class?:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = #"(local)\SQLExpress";
builder.UserInstance = true;
builder.IntegratedSecurity = true;
builder.AttachDBFilename = "|DataDirectory|ConfigurationData.mdf";
SqlConnection conn = new SqlConnection(builder.ConnectionString());
The output:
"Data Source=(local)\\SQLExpress;AttachDbFilename=|DataDirectory|ConfigurationData.mdf;Integrated Security=True;User Instance=True"
One of the way to do this is to add your connection string in web.config file as shown below:
Jus click on the properties of database on the database explorer. There you will find connectionstring in its properties. Jus add it in connectionstring below.
<configuration>
<connectionStrings>
<add name="ConnectionName" connectionString="your connection string" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Then in the page you can store it in string or directly refer to your connection as shown below:
Connection con=new SqlConnection();
con.ConnectionString=ConfigurationManager.ConnectionStrings["connString"].ToString();
and I suspect your insert statement is not properly declared.
Just try this:
SqlCommand comm = new SqlCommand("INSERT INTO Test (id,number) VALUES('10' ,'12')", con);
That's all from my part... Hope it helped you..
I use the code bellow to connect to my database on my website:
string tempstr = "Data Source=" + "72.55.---.---" + ";Initial Catalog=-------;Integrated Security=False;Persist Security Info=True;User ID=" + "MYUSER" + ";Password=" + "MYPASS";
SqlConnection con = new SqlConnection(tempstr);
con.Open();
Is it secure enough ? or someone who is not professional hacker can capture the username and the password which is sent from his/her computer to my database !?
thanks in advance.
Strings like the above will be stored in plain text in the executable.
If the "attacker" has access to the DLL, it is a simple thing to dump all the strings contained in it - including the connection string.
If you want to secure the connection string, a common practice is to store it in the connectionStrings section of the application .config file and encrypt it.
I have a problem with inserting to my SQL CE Database.
I have wrote some code, then when I needed a DB, I have right clicked on projected, added new item, Local Database, after that it offered me to choose a datamodel - I selected 'dataset'.
This has created a DB for me, under Server Explorer on my left, and same .sdf file is seen on my right, in solution explorer.
I start my application, I run an insert query, it gives me output that insert was successful, I see that .sdf file under root/bin/Debug/db.sdf was just modified, I close my application, but my original database located at /root/db.sdf. If I query DB from Server explorer, I see no changes/inserted rows. Here is the code I use:
First I have tried sever Data Source options, all uncommented ones did not work for me.
//String connectString = #"Data Source=" + '"' + #"C:\Users\Alex\Documents\Visual Studio 2012\Projects\my\my\myDB.sdf;" + '"';
//String connectString = "Data Source:=" + '"' + #"C:\Users\Alex\Documents\Visual Studio 2012\Projects\my\my\my.sdf" + '"';
//String connectString = "Data Source:=C:\\Users\\Alex\\Documents\\Visual Studio 2012\\Projects\\my\\my\\my.sdf";
//String connectString =#"Data Source:=C:\Users\Alex\Documents\Visual Studio 2012\Projects\my\my\myDB.sdf";
String connectString = "Data Source=myDB.sdf";
using (SqlCeConnection connection = new SqlCeConnection(connectString))
{
connection.Open();
String query = "Insert into items (id, title) VALUES ('" + ID + "', '" + title + "');
SqlCeCommand cmd = new SqlCeCommand(string.Format(query), connection);
int result = cmd.ExecuteNonQuery();
}
After closing application I do a right click on the items table, and 'show table data' - no inserts. What am I doing wrong?
Visual studio is probably creating a copy of your original solution item into the bin/Debug sub-folder (on every build). The original file is never touched while executing your code and your changes are possibly discarded the next time you build the application.
So depending on your use-case you either have to open the database in bin/Debug for viwewing the data or change your connection string to use the one located in the root of your project/solution.
You have a copy of the database in your bin/debug folder, that contains correct data - enter a full path to the database file in your connection string to avoid confusion