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
Related
I am trying to connect to a sample database I have created in Azure using C# (.NET Core 3.1)
I have enabled my IP address within Azure's Firewall rules.
I am able to use VS2019's SQL Server Object Explorer to connect and view the database within with no problems.
However, when I run a simple C# app on the same PC to execute a query to count the number of records in a table, it throws the following exception at the point where the connection is opened (conn.Open());
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: TCP Provider, error: 0 - The requested address is not valid in its context.)
The C# code;
using System;
using System.Data.SqlClient;
namespace AzureSql2
{
class Program
{
static void Main(string[] args)
{
string connStr = " Server=tcp:beaconsqlsql.database.windows.net,1433;Initial Catalog=MRP2;Persist Security Info=False;User ID=beaconadmin;Password=********;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
Console.WriteLine("Building connection");
try
{
using (var conn = new SqlConnection(connStr))
{
Console.WriteLine("Creating command");
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM [dbo].[Table]";
Console.WriteLine("Opening connection");
conn.Open();
Console.WriteLine("Reading database");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Record count: {0}", reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
}
}
I've tried temporarily turning off the firewall on my PC, but that made no difference.
The fact that SQL Server Object Explorer can connect but the C# code cannot makes it sound like there's a problem with the C# code, but I can't see any differences between it and the samples I've looked at.
I created one Azure SQL database and allowed my client IP like below :-
I created one .Net Console application and ran your code, I replaced
using System.Data.SqlClient
with
using Microsoft.Data.SqlClient
You can use any of the above packages.
Copied connection string from Azure Portal > Azure SQL server > Connection string refer below :-
C# Code:-
using System;
using System.Linq.Expressions;
using Microsoft.Data.SqlClient;
namespace AzureSql2
{
class Program
{
static void Main(string[] args)
{
string connStr = "Server=tcp:sqlservername.database.windows.net,1433;Initial Catalog=sqldbname;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
Console.WriteLine("Building connection");
try
{
using (var conn = new SqlConnection(connStr))
{
Console.WriteLine("Creating command");
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT * FROM Products";
Console.WriteLine("Opening connection");
conn.Open();
Console.WriteLine("Reading database");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Record count: {0}", reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
}
}
Output :-
I tried to run the code with the connection string format you mentioned in the comments :-
Data Source=azuresqlservername.database.windows.net;Initial Catalog=databasename;User ID=siliconuser;Password=password;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
And I was able to run the same code above and got the desired output:-
When I tried to change the Azure SQL server name in the connection string, I got the same error code as yours, refer below :-
Verify if your connection string has any syntax missing and validate it from Azure Portal.
I ended up taking a copy of the project home and running it on my home PC, and it worked correctly and reliably (after telling Azure to allow that IP address as well)
It turned out the answer was embarrassingly obvious - in addition to the standard Windows 10 firewall, my work PC is running another virus protection/firewall software, and that also needed to be told to allow the app thru.
Definitely one to remember for next time... Although I am kind of intrigued that on two occasions (once mentioned above, once afterwards) out of a few hundred attempts the app did manage to get thru and connect.
Thank you everyone for your answers and help.
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}");
}
}
}
static void Main(string[] args)
{
OleDbConnection conn = new OleDbConnection("Provider=SAOLEDB.10;LINKS=tcpip(IP=192.168.1.100,Port=2638);ENG=dental;Persist Security Info = True; User ID = dba; PWD = sql");
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT tran_num FROM transactions WHERE tran_date > '2015-10-01'", conn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0}", reader.GetValue(0).ToString());
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
As the title suggests, I'm getting an error when attempting to connect to this server. The driver (Provider) works fine for a local database using the same server setup, trying to adjust the code to connect remotely to the same setup at a different location. This is an old SQL Anywhere 10 database and I've tried hard to find answers for this with no success so far.
Edit: I changed the string a little to reflect some suggestions, now just getting a new error: Additional information: Connection error: TCPIP requires a server name
Update: The syntax changes to LINKS seems to have progressed my attempts but now I'm having issues with the syntax it's looking for when searching for a server at that IP. Receiving an error: Additional information: Database server not found
This is the connection string in registry:
DBN=DENTSERV;DSN=DENTAL;UID=DBA;PWD=SQL
I've tried both ServerName= and ENG= using the DSN and DBN, also while having them in ' ' but still receiving that same error. Any thoughts?
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..."){}
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 ....