I have this as my connection string property:
Data Source="c:\users\perdanny\documents\visual studio 2012\Projects\WebApplication1\WebApplication1\App_Data\Users.sdf"
Now, how should I write it in my code:
sqlConnection = new SqlConnection(???);
try this:
string strConnection = ConfigurationManager.ConnectionStrings["Name of connection string key"].ConnectionString;
// Or, for a quick test you could also use
// string strConnection = "Data Source = c:\\users\\perdanny\\documents\\visual studio 2012\\Projects\\WebApplication1\\WebApplication1\\App_Data\\Users.sdf"
using (var conn = new SqlCeConnection(string.Format("Data Source={0}", strConnection)))
{
conn.Open();
try
{
System.Data.SqlServerCe.SqlCeCommand cmd = System.Data.SqlServerCe.SqlCeCommand;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "Your sql stored proc name";
cmd.Connection = conn ;
cmd.ExecuteNonQuery();
}
catch (SqlCeException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
string connStr = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
<add name="connectionString" connectionString="Data Source=SQLEXPRESS;Initial Catalog=dbsql;User ID=hello;Password=hello"
providerName="System.Data.SqlClient" />
use ConfigurationManager and
look at below code line:
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
Related
I'm new to ASP.Net & SQL Server and have the following code:
protected void btnShowData_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=DESKTOP-RV7DDL4;Initial Catalog=Demodb
;User ID=DESKTOP-RV7DDL4\dbname;Password=test123";
cnn = new SqlConnection(connectionString);
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = "";
sql = "Select TutorialID, TutorialName from demotb";
command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
lblName.Visible = false;
txtName.Visible = false;
lstLocation.Visible = false;
chkC.Visible = false;
chkASP.Visible = false;
rdMale.Visible = false;
rdFemale.Visible = false;
btnSubmit.Visible = false;
}
When I run the project I receive the following error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed.
I thought the connection was made so not sure why it says the db is closed?
Try to to explicitly open the connection via the Open method on the SQL connection class.
Perhaps a using statement is more appropriate here. Like so:
using (var cnn = new SqlConnection(connectionString))
{
// Use the connection
}
Thanks for your help. I re-jigged things around and added the .Open method and it works!
string connectionString = null;
SqlConnection cnn;
SqlCommand command;
string sql, Output = "";
connectionString = #"Data Source=DESKTOP-RV7DDL4\SQLEXPRESS;Initial Catalog=DemoDBase
;User ID=sa;Password=test1234";
cnn = new SqlConnection(connectionString);
sql = "Select TutorialID, TutorialName from demoTable";
cnn.Open();
command = new SqlCommand(sql, cnn);
SqlDataReader dataReader;
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
my web.config is
<connectionStrings>
<add name="taraznegarConnectionString" connectionString="Data Source=.;Initial Catalog=taraznegar;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
and this is my code:
namespace taraz
{
public class DAL
{
string connection = "Data Source=.;Initial Catalog=taraznegar;Integrated Security=True";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = connection;
cmd = new SqlCommand();
cmd.Connection = con;
da = new SqlDataAdapter();
da.SelectCommand=cmd;
dt = new DataTable();
}
public DataTable ExecuteReader(string SQL)
{
connect();
da.SelectCommand.Connection = con;
da.SelectCommand.CommandText = SQL;
try
{
da.SelectCommand.ExecuteReader();
}
catch
{
da = null;
}
disconnect();
da.Fill(dt);
return dt;
}
public string ExcuteNonQuery(string SQL)
{
string result=null ;
cmd.CommandText = SQL;
connect();
try
{
cmd.ExecuteNonQuery();
}
catch { result = "خطا"; }
disconnect();
return result;
}
public string ExecuteScalare(string sql)
{
string result = null;
cmd.CommandText = sql;
connect();
try {
result = cmd.ExecuteScalar().ToString();
}
catch { result = "خطا"; }
disconnect();
return result;
}
void connect()
{
if (con.State == ConnectionState.Closed)
con.Open();
}
void disconnect()
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
}
and when I'm using this class in my project the error is:
Server Error in '/' Application.
Keyword not supported: 'server(local); database'.
what's the probleam?
When you have a ConnectionString in your webconfig file then in your application you don't need to create another connection. You should use that connection. In your class DAL you are creating a new connection string. Instead of that you should use something like this-
string connectionString = ConfigurationManager.ConnectionStrings["taraznegarConnectionString"].ConnectionString;
For Entity Framework (database-first or model-first; when you have a physical EDMX model file) you need to use a special type of connection string which is quite different from the straight ADO.NET connection strings everyone else has mentioned so far...
The connection string must look something like:
<connectionStrings>
<add name="testEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.;Initial Catalog=taraznegar;Integrated Security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Inside this connection string, you'll find the provider connection string= attribute which is basically your ADO.NET connection string:
If I have a connection string defined in my web.config file, how do I create a connection to the SQL db from C# code (sorry forgot to specify) and then call a stored procedure. I would then like to eventually use this data in some way as my DataSource for a GridView.
Here is how the connection string is defined in the web.config:
<connectionStrings>
<add name="db.Name" connectionString="Data Source=db;Initial Catalog=dbCat;User ID=userId;Password=userPass;" providerName="System.Data.SqlClient" />
</connectionStrings>
The db server is a Microsoft SQL server.
Here is what I was looking for:
ConnectionStringSettings conSet = ConfigurationManager.ConnectionStrings["db.Name"];
SqlConnection con = new SqlConnection(conSet.ConnectionString);
The code to get the data is fairly trivial. I was more interested in accessing it from a connectionString variable in the web.config file.
If it's a resource file like so:
private static readonly string connString = Resource1.connString;
Where connString is the name of the key. If it is a web.config file
Something like so:
private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["strConn"]; where conn is defined in your web config file.
<add key="strConn" value="User ID=test;Password=test;Initial Catalog=TestDB;Data Source=NameOfServer;"/>
Then call the sproc:
//connString = the string of our database app found in the resource file
using (SqlConnection con = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("EMPDLL_selClientByClientID", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ClientID", SqlDbType.VarChar).Value = cID;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
//more code
}
}
}
}
}
That's if you are coding in C#, VB.net its the same deal just a bit more wordier :), here's a small sample:
Public Sub DeleteEmployee(ByVal lVID As Long)
Dim conMyData As SqlConnection
Dim cmdDelete As SqlCommand
Try
conMyData = New SqlConnection(connString)
cmdDelete = New SqlCommand("delEmployee", conMyData)
With cmdDelete
.CommandType = CommandType.StoredProcedure
'add the parameters
.Parameters.Add("#LoginID", SqlDbType.BigInt).Value = lVID 'the request
conMyData.Open() 'open a connection
.ExecuteNonQuery() 'execute it
End With
Catch ex As Exception
Throw ex
Finally
cmdDelete = Nothing
conMyData.Close()
conMyData = Nothing
End Try
End Sub
Of course you should use a using statement instead of try/catch/finally to ensure you clean up your resources that are being used.
Something like this...
using (var con = new SqlConnection(_connectionString))
{
using (var cmd = new SqlCommand(_storedProcedureName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#pMyParamater", myParamaterValue);
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// do something with the row
}
}
}
}
This is all pretty simple stuff to be honest, you should be able to find everything you need from the ADO.NET documentation
Actually I am new in this topic so required some help.
I have added connection string in Web.Config
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
and know that, to use it I have to put this statement in my C# code behind
string connStr = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
That's all I know.
My Question is
What should I do if I want to execute some query for my aspnetdb.mdf dataabase (Built in db of ASP.NET built in login contols in Visual Studio 2010)
Earlier, I was doing this to accomplish my task
1) No connection string in Web.Config. and
2) Hard code in codebehind
SqlConnection con = new SqlConnection("data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true");
SqlCommand cmd = new SqlCommand();
protected void btnnameedit_Click(object sender, EventArgs e)
{
try
{
con.Open();
cmd.CommandText = "update tamhankarnikhil set fname = '" + fname.Text + "'";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
fname.Text = "";
}
catch (Exception a)
{
Response.Write(a.Message);
}
}
Here's what you could do:
protected void btnnameedit_Click(object sender, EventArgs e)
{
try
{
string connStr = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
using (var conn = new SqlConnection(connStr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "UPDATE tamhankarnikhil SET fname = #fname";
cmd.Parameters.AddWithValue("#fname", fname.Text);
cmd.ExecuteNonQuery();
fname.Text = "";
}
}
catch (Exception a)
{
Response.Write(a.Message);
}
}
You will notice the usage of parametrized queries to avoid SQL injection to which your code was vulnerable to due to the string concatenations you were using when constructing the SQL query.
You will also notice that the SqlConnection and SqlCommand are wrapped in using statements to ensure their proper disposal even in the event of an exception.
string ConnectionString = WebConfigurationManager.ConnectionStrings["dbnameConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(ConnectionString);
myConnection.Open();
try
{
string qry = "UPDATE customers SET firstname=#firstname WHERE cid=1";
SqlCommand insertQuery = new SqlCommand(qry, myConnection);
insertQuery.Parameters.Add(new SqlParameter("#firstname", txtFirstname.Text));
insertQuery.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ee)
{
}
Any suggestions?
A little cleanup of your code you may like to try (you should dispose IDisposable objects):
string ConnectionString = // ...
using (var connection = new SqlConnection(ConnectionString))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "UPDATE customers SET firstname = #firstname WHERE cid=1";
command.Parameters.AddWithValue("#firstname", txtFirstname.Text);
var rowsUpdated = command.ExecuteNonQuery();
}