Backup a database - c#

I want to backup my DB but I got a error:
ConnectionStrings cannot be used like a method
How can I resolve this?
string strCon = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
string sSQL = "BACKUP DATABASE Database TO DISK = 'D:\\Database.bak';";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.Connectionstrings(strCon).ConnectionString))
{
SqlCommand command = new SqlCommand(sSQL, connection);
connection.Open();
command.ExecuteNonQuery();
}

You should directly use that variable as SqlConnection requires a string object containing a connection string and you are storing it in a string object itself.
So it would be simply like this:
using (SqlConnection connection = new SqlConnection(strCon))
{
SqlCommand command = new SqlCommand(sSQL, connection);
connection.Open();
command.ExecuteNonQuery();
}
Recommended: (to store it in Web.config)
<connectionStrings>
<add name="job" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Then access it like this: (using System.Configuration;)
ConfigurationManager.ConnectionStrings["job"].ConnectionString

ConnectionStrings is a collection. It must be used like:
ConfigurationManager.Connectionstrings[0].ConnectionString

Related

ConnectString didn't work in C#

public static DataSet ParseDatabaseData(string sheetName)
{
string connectionString = "Provider=System.Data.SqlClient;Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;";
SqlConnection conn = new SqlConnection(connectionString);
string strSQL = "SELECT * FROM [" + sheetName + "$]";
SqlCommand cmd = new SqlCommand(strSQL, conn);
conn.Open();
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataset);
conn.Close();
return dataset;
}
The error show that 'provider' keyword is wrong.
Please help me to correct how to connect with Database through connection string?
You do not need to specify the Provider in the Connection String.
Try it like this:
public static DataSet ParseDatabaseData(string sheetName)
{
string connectionString = "Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;";
Instead of mentioning the connection string in the individual file itself, you can place the connection string in the web.config or app.config and use the config where ever required.
Sample for web.config place the connection string under the <configuration>, there you can provide the provider name:
<configuration>
<connectionStrings>
<add name="ConnString"
connectionString="Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and inside the file
public static DataSet ParseDatabaseData(string sheetName)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
Note: add using System.Configuration; for the ConfigurationManager.

Oracle DB connection with c# failed

I've installed Oracle DB on another pc(A) and trying to establish the connection from my pc(B). Now when I'm trying to debug the application I get this error- "[DBNETLIB][ConnectionOpen (ParseConnectParams()).]Invalid connection."
public void InsertionTest()
{
string cmdText = #"Insert into O_TEST_TABLE (ID,Name,MOBILE) Values (4, 'rD','798984');";
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["HR"].ConnectionString;
using (OleDbConnection con = new OleDbConnection(ConnectionString))// "Provider=SQLOLEDB; DATA SOURCE=172.16.1.220:1521/orcl;PASSWORD=hr;PERSIST SECURITY INFO=True;USER ID=hr"))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
{
Console.WriteLine("Failed!!!");
}
else
{
Console.WriteLine("Success.");
}
}
}
In my web config file, the connection string is-
<connectionStrings>
<add name="HR" connectionString="Provider=SQLOLEDB;Initial Catalog=HR;DATA SOURCE=172.16.1.13:1521/orcl;PASSWORD=hr;PERSIST SECURITY INFO=True;USER ID=hr; OLEDB.NET=True " />
</connectionStrings>
I feel provider should be Provider=OraOLEDB.Oracle

Connection String with WCF and deployment

I have an WCF service in Visual Studio. The WCF Service must simply write to a database name Market.mdf. What I have done to write to a database is:
string connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|/Market.mdf';Integrated Security=True";
using(SqlConnection connection =new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Table (Value) VALUES (#Value);");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Value", "Jonathan");
connection.Open();
cmd.ExecuteNonQuery();
}
This does not allow me to write to the database when I attempt via localhost:58632/UserManagement.svc/write. When I use this I get.
I don't know how to fix this as I am new to C# and WCF. How would the connection string differ if I was going to deploy on to IIS?
You have an unescaped sequence in your connection string
string connectionString = #"Data Source=(LocalDB)\v11.0;
AttachDbFilename='|DataDirectory|/Market.mdf';
Integrated Security=True";
Add the character # before the connectionstring to get a verbatim literal string or double the backslashes
string connectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename='|DataDirectory|/Market.mdf';Integrated Security=True";

Not able to connect to database with connection string in app.config

DataSet ds = new DataSet("Transactions");
using (SqlConnection conn = new SqlConnection("myConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("[dbo].[GetFullTransactionList]", conn);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
return ds;
Relevant content of app.config:
<configuration>
<connectionStrings>
<add name="myConnectionString"
connectionString="Data Source=LAPTOP-LT;Initial Catalog=myDb;User ID=sa;Password=abc"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
I'm getting this exception:
Format of the initialization string does not conform to specification
starting at index 0. Description: An unhandled exception occurred
during the execution of the current web request. Please review the
stack trace for more information about the error and where it
originated in the code.
Exception Details: System.ArgumentException: Format of the
initialization string does not conform to specification starting at
index 0.
Source Error:
Line 44: DataSet ds = new DataSet("Transactions");
Line 45: using (SqlConnection conn = new SqlConnection("myConnectionString"))
The correct way to refer a connection string in the app.config is:
string cnnString = ConfigurationManager.ConnectionStrings["yourCnnString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(cnnString))
{
}
do not forget the final property ConnectionString
To use connection string from config file, you need to access it ConfigurationManager.
So it will be:
using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"]))
{
...
}
Refer to documentation to get more info
SqlConnection expect a real connection string not the key from app.config. Try to read it with
ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString

How to get server name and database from config file

I have a connection string in my config file and i am using it in my code as follows -
SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString);
I need to get the server name and the database from this and pass it as a parameter to my stored proc.
I am trying to get it as below but it is failing.
SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString);
SqlConnectionStringBuilder conbuilder = new SqlConnectionStringBuilder();
conbuilder.ConnectionString = sqlconn.ToString();
string server = conbuilder.DataSource;
string database = conbuilder.InitialCatalog;
Please help me get the database and server name from my config file
Your not assigning the connection string property correctly, try:
builder.ConnectionString = ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString;
Or initialize your SqlConnectionStringBuilder class with the connection string e.g.
var conBuilder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString);
Try Following:
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder.ConnectionString = sqlconn.ConnectionString;
string server = builder.DataSource;
string database = builder.InitialCatalog;
i recommend that you store your connection string in your web.config than take it as it is, rather than build it
in web.config
<add name="connStr" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=dbtest; Integrated Security=SSPI" />
in the cs file
string connectionString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();

Categories