Azure - ASP.NET MVC connect to mysql database - c#

Actually, i wanted to check is my connection string valid.
There are asp.net mvc web app and mysql db deployed on azure, so i want use second thing in first. So, i added db to visual studio server explorer - db and all tables are visible.
Now i tried to add connectionstring to my project, and, wow, there are two of them i found:
First: In Visual studio data connection properties:
server=us-cdbr-azure-central-a.cloudapp.net;user id=userid;persistsecurityinfo=True;database=crawlerdb
Second: In azure workplace's database property:
Database=CrawlerDB;Data Source=us-cdbr-azure-central-a.cloudapp.net;User Id=userid;Password=userpass
And both of them doesn't work. Never lucky.
Connection state checking code:
using (SqlConnection conn = new SqlConnection(connstr))
{
try
{
conn.Open();
var q = conn.State;
}
catch(Exception ex)
{
var q = ex.Message;
}
}
What am i doing wrong?:) Tell me plz:)
public class CrawledDataContext : DbContext
{
public CrawledDataContext()
{
Database.SetInitializer<CrawledDataContext>(null);
using (SqlConnection conn = new SqlConnection("server=us-cdbr-azure-central-a.cloudapp.net;user id=bb15193d20f901;persistsecurityinfo=True;database=crawlerdb"))
{
try
{
conn.Open();
var q = conn.State;
}
catch(Exception ex)
{
var q = ex.Message;
}
}
}
public DbSet<GroupInfo> GroupInfoes { get; set; }
}
Here is exception 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"

SqlConnection is for SQL Server Databases. you should use MySqlConnection instead.
using (MySqlConnection conn = new MySqlConnection("server..."){}

Related

C# trying to send queries

I got a linux server with mariadb installed and i want to send queries to that server with C# with this script
namespace SQLTEST
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
CreateCommand(
"INSERT INTO TEST(name) VALUES ('sample');",
"server=IPadress;database=test;uid=root;password=**;pooling=false;" );
Console.ReadKey(true);
}
private static void CreateCommand(string queryString, string connectionString)
{
try{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
System.Console.WriteLine("Connectin open");
command.ExecuteNonQuery();
}
} catch(Exception e){
System.Console.WriteLine(e.Message);
}
}
}
}
I tried to change the connection string multiple times. It seems like i cant get over the command.connection.open line
This is the error i keep getting
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)
You have MariaDB (essentially MySQL) as your database and you are trying to use Microsoft SQLServer client libraries to access it. It'll never work - they are completely different databases.
Use MySQL library instead

How to create connection to database

This is my code:
string dbInfo;
SqlConnection dbConnection;
public Sales_Database()
{
dbInfo = #"SERVER=185.175.200.35;DATABASE=guusbxg438_products;UID=*****;PASSWORD=******";
}
public override bool Connect()
{
dbConnection = new SqlConnection(dbInfo);
dbConnection.Open();
}
This is the upfollowing exception:
System.Data.SqlClient.SqlException: "A network error or an instance-specific error occurred while connecting to SQL Server. The server was not found or is not accessible. Verify that the instance name is correct and that the SQL Server settings allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open connection to SQL Server) '
Are you trying to connect to an SQL or MySQL database. At the moment you are connecting to an SQL server. Since you have the tag phpmyadmin, it will probably a MySQL database. Therefor you need a MySQL connector.
Read more here: http://zetcode.com/csharp/mysql/
Example from source above:
using System;
using MySql.Data.MySqlClient;
namespace Version
{
class Program
{
static void Main(string[] args)
{
string cs = #"server=localhost;userid=dbuser;password=s$cret;database=testdb";
using var con = new MySqlConnection(cs);
con.Open();
Console.WriteLine($"MySQL version : {con.ServerVersion}");
}
}
}

Connection string for local database not working

I have a database on my local machine on SQL Server Management studio.
The database connection information is as follows.
In my c# application, I have a connection string to connect to this database. I get an error though saying my connection string is incorrect. I have tried a number of different ones.
This is my function to connect to a database.
public virtual void openConnection()
{
con = new SqlConnection();
con.ConnectionString = "Server=DESKTOP-8UDMQUI\\WILLIAMSQL;Initial Catalog=team3db;TrustServerCertificate=true;";
try
{
con.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
I have two \ in the server name because when I only have one, it has a red squiggle line under it throwing me an error on visual studio.
What should my connection string be? Note there is no password on this database.
Replace TrustServerCertificate = true; with Integrated Security = true

Connect and insert data from my computer to server's MySQL DB table with the help of C#.NET

I want to connect with a server's MySql DB(cpanel) . Though there are no errors every time I'm getting a message for Messegebox : unable to connect to any of the specified any of the MySql hosts.
using MySql.Data.MySqlClient;
connString = "SERVER = ********;PORT=3306;DATABASE=********;UID=**********;PASSWORD=*********";
try
{
conn = new MySqlConnection();
conn.ConnectionString = connString;
conn.Open();
MessageBox.Show("Server is online");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{ MessageBox.Show(ex.Message);}
If you try to connect to your MySQL server externally, external connections need to be enabled.
Be aware that it is a security hole if you provide your app to others which contain the DB information. To go around that, you need to create a Web-API.
The first step to connect to your app to a remote server MySql Server is verify if it allows external connections, for default the root user is locked, to allow local you can try to connect with the root user typing the following command in MySql:
GRANT ALL PRIVILEGES ON *.* TO 'root'#'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
'root': You can change it with your user.
'%': allows all connections, you can limit it typing an IP.
Second step is verify your MySql .net connector
Cheers!
I would look into using ConnectionStringBuilder. Also note the use of 'using'. This will ensure resources are disposed once finished with.
private MySqlConnectionStringBuilder sConnString = new MySqlConnectionStringBuilder
{
Server = "",
UserID = "",
Password = "",
Database = ""
};
private void Test(){
// open connection to db
using (MySqlConnection conn = new MySqlConnection(sConnString.ToString()))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
try
{
conn.Open();
cmd.CommandText = "SELECT * FROM foo WHERE OrderID = #OrderID";
// Add any params
cmd.Parameters.AddWithValue("#OrderID", "1111");
cmd.Prepare();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return;
}
}
}
}

My database system cannot find the file specified in asp.net

I am trying to retrieve data from a database with the following code:
public partial class populate : System.Web.UI.Page
{
SqlConnection scon = new SqlConnection("Data Source = localhost; Integrated Security = true; Initial Catalog = populate");
protected void Page_Load(object sender, EventArgs e) {
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
}
It's throwing an error:
The system cannot find the file specified
I am wondering if someone can show me where the error is or guide me through debugging this. Thanks in advance.
(update): More specifically, the scon.Open() is causing the error:
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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
This looks easy enough to fix, but I'm not very good with the database. Any help will be appreciated.
I don't know what SQL Server edition you have installed, and what you called it (as an instance name) .....
Go to Start > SQL Server > Configuration Tools > Configuration Manager; under SQL Server Services, search for the SQL Server service - what is it's name??
If it's SQL Server (SQLEXPRESS), then that means you have the Express edition, with an instance name of SQLEXPRESS - change your connection string to:
Data Source=.\SQLEXPRESS;Initial Catalog=populate;Integrated Security=true;
If it's SQL Server (MSSQLSERVER) then you should be fine really - you have an unnamed, default instance ....

Categories

Resources