I have a website and an SQL Server database on it. The control panel of my host is Plesk 12.5. Now, I want backup my database and store it on a special folder in my host. I've added permisson to save data to this special folder in my host control panel, and the function that I use it to create and save database backup is :
string CS = "server=localhost;database = Test;uid=***; password=***;";
string filename = "testDB.bak";
string folderPath = Server.MapPath("~/Backups/");
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
using (SqlConnection con = new SqlConnection(CS))
{
string SqlStmt = String.Format("Backup Database Test To Disk = '{0}'", folderPath + filename);
using (SqlCommand cm = new SqlCommand(SqlStmt, con))
{
try
{
con.Open();
cm.ExecuteNonQuery();
con.Close();
}
catch (Exception E)
{
Label1.Text = E.Message;
return;
}
}
}
'Backups' folder is created, but for backup, get this error: "Cannot open backup device 'C:***********.com\httpdocs\Backups\testDB.bak'. Operating system error 5(Access is denied.). BACKUP DATABASE is terminating abnormally."
Related
I am working on a c# project where I need the user to open an Excel file and insert the data in an SQL server database. The problem is that using this connection string
("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;")
during the opening of the connection I get
the provider 'microsoft.ace.oledb.12.0' is not registered
exception, which is odd because I worked with an Access Database and used the same connection string. The Access Database Engine is installed on my PC and I even compiled at x86, am I missing something?
The reasons are as follows:
When accessing the .xlsx file with SQL SERVER, you must use
provider 'Microsoft.ACE.OLEDB.12.0' to implement.
First install AccessDatabaseEngine.exe.
Download path: http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
This provider can be seen in the database on 32-bit systems.
It cannot be seen in a 64-bit system, so you need to call
C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\DTExec.exe
to execute the package.
solution:
Open IIS Manager.
Right-click the connection pool where the application is located.
Modify "Enable 32 as application" to true.
The code shown below may help you.
Sqlconn sqlcon = new Sqlconn();
public Form1()
{
InitializeComponent();
}
string str_Excel_Path;
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//Only one file can be opened------------------------------------------
openFileDialog1.Filter = "Excel file|*.xlsx";//Set the open file filter
openFileDialog1.Title = "Open Excel file";//Set the title of the open file
openFileDialog1.Multiselect = true;//Allow multiple files to be selected
if (openFileDialog1.ShowDialog() == DialogResult.OK)//Determine whether a file is selected
{
str_Excel_Path = openFileDialog1.FileName.ToString();//Get the selected file address
textBox1.Text = str_Excel_Path;//Display the selected file address in textBox1
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
string[] P_str_Names = textBox1.Text.Split(',');//Store all selected Excel file names
string P_str_Name = "";//Store the traversed Excel file name
List<string> P_list_SheetNames = new List<string>();//Create a generic collection object to store sheet names
for (int i = 0; i < P_str_Names.Length; i++)//Iterate over all selected Excel file names
{
P_str_Name = P_str_Names[i];//The Excel file name traversed by the record
P_list_SheetNames = GetSheetName(P_str_Name);//Get all sheet names in the Excel file
for (int j = 0; j < P_list_SheetNames.Count; j++)//traverse all worksheets
{
/* if (ckbox_Windows.Checked)//Log in to SQL Server with Windows authentication
//Export worksheet contents to SQL Server
{
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data Source='" + txt_Server.Text + "';Initial Catalog='" + cbox_Server.Text + "';Integrated Security=True;");
}
else if (ckbox_SQL.Checked)//Log in to SQL Server with SQL Server authentication
{
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data Source='" + txt_Server.Text + "'Database='" + cbox_Server.Text + "';Uid='" + txt_Name.Text + "';Pwd='" + txt_Pwd.Text + "';");
}*/
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data source=localhost;Initial Catalog=student;User ID=sa;Password=123456");
}
}
MessageBox.Show("All selected Excel sheets have been imported into SQL Server database!", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Please select the file to be imported into the database!");
}
}
//Get all worksheet names in the Excel file
private List<string> GetSheetName(string P_str_Name)
{
List<string> P_list_SheetName = new List<string>();//Create a generic collection object
//Connect to the Excel database
//OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + P_str_Name + ";Extended Properties=Excel 8.0;");
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + P_str_Name + ";Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1;\"");
olecon.Open();//Open database connection
System.Data.DataTable DTable = olecon.GetSchema("Tables");//Create a table object
DataTableReader DTReader = new DataTableReader(DTable);//Create table read object
while (DTReader.Read())
{
string p_str_sName = DTReader["Table_Name"].ToString().Replace('$', ' ').Trim();//Record the worksheet name
if (!P_list_SheetName.Contains(p_str_sName))//Determine whether the sheet name already exists in the generic collection
P_list_SheetName.Add(p_str_sName);//Add the worksheet to the pan-collection
}
DTable = null;//Clear the table object
DTReader = null;//Clear the table read object
olecon.Close();//Close the database connection
return P_list_Sheet
}
/* Import the content of the specified worksheet in Excel into the SQL Server database */
public void ImportDataToSql(string p_str_Excel, string p_str_SheetName, string p_str_SqlCon)
{
DataSet myds = new DataSet();//Create a dataset object
try
{
// get all data
//string P_str_OledbCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + p_str_Excel + ";Extended Properties=Excel 8.0;";
string P_str_OledbCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + p_str_Excel + ";Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1;\"";
OleDbConnection oledbcon = new OleDbConnection(P_str_OledbCon);//Create an Oledb database connection object
string p_str_ExcelSql = "";//Record the Excel query statement to be executed
OleDbDataAdapter oledbda = null;//Create an Oledb data bridge object
p_str_ExcelSql = string.Format("select * from [{0}$]", p_str_SheetName);//Record the Excel query statement to be executed
oledbda = new OleDbDataAdapter(p_str_ExcelSql, P_str_OledbCon);//Execute Excel query using data bridge
oledbda.Fill(myds, p_str_SheetName);//Fill data
//Define variables to record the SQL statement that creates the table
string P_str_CreateSql = string.Format("create table {0}(", p_str_SheetName);
foreach (DataColumn c in myds.Tables[0].Columns)//traverse all rows in the dataset
{
P_str_CreateSql += string.Format("[{0}]text,", c.ColumnName);//Create a field in the table
}
P_str_CreateSql = P_str_CreateSql + ")";//Improve the SQL statement for creating a table
//Create SQL database connection object
using (SqlConnection sqlcon = new SqlConnection(p_str_SqlCon))
{
sqlcon.Open();//Open database connection
SqlCommand sqlcmd = sqlcon.CreateCommand();//Create an execution command object
sqlcmd.CommandText = P_str_CreateSql;//Specify the SQL data to be executed
sqlcmd.ExecuteNonQuery();//Execute operation
sqlcon.Close();//Close the database connection
}
using (SqlBulkCopy bcp = new SqlBulkCopy(p_str_SqlCon))//Import data with bcp
{
bcp.BatchSize = 100;//Number of rows per transfer
bcp.DestinationTableName = p_str_SheetName;//Define the destination table
bcp.WriteToServer(myds.Tables[0]);//Write data to SQL server data table
}
}
catch
{
MessageBox.Show("SQL Server database already exists" + p_str_SheetName + "Table!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Sqlconn code:
// private static string constr = "server=(local);Initial Catalog=D_total;Integrated Security=True";
private static string constr = "Data source=localhost;Initial Catalog=student;User ID=sa;Password=123456";
// private static string constr = "Data Source =192.168.1.201;Initial Catalog=D_total23 ;User Id=sa;Password=123";
public DataTable f1()
{
string A = "select name from master..sysdatabases";//Query this database information
return Only_Table1(A);
}
public DataTable Only_Table1(string exec)
{
System.Data.DataTable dt_jdl = new DataTable();
try
{
using (SqlConnection con = new SqlConnection(constr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
if (con.State == ConnectionState.Open || con.State == ConnectionState.Connecting)
{
SqlDataAdapter sda2 = new SqlDataAdapter(exec, con);//All by writing stored procedures
DataSet ds2 = new DataSet();
sda2.Fill(ds2, "cxq");
dt_jdl = ds2.Tables["cxq"];
sda2.Dispose();
ds2.Dispose();
}
con.Close();
}
return dt_jdl;
}
catch (Exception EX)
{
return null;
}
}
}
Run the project:
Click the OK button to select the xml file from the folder. Click the import button to import the file into the database.
Hi everyone i can't set a relative path to open my database, the project is structured in this mood
projectname
db/acces.db
info/try.cs
This is the code inside try.cs with which i should open the database, obviously if I put the full path it goes:
try {
using (SQLiteConnection conn = new SQLiteConnection(#"data source="db/access.db")
{
conn.Open();
using (SQLiteCommand fmd = conn.CreateCommand()){
fmd.CommandText = #"SELECT * FROM 'test';
fmd.CommandType = CommandType.Text;
SQLiteDataReader r = fmd.ExecuteReader();
while (r.Read())
Debug.Writeline("foo");
conn.Close();
}
}
catch (Exception e){
Debug.WriteLine("Errors");
}
I should take the path of the acces.db file, not complete but relative to my project, to be set in data source, how should i do?
You can use something like this:
using System.IO;
var connection = "Data Source=" + Path.Combine(Directory.GetCurrentDirectory(), "db\\access.db")
try {
using (SQLiteConnection conn = new SQLiteConnection(connection)
{
conn.Open();
using (SQLiteCommand fmd = conn.CreateCommand()){
fmd.CommandText = #"SELECT * FROM 'test';
fmd.CommandType = CommandType.Text;
SQLiteDataReader r = fmd.ExecuteReader();
while (r.Read())
Debug.Writeline("foo");
conn.Close();
}
}
catch (Exception e){
Debug.WriteLine("Errors");
}
You said you should get something of type Data Source=C:\\Users\\mypc\\Documents\\tesrepo\\Myapp\\testApp\\db\\test.db.
Here is how to get the correct path.
Project path:
Directory.GetParent(workingDirectory).Parent.FullName;
Add the path you want at the end: For example, the address of the 123.mp3 file in the music folder here is:
string filepath = Path.Combine(projectDirectory + "\\music\\123.mp3");
//Get db address
string workingDirectory = Environment.CurrentDirectory;
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;
string dbpath = Path.Combine(projectDirectory + "\\db\\test.db");
dbpath is what you want.
If you have any questions about my code, please add a comment below.
Updated:
You can import the updated file into the output directory through this operation.
Your path would work without any modification.
private void button1_Click(object sender, EventArgs e)
{
string usernames = textBox1.Text;
string passwords = textBox2.Text;
string emailid = textBox5.Text;
string telno = textBox6.Text;
string connectionstring = "Data Source=|DataDirectory|\\libdb.sdf; Persist Security Info=False ;";
using (SqlCeConnection con = new SqlCeConnection(connectionstring))
{
con.Open();
using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (#usernames,#passwords,#emailid,#telno)", con))
{
Query.Parameters.AddWithValue("#usernames", usernames);
Query.Parameters.AddWithValue("#passwords", passwords);
Query.Parameters.AddWithValue("#emailid", emailid);
Query.Parameters.AddWithValue("#telno", telno);
Query.ExecuteNonQuery();
}
MessageBox.Show("QueryExecuted");
con.Close();
MessageBox.Show("Closedconnecrion");
con.Dispose();
MessageBox.Show("disposed");
this.Close();
/*string conString = "Data Source=" +
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyAppData\\database.sdf") + ";Password=yourPassword;";
even this method dosent works */
}
}
}
on executing this code I find it executes successfully. But when I go and check the database, I find the entries empty...
I even tried refreshing database..
I didn't find problem in connectivity.
Query no error executed successfully.
The problem is I didn't find result or the data I gave as input in database.
Please be descriptive with code eg and mail to scarlet.gabriel#gmail.com
Test your connection with the database first, You can get the connection string by creating the udl file.
create a textfile and savaas it with the extension udl (example connection.udl).
double click and run this file.
a window will be opened where you can get the option for getting the connection string.
after testing the connection, close this window and open this file with a note pad.
copy the connection string and paste it in the below statement.
string connectionstring =" paste here";
How can you be sure if the connection is open and has done the job? Use try... catch block to catch if any error occurs:
using (SqlCeConnection con = new SqlCeConnection(connectionstring))
{
try{con.Open();}
catch(Exception ex)
{
// database connection error. log/display ex. > return.
}
if(con.State==ConnectionState.Open)
{
using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (#usernames,#passwords,#emailid,#telno)", con))
{
Query.Parameters.AddWithValue("#usernames", usernames);
Query.Parameters.AddWithValue("#passwords", passwords);
Query.Parameters.AddWithValue("#emailid", emailid);
Query.Parameters.AddWithValue("#telno", telno);
try{
Query.ExecuteNonQuery();
}
catch(Exception ex)
{
// database communication error. log/display ex
}
}
MessageBox.Show("QueryExecuted");
}
if(con.State==ConnectionState.Open)
{
try{con.Close();}
catch{}
}
}
Instead of using connectionstring = "Data Source=|DataDirectory|\libdb.sdf; Persist Security Info=False ;"; Please try to use absolute path like
connectionstring = "Data Source=C:\Users\chandra\Documents\Visual Studio 2010\Projects\Window\LMS\AppData\LMSDatabase.sdf;Persist Security Info=False;";
I hope this will work.
Thanks
This code copies data from access to SQL server table.
but this code has some problems.
This code can not copy data from access to SQL server table where have data.
My SQL server table has some data and I want to add data from access to under existing data in SQL server table.
How do I add data to the existing table?
Can not read data from access 2007 or 2010.
How do I read data from access 2007/2010
OpenFileDialog openfiledialog1 = new OpenFileDialog();
openfiledialog1.Title = "select access file";
openfiledialog1.Filter = "Access 2003 (*.mdb)|*.mdb|Access 2007|*.accdb";
if (openfiledialog1.ShowDialog() == DialogResult.OK)
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openfiledialog1.FileName;
const string connectionStringDest = #"server=ahmad-pc\anfd;database = phonebook;Integrated Security = true";
using (var sourceConnection = new OleDbConnection(connectionString))
{
sourceConnection.Open();
var commandSourceData = new OleDbCommand("SELECT * from numberperson", sourceConnection);
var reader = commandSourceData.ExecuteReader();
using (var destinationConnection = new SqlConnection(connectionStringDest))
{
destinationConnection.Open();
using (var bulkCopy = new SqlBulkCopy(destinationConnection))
{
bulkCopy.ColumnMappings.Add("name", "nameperson"); //THIS A MAPPING REPLACE IT WITH YOUR NEED
bulkCopy.ColumnMappings.Add("family", "family1");
bulkCopy.DestinationTableName = "profile2";
try
{
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
reader.Close();
}
}
}
MessageBox.Show("success");
}
}
SQLBulkCopy only does Bulk inserts so any existing data should not be modified.
For MS Access > 2003 you'll need to use Microsoft ACE instead of JET
When I run the application, are all forms in the app loaded/initialized even though I have not opened them yet? (I.E. Form.Show)
this is how I closed the connection in the login form:
if (usertype == "UT1") //admin rights
{
//GET LOGGED USER
Home_Admin homeAdmin = new Home_Admin();
homeAdmin.SetUsername(username);
cString.Close();
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(OpenHomeAdmin));
t.Start();
}
And how I got to the back up form from Home_Admin's menu strip
private void backUpToolStripMenuItem_Click(object sender, EventArgs e)
{
BackUp BackUpForm = new BackUp();
BackUpForm.Show();
}
I am trying to create a back up of my database and it works perfectly if I run only the back up form. If I start the app from the very beginning, it says back up failed the database is in use. I already closed the connection from login to the form where I will launch the back up form and even set a
if(conn.State = connectionState.Open)
{
conn.close();
}
prior to the back up procedure. Is there any way I can just kill all connections to the SQL database > back up > and then restore the connections?
BACK UP CODE
public void BackupDatabase(String destinationPath)
{
SqlConnection cString = new SqlConnection();
cString.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\MY_THESIS\\WORKING FILES\\NNIT-RMS.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
if (cString.State == ConnectionState.Open)
{
cString.Close();
}
try
{
//MY SERVER
String userName = "NNIT-Admin";
String password = "password";
String serverName = #"RITZEL-PC\SQLEXPRESS";
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
Backup BackupMgr = new Backup();
BackupMgr.Devices.AddDevice(destinationPath, DeviceType.File);
BackupMgr.Database = "NNIT DB";
BackupMgr.Action = BackupActionType.Database;
BackupMgr.SqlBackup(sqlServer);
MessageBox.Show("Back up saved!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " " + ex.InnerException);
}
}
FORM LOAD
private void BackUp_Load(object sender, EventArgs e)
{
string date = DateTime.Now.Day.ToString();
string year = DateTime.Now.Year.ToString();
string month = DateTime.Now.Month.ToString();
Filename_txt.Text = "NNIT-RMSDB_" + month + date + year;
}
Error message
http://img824.imageshack.us/img824/8541/error1lj.jpg
In this piece of code:
SqlConnection cString = new SqlConnection();
cString.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\MY_THESIS\\WORKING FILES\\NNIT-RMS.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
if (cString.State == ConnectionState.Open)
{
cString.Close();
}
You are instantiating a new connection and never opening it. The code in the if clause will never be hit.
Your mistake is assuming that the new connection is the only one - there may be multiple connections (opened in other forms and never properly closed) - some not even from your application (for example, using SQL Server Management Studio - having an open query window to your database will mean there is an open connection).
The best solution for to kill all connections to db is to take it offline, other solutions almost fail
using (SqlConnection sqlcnn = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=True"))
{
SqlCommand sqlcmd = new SqlCommand("ALTER DATABASE DB_NAME SET OFFLINE WITH ROLLBACK IMMEDIATE", sqlcnn);
sqlcnn.Open();
sqlcmd.ExecuteNonQuery();
sqlcnn.Close();
}
Add the above code before your backup or restore code and then your backup or restore will work even if you have open connections to your db.