The Problem is: in Con.Open();
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
protected void btnSubmit_Click1(object sender, EventArgs e)
{
string Name = txtUsername.Text;
string Pass = txtPass.Text;
string Email = txtEmail.Text;
ConnectionStringSettings settings;
settings = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"];
string connectionString = settings.ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("INSERT into Users values('" + Name + "','" + Pass + "','" + Email + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
and That is my Connection String in web.config:
<connectionStrings>
<add name="ConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\myData.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
how do i know exactly what is my Data source? and what seems to be the problem?
Thanks in Advcance.
The error is saying that it can't connect to your database or instance of SQL SERVER. Have you try connecting to the db via SQl Server Management Studio? if you can connect with SSMS, then your problem may be inside your connection string.
Also, get in the habit of using parameters for your sql statement.
Related
I am new to programming and found these great tutorials on the Guru99.com site. Under the insert, update, Delete Asp.Net Database Connection Tutorial I was able to make the connection to the database successfully where the message came back "Connection Made".
The problem I am having is under the ASP.NET Read Database using the SQLDataReader. When I added the code and ran the program, I got a CS103 code which is The name 'sqlquery' does not exist in the current context. I thought that had to rem out the response.write and ccn.close statements thinking that the connection needed to be opened and still got the same error code. I hoping to find someone who are familiar with this tutorial. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
String connetionString; //Variable declaration
SqlConnection cnn;
connetionString = #"Data Source=BMIS-JHanlon3\SQLEXPRESS;Initial Catalog=DemoDB;User ID=sa;Password=demo123"; //Set connection string
cnn = new SqlConnection(connetionString); //Assign connection
cnn.Open(); //open and close the connection
// Response.Write("Connection Made");
// cnn.Close();
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = " ";
sql = "Select TutorialID,TutorialName from DemoDB";
command = new SqlCommand(sql, cnn);
dataReader = sqlquery.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
}
}
}
I have to change my data source to the name of my server [server name]\SQLExpress after moving my connection string from Page_Load to web.config. Otherwise I get an SqlException at con.Open(). The app works fine both ways am just wondering why I need to change the datasource name after moving the connection string.
<connectionStrings>
<add name="CS"
connectionString="data source=[server name]\SQLEXPRESS; Initial Catalog = SampleDb; integrated security = true"
providerName="System.Data.SqlClient"/>
</connectionStrings>
(string cs = "data source=.\\SQLExpress; initial catalog = SampleDb; integrated security= true";)-moved to web.config
string CS = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
//pass the connection string to the SqlConnection() constructor
SqlConnection con = new SqlConnection(CS);
//tell sqlcommand what query to execute and which connection
SqlCommand cmd = new SqlCommand("select * from Electronics", con);
//open connection
con.Open();
//execute the command
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
//close the connection
con.Close();
Preface: I have already and can connect to the respective databases in Amazon RDS from MySQL Workbench hence rendering my username, instance url, port number as well as password to be correct.
I am creating an online application for ASP.NET and need to connect to Amazon RDS
s MariaDB instead. I tried to do it via web.config or c# code way but both doesn't work. Advice needed.
Method 1
Web.config:
<add name="rdbs" connectionString="Server=xxxxxx.xxxxxx.ap-southeast-1.rds.amazonaws.com:3306; Database=xxx; Uid=xxxx; Pwd=xxxx;" providerName="MySql.Data.MySqlClient"/>
For my C# code side:
string connStr = ConfigurationManager.ConnectionStrings["rdbs"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(connStr))
Method 2
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Initial Catalog"] = "xxxx";
builder["Data Source"] = "xxxxx.xxxx.ap-southeast-1.rds.amazonaws.com";
builder["integrated Security"] = true;
builder["Uid"] = "xxxx";
builder["Pwd"] = "xxxx";
string connexionString = builder.ConnectionString;
SqlConnection connexion = new SqlConnection(connexionString);
try { connexion.Open(); return true; }
catch { return false; }
This is the form of errors I am facing:
Message "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)"
Thanks!
This actually solved it.
Grab MySql.Data.Entity from Nuget
Have this in web.config
<add name="connRDB" connectionString="Data Source=xxxxx.xxxx.ap-southeast-1.rds.amazonaws.com;port=3306;Initial Catalog=xxxxx;User Id=xxxxx;password=xxxx" providerName="MySql.Data.MySqlClient" />
On the code side
string constr = ConfigurationManager.ConnectionStrings["connRDB"].ConnectionString;
using (MySqlConnection conn = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("Select * FROM orders"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = conn;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string connString = "Data Source=localhost;Initial Catalog=test_db;Integrated Security=True;";
string insertCommand = "INSERT INTO empDetl (empName,addr) values(#empName,#addr)";
string _name = txtName.Text;
string _addr = txtAddr.Text;
using(SqlConnection conn = new SqlConnection(connString))
{
//open DB Connection
conn.Open();
using (SqlCommand cmd = new SqlCommand(insertCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#empName", _name);
cmd.Parameters.AddWithValue("#addr", _addr);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
This code doesn't work properly. Please tell me where the error is. While inserting values it says "Invalid object name 'empDetl'" but my table name is empDetl.
You probably have a database security issue here.
"Data Source=localhost;Initial Catalog=test_db;Integrated Security=True;";
This is going to use the current windows user (in the case of a web application probably the IIS user or whatever user your application runs under) to connect to the database using windows authentication.
Although your table may exist, the connecting user may not be able to see it.
Try change your connection string to the same user credentials you are connecting to your DB with through management studio
"Data Source=localhost;Initial Catalog=test_db;User Id=sa;Password=********;";
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.