I have an c# winforms application (.net 2 framework).
I need to backup data bases from my application.
I am trying to do this by executing an SqlCommand asynchronously.
The code is executed with no exceptions but I dont get the .bak file in my destination...
this is the code :
#region backup DB using T-SQL command
string connString = "Data Source=" + ConfigurationManager.AppSettings.Get("localhost_SQLEXPRESS") + ";Initial Catalog=" + db + ";UserID=" + ConfigurationManager.AppSettings.Get("user") + ";Password=" + ConfigurationManager.AppSettings.Get("password");
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connString);
builder.AsynchronousProcessing = true;
using (SqlConnection sqlConnection1 = new SqlConnection(builder.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE " + db + " TO DISK=" + location + "\\" + ConfigurationManager.AppSettings.Get("DataBaseBackupsFolderName") + "\\" + db + ".bak'", sqlConnection1))
{
sqlConnection1.Open();
IAsyncResult result = cmd.BeginExecuteNonQuery();
while (!result.IsCompleted)
{
Thread.Sleep(100);
}
}
}
#endregion
In your SQL backup line you seem to be missing a single quote at the beginning of the path to the backup file.
using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE " + db + " TO DISK='" + location + "\\" + ConfigurationManager.AppSettings.Get("DataBaseBackupsFolderName") + "\\" +db + ".bak'", sqlConnection1))
Two advices to try to isolate the problem:
1) Get the resulting string (the one you are executing on the SqlCommand and run it manually on SQL Server to make sure the backup commnad is correct.
2) Try a synchronous command with a regular ExecuteNonQuery to see if you are getting a SQL Server exception
You should call EndExecuteNonQuery() on your SqlCommand instance in order to throw any eventual exception and thus understand what is wrong with your SQL statements:
IAsyncResult result = cmd.BeginExecuteNonQuery();
// Wait for the command to complete
result.AsyncWaitHandle.WaitOne();
// End the execution and throw any eventual exception
cmd.EndExecuteNonQuery(result);
As you can see, I have also replaced your original Thread.Sleep() cycle block with a more effective wait on the wait handle of the command.
Quoting MSDN:
For each call to BeginOperationName, the application should also call
EndOperationName to get the results of the operation.
Related
I am creating a Smart Device project using VS2008 for a WIndows CE 6.0 device with .Net Compact Framework 3.5
Here is my code:
string queryString = "SELECT id, name, insert_date, activity FROM dbo.[my Table]";
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection connection = new SqlConnection("Data Source=dba;Initial Catalog=myDb;Persist Security Info=True;User ID=usern;Password=paswd"))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
//command.Connection.Open();
//command.ExecuteNonQuery();
}
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Debug.WriteLine(errorMessages.ToString());
}
}
Mind that usernames ant table names are changed but I am getting the following errors on command.Connection.Open();
Index #0
Message: Invalid connection.
LineNumber: 0
Source: .Net SqlClient Data Provider
Procedure: ConnectionOpen (Invalid Instance()).
Why and how to fix it? The device easly pings the server machine if that is useful.
at place of command.Connection.Open();
use connection.open()
and after execute query
close the connection...
Yes, open the connection prior to creating the command object, you will not need to close the connection because it is inside the using{}
I have gone through several posts regarding this query but neither solution works for me.
Here is my code snippet:
DBConnector connector = new DBConnector();
MySqlConnection connection = connector.GetConnection();
string select_column = QORTrackingToolLibConstants.DeviationTypeID + "," + QORTrackingToolLibConstants.DeviationTableID;
string table_name = QORTrackingToolLibConstants.DeviationNorm;
string c_name1 = QORTrackingToolLibConstants.MetricID;
string c_name2 = QORTrackingToolLibConstants.TestcaseID;
string c_name3 = QORTrackingToolLibConstants.InactiveBuildInfo;
string testCaseQry = "SELECT " + select_column + " FROM " + table_name + " where " + c_name1 + " = " + testcaseID + " AND " + c_name2 + " = " + metricID + " AND " + c_name3 + " = null;";
int total_rows_returned = 0;
int DeviationTypeID = -1;
int DeviationTableID = -1;
using (MySqlCommand command = new MySqlCommand(testCaseQry, connection))
{
# Issue in this reader command.
using (MySqlDataReader oReader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while (oReader.Read())
{
++total_rows_returned;
DeviationTypeID = (int)oReader[QORTrackingToolLibConstants.DeviationTypeID];
DeviationTableID = (int)oReader[QORTrackingToolLibConstants.DeviationTableID];
}
}
}
Please let me know if any more information is needed.
You should not try to do your own connection pooling by creating a global connection. That is most likely the cause of your problem.
http://dev.mysql.com/doc/connector-net/en/connector-net-programming-connection-pooling.html
Connection pooling works by keeping the native connection to the
server live when the client disposes of a MySqlConnection.
Subsequently, if a new MySqlConnection object is opened, it will be
created from the connection pool, rather than creating a new native
connection. This improves performance.
To work as designed, it is best to let the connection pooling system
manage all connections. Do not create a globally accessible instance
of MySqlConnection and then manually open and close it. This
interferes with the way the pooling works and can lead to
unpredictable results or even exceptions.
Although you say your app is single threaded, unless it is a very simple console app, it may very well be multi-threadded without you realizing it. If two threads hit your while loop with the same global connection, you'll get the exception you're getting.
I'm using following code to restore a BAK file to an MDF file, initially I create a database and then try to restore it using my BAK file, but I get some errors:
I use an open file dialog to select my BAK file
openDialogConvert.ShowDialog();
RegistryKey rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server");
String[] instances = (String[])rk.GetValue("InstalledInstances");
string sqlname = "";
if (instances.Length > 0)
{
foreach (String element in instances)
{
if (element == "MSSQLSERVER")
sqlname = System.Environment.MachineName;
else
sqlname = System.Environment.MachineName + #"\" + element;
}
}
String str;
SqlConnection myConn = new SqlConnection("Server=" + sqlname + ";Integrated security=SSPI;database=master");
string dbname = "tmpDB" + DateTime.Now.Ticks.ToString();
str = "CREATE DATABASE " + dbname + " ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = '" + Environment.CurrentDirectory + "\\" + dbname + ".mdf') " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = '" + Environment.CurrentDirectory + "\\" + dbname + ".ldf') ";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
myCommand.Dispose();
str = #"RESTORE DATABASE [" + dbname + "] FROM DISK = N'" + openDialogConvert.FileName + #"' WITH MOVE N'IODB_Data'
TO N'" + Environment.CurrentDirectory + #"\\" + dbname + #".mdf', MOVE N'IODB_Log'
TO N'" + Environment.CurrentDirectory + #"\\" + dbname + #".ldf', REPLACE ";
myCommand = new SqlCommand(str, myConn);
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConn.Close();
my new (empty) database is created successfully but I get strange errors while trying to restore the BAK file in this newly created database.
I get following error using the above code:
The operating system returned the error '32(failed to retrieve text
for this error. Reason: 15105)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.mdf'.
File 'IODB_Data' cannot be restored to 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.mdf'. Use
WITH MOVE to identify a valid location for the file.
The operating system returned the error '32(failed to retrieve text
for this error. Reason: 15105)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.ldf'.
File 'IODB_Log' cannot be restored to 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.ldf'. Use
WITH MOVE to identify a valid location for the file.
Problems were identified while planning for the RESTORE statement. Previous messages provide details.
RESTORE DATABASE is terminating abnormally.
but when I insert a 'GO' at the end my command, I get following error:
Incorrect syntax near GO
what is going wrong here?
of course I've tested the restore operation successfully with SQL server management studio and I've found correct logical names for my BAK file (in fact I've copied the script from MSSMS)
You can also try this.
Step 1 - connect the database server using MS SQL Server Management
Studio.
step 2 - Find the database in the left pane & right-click to choose
the restore option.
Step 3 - Choose the destination and source for restoration.
Step 4 - Browse for the backup file from the device & click on ok
Step 5 - Select the database you want to restore from the list and
click ok.
After completing the restore process, your database will be ready to use.
Note: You must create a new database to restore the old one.
I've got an ado.net code listing:
OleDbConnection oconn = new OleDbConnection();
// oconn.ConnectionString ="Driver={Microsoft Visual FoxPro Driver};Provider=vfpoledb.1;SourceType=DBF;SourceDB=" + pelna_sciezka + ";Exclusive=No; Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
oconn.ConnectionString = "Provider=vfpoledb.1;Data Source=" + pelna_sciezka + ";Collating Sequence=machine";
oconn.Open();
OleDbCommand ocmd = oconn.CreateCommand();
string na = TBNazwaKonta.Text.Replace("\n","");
na = na.Replace("\r","") ;
string ks2 = ks.Replace("\n","");
ks2 = ks2.Replace("\r", "");
OleDbCommand dbCmdNull = oconn.CreateCommand();
dbCmdNull.CommandText = "SET NULL OFF";
dbCmdNull.ExecuteNonQuery();
string zapytanie = #"insert into " + #pelna_sciezka + #" (rk, Na,Ks) values (0,'" + na + "','" + ks2 +"')";
ocmd.CommandText = zapytanie;
ocmd.ExecuteNonQuery();
oconn.Close();
It's working well without any problems. But the dbf file which I using is using by another program. Why if I execute query and close connection the dbf file is still holding by program? If someone want to open it, the error message is 'file access denied'. Only if I close application, the another can get access
You are not closing your OleDbCommands. Contrary to SqlCommands, where this is de facto optional, this does make a difference for OleDb.
I recommend to use the using keyword; this ensures that all resources are released automatically at the end of the block. As an additional bonus, it ensures that the resources are also released if an exception occurs and, thus, your manual Close command would never be reached.
using (OleDbConnection oconn = new OleDbConnection()) {
oconn.ConnectionString = "Provider=vfpoledb.1;Data Source=" + pelna_sciezka + ";Collating Sequence=machine";
oconn.Open();
using (OleDbCommand ocmd = oconn.CreateCommand()) {
string na = TBNazwaKonta.Text.Replace("\n","");
na = na.Replace("\r","") ;
string ks2 = ks.Replace("\n","");
ks2 = ks2.Replace("\r", "");
using (OleDbCommand dbCmdNull = oconn.CreateCommand()) {
dbCmdNull.CommandText = "SET NULL OFF";
dbCmdNull.ExecuteNonQuery();
} // closes dbCmdNull
string zapytanie = #"insert into " + #pelna_sciezka + #" (rk, Na,Ks) values (0,'" + na + "','" + ks2 +"')";
ocmd.CommandText = zapytanie;
ocmd.ExecuteNonQuery();
} // closes ocmd
} // closes connection
I've solved my problem, there were two points that I performed:
- I've changed all ado.net code for that like Heinzi has written
- I've used the information from support.microsoft.com/kb/260856
and followed them, the problem has now disappeared. Thank you all for help!
I keep getting this error:
Invalid object name "CAccounts".
and the code I have is:
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
// Set ConnectionString.
String sConSg =
"CONNSTRING HERE";
using (SqlConnection connection = new SqlConnection(sConSg))
{
try
{
connection.Open();
}
catch (Exception exception)
{
MessageBox.Show(stat.Text = exception.Message);
}
try
{
SqlDataReader slrr = null;
SqlCommand command = new SqlCommand("SELECT ActivationCode FROM CAccounts WHERE ActivationCode = " +
"'" + _activationcode.Text + "'", connection);
slrr = command.ExecuteReader();
while (slrr.Read())
{
if (slrr["ActivationCode"].ToString() == _activationcode.Text)
{
MessageBox.Show(slrr["ActivationCode"].ToString(), "AutoOptimise");
}
else
{
}
}
}
catch (Exception exception)
{
MessageBox.Show(stat.Text = exception.Message);
}
}
});
thread.Start();
Can somebody please shed some light?
The table CAccounts you're referencing in your select clause probably doesn't exist in the database. Check that.
See a list of possibilities here:
http://web.archive.org/web/20150519073601/http://sqlserver2000.databases.aspfaq.com:80/why-do-i-get-object-could-not-be-found-or-invalid-object-name.html
I'd suggest these things:
check which schema the object CAccounts is under. Is it dbo or other? Does the user have permissions on that schema?
login to SQL Server via Management Studio. Use the credentials in the connection string that the code is using. Paste & run the SQL statement above.
use SQL Profiler to capture/verify ensure the SQL statement as it crosses to your SQL Server. Run THAT as an adhoc query against that SQL Server.
are there any funny DNS issues? Hosts files? Does this happen during debugging or on the app server?
is the database server name correct? i.e. localhost versus a named server. Try addressing by the IP address that you expect it to be run at, just for fun, both in your connection string, and via SSMS.
Instead of CAccounts, I had to label it DATABASENAME.dbo.CAccounts.
So it would be something like:
"SELECT * FROM DATABASENAME.db.CAccounts"
This might work:
SqlConnection con = new SqlConnection("Data Source=192.168.1.12;Initial Catalog=Ibrahim;User ID=sa;Password=1412;");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Ibrahim.EVC_Activation_Val (Date,Dealer,Transaction_ID,Invoice_ID,Mobile_Num,Quantity_LE) values('" + DateTimePicker1.Value.ToString("yyyy/mm/dd") + "','" + Txtbx1.Text + "','" + Txtbx2.Text + "','" + Txtbx3.Text + "','" + Txtbx4.Text + "','" + Txtbx5.Text + "')",con);
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
con.Close();