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();
}
}
}
}
Related
<connectionStrings>
<add connectionString="provider=MSDAORA;Data Source=MyOracleDB;User Id=user;Password=****;" name="con"/>
</connectionStrings>
This is my connection string. i am using visual studio 2013 and oracle 10g version.
This is my code.
OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
public DataTable GetTday()
{
conn.Open();
string query = "select * from tday";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
return dt;
}
it shows 'ORA-12154: TNS:could not resolve the connect identifier specified' this error. please someone help
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();
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.
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=********;";
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