Retrieve values from a RESTORE LABELONLY operation - c#

I want to retrieve the resulting value of the following query :
RESTORE LABELONLY FROM DISK = 'C:\folder\db-backup.bak';
After doing some search I tried:
string connection = #"data source=.\SQLExpress;initial catalog=DB;persist security info=False;user id=sa;password=12356;MultipleActiveResultSets=True;App=EntityFramework";
ExecuteSQL(connection , #"RESTORE LABELONLY FROM DISK = 'C:\folder\db-backup.bak'");
And, the ExecuteSQL is:
private void ExecuteSQL(string ConnString, string sqlText)
{
string result = "";
using (SqlConnection sqlCon = new SqlConnection(ConnString))
{
sqlCon.Open();
using (SqlCommand sqlCom = sqlCon.CreateCommand())
{
sqlCom.CommandType = CommandType.Text;
sqlCom.CommandText = sqlText;
sqlCom.CommandTimeout = 0;
try
{
string str = Convert.ToString(sqlCom.ExecuteScalar());
}
catch (Exception e)
{
result = e.Message;
}
}
}
}
BUT .. the str always empty !!
The result of the query in SQL Server Management Studio is:
What I want is how can I retrieve the MediaSetID field?

MSDN says about the RESTORE LABELONLY operations:
Result Sets
The result set from RESTORE LABELONLY consists of a single row with
this information.
MediaName nvarchar(128) Name of the media.
...
So you have to use ExecuteReader method and process the columns in the returned reader (or load it to DataTable and do the same).

You should be using ExecuteReader() instead like below since your said command returning non-scalar value. You probably getting empty string cause the first column value of the RESTORE command is NULL per your posted SSMS result image
sqlCom.ExecuteReader()

Related

How to update Oracle CLOB column with long string using C# and Oracle Data Access Client

I'm trying to update a CLOB column in my database with a long string containing the HTML contents of an email. There are 18,000 characters in the record I'm having an issue with.
The below code will work if I set the html variable to "short string". But if I try to run the code with the long 18,000 character HTML string, I get this error: "Oracle.DataAccess.Client.OracleException ORA-22922: nonexistent LOB value ORA-02063: preceding line from ((servername))"
public static void UpdateHtmlClob(string html, string taxId,string un, string pw)
{
using (OracleConnection conn = new OracleConnection())
{
try
{
conn.ConnectionString = "User Id=" + un + ";Password=" + pw + ";Data Source=server.com;";
conn.Open();
OracleCommand cmd = new OracleCommand();
string indata = html;
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
OracleParameter clobparam = new OracleParameter("clobparam", OracleDbType.Clob, indata.Length);
clobparam.Direction = ParameterDirection.Input;
clobparam.Value = indata;
cmd.Parameters.Add(clobparam);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
conn.Close();
}
}
}
Before you edited your code to reflect my answer, there were two problems with your code that I saw.
Firstly, you need to use a colon in your command text to tell Oracle that clobparam is a bind variable, not a column name:
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
Secondly, you were not setting the database connection anywhere on the command. Which connection should the command be using? In your situation you have only one connection but more generally it may be possible to have more than one connection open. Add the line
cmd.Connection = connection;
or alternatively create the command using
OracleCommand cmd = connection.CreateCommand();
Of course, it would be nice if Oracle.DataAccess returned an error message that gave you the slightest hint that this was what you were doing wrong.
Anyway, now that you've edited your question to include the critical detail ORA-02063: preceding line from ((servername)), which tells us that you are using a database link, all I can really do is echo what I wrote in the comment: connect direct to the remote database to transfer LOB data, don't use a database link.

Doesn't save added value into database

In Visual Studio (2013) I have added service-based database (Database1.mdf) in my project. I have added in it a table, and via Show Data Table added two rows. Reading data from database works as required. But there is a problem with add value to database. If I while the program is running add value to database and then press "Reading data" it's ok, the data is reading. But If I while the program is still running go to "Show Data Table" and press button "update", I get the error: "This database cannot be imported. It is either an unsupported SQL Server verison or an unsopported database compatibility".
If I press button "update" in "SQL Server Object Explorer" and then go to "Show Data Table" and press button "update", the data is updates, but no added data. Also, after the completion of the program there isn't the added data.
Why?
I have tried to change the properties "Copy To Output Directory" from "Copy always" to "Do not Copy" or "Copy if newer". But it didn't help me. Please help me
Read data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnectionString))
{
try
{
SqlCommand command = new SqlCommand("SELECT [Login] FROM [UsersTable];", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
label1.Text = "Last value: " + reader.GetString(0);
}
}
}
catch (SqlException ex)
{
}
Add data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(strConnectionString))
{
using (SqlCommand command2 = new SqlCommand())
{
command2.Connection = con2;
command2.CommandType = CommandType.Text;
command2.CommandText = "INSERT INTO [UsersTable] ([Login], [Password]) VALUES (#Login, #Password)";
command2.Parameters.AddWithValue("#Login", textLogin.Text);
command2.Parameters.AddWithValue("#Password", textPassword.Text);
try
{
con2.Open();
command2.ExecuteNonQuery();
}
catch (SqlException)
{
// error here
}
finally
{
con2.Close();
}
}
}
Update
Perhaps the example isn't clear enough for you.
private void SubmitNote(string message)
{
// Ensure parameter isn't null.
if(string.IsNullOrEmpty(message))
return;
// Our Insert Query:
string insert = #"INSERT INTO [Notes] ([Username], [Date], [Message])
VALUES (#Username, #Date, #Message);";
// Define our Connection & Command:
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
using(SqlCommand command = new SqlCommand(insert, connection))
{
// Open Connection
connection.Open();
// Define our Command (AddWithValue / Add Approach)
command.Parameters.Add("#Username", SqlDbType.VarChar, 50).Values = User.Identity.Name;
command.Parameters.AddWithValue("#Date", DateTime.Now);
command.Parameters.Add("#Message", SqlDbType.VarChar).Value = message;
// Execute Query:
command.ExecuteNonQuery();
}
}
So anytime I'd like to insert a message to the database I simply call:
SubmitNote("What is love, baby don't hurt me.");
That would execute without any issues, assuming the parameter and connection are valid. You could write an exception helper, but that is above and beyond your issue. One of the problems your potentially having is:
Parameter may be Null
An issue within your Command Text
Potential issue with your Connection String.
Based on the issue you mentioned, a value is Null which means it doesn't contain a valid value. For instance if you do:
String message = String.Empty;
SubmitNote(message);
That would fail, as message doesn't have a value. Hopefully this helps.

Retrieving SQL row and set to string

I'm somewhat new to C# - I have a connection string set in my app web.config called "ApplicationServices" Using C#, how can I write a certain SQL command that retrieves data from my database and set's it to a string that I can operate on?
Here is the full explanation.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
//Taken from MSDN
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
You can also use an ORM such as LINQ2SQL
http://codesamplez.com/database/linq-to-sql-c-sharp-tutorial
EDIT:
How to debug...
Below are some links on how to use the debugging features in visual studio.
http://msdn.microsoft.com/en-us/library/ms165053.aspx
http://msdn.microsoft.com/en-us/library/k0k771bt(v=vs.71).aspx
http://www.dotnetperls.com/debugging
If you are planning on writing a query that returns one single value, you should have a look at ExecuteScalar. See this example for a quick demo on how to retrieve a value from the database and set it to a variable:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

Values added in the GridView are not saved in the database

Here is my following code:
string csr = "connection string";
string add = "Insert INTO table (Column1,Column2,Column3) Values (#Column1,#Column2,#Column3)";
using(SqlConnection connect = new SqlConnection(csr))
{
using ( SqlCommand command = new SqlCommand(add,connect))
{
command.Parameters.AddWithValue("Column1",textbox1.text");
//and so on
connect.Open();
command.ExecuteReader();
connect.Close();
}
}
I can see the data added in the gridview but when I check the table data in c# is empty, no value added. what's wrong?
You shouldn't have the connect.Close();, the using statement will take care of that for you.
command.Parameters.AddWithValue("Column1",textbox1.text")
should be
command.Parameters.AddWithValue("Column1",textbox1.text)
Set a breakpoint and ensure your connectionstring was properly set, textbox has a value, etc...

How to properly initialize a .NET OleDbConnection object and its ConnectionString property?

This is my C# code to connect and work with an Access database.
using System.Data.OleDb;
var cb = new OleDbCommandBuilder(da);
DataRow dRow = ds1.Tables["Customer"].NewRow();
dRow[0] = textBox1.Text;
dRow[1] = textBox2.Text;
dRow[2] = textBox3.Text;
ds1.Tables["Customer"].Rows.Add(dRow);
da.Update(ds1, "Customer");
con.Close();
MessageBox.Show("Entry added");
But the line da.Update(ds1,"Customer");, throws an exception:
The ConnectionString property has not been initialized.
I'm not following your question too well, but here's some sample code that may help you figure out whatever it is that you are trying to do.
For clarity: The database is named "MyDb.accdb" and has a table named "Customer" which has two fields "Name" and "Phone". This example assumes the database lives in the same directory as the executable.
private void AddCustomer(string customerName, string customerPhone)
{
string name = customerName;
string phone = customerPhone;
// An easy way to determine the connection string to your database is to open the database from Visual Studio's 'Server Explorer'.
// Then, from Server Explorer, view the Properties of the database - in the Properties you will see the "Connection String".
// You can/should replace the arbitrary part of the path with "|DataDirectory|".
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|MyDb.accdb;Persist Security Info=True";
// Create your sql query in a string variable
string cmdText = string.Format("INSERT INTO Customer(Name, Phone) VALUES('{0}','{1}');", name, phone);
// Use the 'using' statement on your connection so that the resource is managed properly
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(connString))
{
// Here's where/how we fire off the INSERT statement
OleDbCommand cmd = new OleDbCommand(cmdText, connection);
connection.Open();
cmd.ExecuteNonQuery();
}
}

Categories