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();
Related
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.
Hello i am a beginner in C# winform,
I have to connect multiple users (400 different users) through a login form ( textbox : name - password) to a single sql database with Winform C#, all users are sql users created in the database and have roles like users or admin.
I have been looking for an easy way of doing this with entity framework but couldn't find anyhting.. anyone has an idea how this can be done ?
Thanks for your help.
Does every user need their own login to the database?
If this is true you would need to write a special connection string, something like below:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=" + UserName + ";"
"Password=" + Password + ";";
conn.Open();
Put this in a class that accepts the username and password.
Full example:
class myConnection
{
public static SqlConnection GetConnection(string UserName, string Password)
{
string str = "Data Source=ServerName;Initial Catalog=DataBaseName;User id=" + UserName + ";Password=" + Password + ";";
SQlConnection con = new SqlConnection(str);
con.Open();
return con;
}
}
User credentials are specified in the connection string, so you need to build a connection string with the data provided by the user in the login form.
var sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = "ServerName";
sqlBuilder.InitialCatalog = "DatabaseName";
sqlBuilder.UserID = "USERNAME";
sqlBuilder.Password = "PASSWORD";
sqlBuilder.IntegratedSecurity = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
var entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
And then use this connection string to initialize your DbContext
var context = new DbContext(entityBuilder.ConnectionString);
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";
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
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