How to create connection to database - c#

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}");
}
}
}

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

Connect to AWS RDS mssql using C#

I'm developing an app that requires a database and I'm attempting to use Amazon Web Service RDS and I have the security set to accept any IP from and port and I'm able to access the database using Microsoft SQL Server Manager, but when I attempt to connect using a test program in C#, I'm not able to establish a connection. I'm not getting a rejected connection, but a connection that can't even find the server. Am I going at this wrong? Here's my test code.
using System;
using System.Diagnostics;
using System.Data.SqlClient;
public static class Program
{
public static void Main(string[] args)
{
GetConnection();
}
public static void GetConnection()
{
string ConnectionFormat = "Server={0}; Database={1}; Uid=tie; Pwd=dune";
string Database = "juniorproject";
string Server = #"copy pasta,1433";
using (SqlConnection connection = new SqlConnection(string.Format(ConnectionFormat, Database, Server)))
{
Console.WriteLine(connection.ConnectionString);
connection.Open();
Console.WriteLine("Success");
}
}
}
Your server name doesn't even look close to right - it is going to be a much longer string, i.e. something like this:
myinstance.123456789012.us-east-1.rds.amazonaws.com
you'll need to lookup the actual endpoint in the AWS console.

Azure - ASP.NET MVC connect to mysql database

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..."){}

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 ....

C# Cant connect to Local SQL database

I've created a local SQL Server database and Login form, Here is the code of Login form :
namespace WindowsFormsApplication1
{
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (!(Usertxt.Text == string.Empty))
{
SqlConnection connection = new SqlConnection(#"Data Source=|DataDirectory|\crimemanagement.sdf");
connection.Open();
SqlCommand cmd = new SqlCommand(#"SELECT Count(*) FROM Login_table
WHERE Username=#Username and
Password=#Password", connection);
cmd.Parameters.AddWithValue("#Username", Usertxt.Text);
cmd.Parameters.AddWithValue("#Password", Passtxt.Text);
int result = (int)cmd.ExecuteScalar();
if (result > 0)
{
MessageBox.Show("Login Success");
}
else
{
MessageBox.Show("Incorrect login");
}
}
else if (Passtxt.Text == string.Empty || Usertxt.Text == string.Empty)
{
MessageBox.Show("Enter Username and Password");
}
}
}
}
But when I try to login using the form which I created it give me a connection error and highlights connection.open();
System.Data.SqlClient.SqlException was unhandled
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: 26 - Error Locating Server/Instance Specified)
In order to work with SQL Server Compact database files in ADO.NET you need to use the System.Data.SqlServerCe.dll ADO.NET provider, and use objects like SqlCeConnection, SqlCeCommand etc.
You're using SqlConnection which is for proper SQL Server (the server-based system), but you're referencing a SQL Server CE data file (.sdf).
If you want to use the .sdf, you need to use SqlCeConnection, SqlCeCommand etc. - not the SqlConnection and SqlCommand

Categories

Resources