The below code is during page load event in aspx.cs file. When I load the page in chrome, it throws some error in cs file.
Stack trace error:Network related error while connecting to sql server:
protected void Page_Load(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM employee"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
listviewmain.DataBind();
}
}
}
}
Connection string in web.config file:
<add name="constr"
connectionString = "data source=.;initial catalog=[Analyst_RealEstate_WebCP];persist security info=True;user id=sa;password=pass#word1;multipleactiveresultsets=True;"
providerName="System.Data.SqlClient"/>
Sql Connection :
When I am trying to connect in sql using these credentials, I am able to login but not through web.config file
Related
I'm trying to do a DropdownList from Database using ASP.Net Web Form.
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["OraDbContext"].ConnectionString;
OracleCommand cmd = new OracleCommand("SELECT NOMPRE FROM HOPEMPL", conn); //HOPEMPL#HQ
OracleDataAdapter oda = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
oda.Fill(ds);
DDnompre.DataSource = ds;
DDnompre.DataTextField = "NOMPRE";
DDnompre.DataValueField = "NOMPRE";
DDnompre.DataBind();
}
Connection String:
<connectionStrings>
<add name="OraDbContext" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="DATA SOURCE=localhost:1521/xe;DBA PRIVILEGE=;PASSWORD=1234;USER ID=LOUG"" providerName="System.Data.EntityClient" />
</connectionStrings>
Error:
"System.ArgumentException : ''metadata' is not a valid connection
string attribute' "
I'm also working with a database first (EF)
try with :
<add name="{ConnectionName}"
connectionString="Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;"
providerName="Oracle.DataAccess.Client"/>
I am struggling with my new website which I recently uploaded on Godaddy server.
Con.open() is the line which is causing error : The wait operation timed out
My Code: file.aspx.cs
SqlConnection con = new SqlConnection(#"Data Source=databaseserverurl;Network Library=DBMSSOCN;Initial Catalog=mydatabase;User ID=something;Password=something;");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (con.State != ConnectionState.Open) {
con.Open();
}
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from mytable";
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
For MySQL
You should use MySqlConnection, not SqlConnection.
For SQL Server
Most likely your databaseserverurl is wrong. Make sure your connection string corresponds to the one you have in the control panel. See https://de.godaddy.com/help/find-your-connection-strings-3323.
To ensure, open Sql Server Management Tool (or your favorite sql tool) and login your db with same server, user and password.
I tried to run this code but it raise an error at con.Open() method
"System.ComponentModel.Win32Exception: The network path was not found"
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = "server = (localdb)\v11.0 ; database = DepartmentsAndEmployees ; integrated security=true";
SqlConnection conn = new SqlConnection(cs);
SqlCommand com = new SqlCommand("select * from Employees", conn);
conn.Open();
GridView1.DataSource = com.ExecuteReader();
GridView1.DataBind();
conn.Close();
}
}
This is because it can not find the server. There is something wrong with your connection string.
Try this connection string builder:
http://www.developerfusion.com/tools/sql-connection-string/
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
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.
My connection string is placed in web.config as follows.
<connectionStrings>
<add name="empcon" connectionString="Persist Security Info=False;User ID=sa;Password=abc;Initial Catalog=db5pmto8pm;Data Source=SOWMYA-3BBF60D0\SOWMYA" />
</connectionStrings>
and the code of program is...
public partial class empoperations : System.Web.UI.Page
{
string constr = null;
protected void Page_Load(object sender, EventArgs e)
{
ConfigurationManager.ConnectionStrings["empcon"].ToString();
if (!this.IsPostBack)
{
fillemps();
}
}
public void fillemps()
{
dlstemps.Items.Clear();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["empcon"].ConnectionString);
con.ConnectionString = constr;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from emp";
cmd.Connection = con;
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem lt = new ListItem();
lt.Text = reader["ename"].ToString();
lt.Value = reader["empno"].ToString();
dlstemps.Items.Add(lt);
}
reader.Close();
}
catch (Exception er)
{
lblerror.Text = er.Message;
}
finally
{
con.Close();
}
i am totally new to programing....
i am able to run this application with er.message in label control as "the connection string property has not been initialized"
i need to retrieve the list of names of employees from the emp table in database into the dropdownlist and show them to the user...
can any one please fix it...
Where are you initializing your constr variable? It looks like you can leave that line out.
Also: just use using
using(SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["empcon"].ConnectionString)
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
//Rest of your code here
}
}
Side note: Don't use Select * From. Call out your columns: Select empname, empno From...
You are not assigning ConfigurationManager.ConnectionStrings["empcon"].ToString(); to string constr
protected void Page_Load(object sender, EventArgs e)
{
constr = ConfigurationManager.ConnectionStrings["empcon"].ToString();
...
will probably solve your problem for the time being.