connection string from c# to msql - c#

I am new to msql and i am working on MySQL Workbench 8.0 CE
I am trying to bind data from database to datagridview as show below but i am getting error below
but I am able to connecto my database using MySQL Workbench 8.0 CE so the connection to up so what I can do ?
public void GetPersonData()
{
string connstr = "Server=localhost;Database=newsequesterdb;Uid=reser;Pwd=00";
string query = "SELECT * FROM NEWSEQUESTERDB.PERSON;";
using (SqlConnection conn = new SqlConnection(connstr))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dgv_data.DataSource = ds.Tables[0];
}
}
}
error message
System.Data.SqlClient.SqlException: 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 specific to MS SQL Server. Use MySqlConnection (and associated command and data adapter classes) instead.
Note that MySqlConnection is not built in to the .NET Framework - you'll need to install it separately.

The thing is that you cannot use an SqlConnection instance nor SqlAdapter, those are intended to be SQL Server connection classes. And this you can see by the exception itself.
...(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
So, what's next? You should really look up to this question and may solve a few doubts.
From that question we can see that is using other references to connect to MySQL. Specifically Oracle's nugget package: MySQL.Data
using MySql.Data;
using MySql.Data.MySqlClient;
From that question example:
var dbCon = DBConnection.Instance();
dbCon.DatabaseName = "YourDatabase";
if (dbCon.IsConnect())
{
//suppose col0 and col1 are defined as VARCHAR in the DB
string query = "SELECT col0,col1 FROM YourTable";
var cmd = new MySqlCommand(query, dbCon.Connection);
var reader = cmd.ExecuteReader();
while(reader.Read())
{
string someStringFromColumnZero = reader.GetString(0);
string someStringFromColumnOne = reader.GetString(1);
Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
}
dbCon.Close();
}

Related

Error connecting to Local Database con.open()

I have the sample database Northwind installed and attached to a C# project
I'm trying to connect to the database and retrieve column names of a table in the database, but I'm getting an error while trying to open the connection, here is the code I'm using to do so:
public void connectToDB()
{
Dictionary<object, object> colns = new Dictionary<object, object>();
List<string> colnNames = new List<string>();
con = new SqlConnection("Data Source = .NorthwindDB.mdf; Integrated Security=True");
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM Products";
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables["Products"];
foreach(DataRow dr in dt.Rows)
{
foreach(DataColumn dc in dr.Table.Columns)
{
colnNames.Add(dc.ColumnName.ToString());
}
}
foreach(string key in colnNames)
{
Console.WriteLine(key.ToString());
}
Console.ReadKey();
}
I'm getting the following error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
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)
Another thing that may help, I'm noticing that whenever I click start button to execute the code, the green plug that appears over the data connection NorthwindDB.mdf turns into red x.
Your connection string is incorrect it should be something like this:
con = new SqlConnection("Data Source=(local);" +
"Initial Catalog=NorthwindDB.mdf;Integrated Security=True");
// Or Data Source=.\\sqlexpress;
You can read more about connection strings here: Database Connectionstrings.

asp.net sqlconnection won't open

I'm using the following to retrieve data from a database but the sqlconnection won't open. It throws an error at scon.Open(). I'm sure it's elementary but I can't work it out.
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();
}
}
}
}
}
I'm using this link
https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx
as one of my references. I'm also using SQLEXPRESS 2008 R2 if these information are of any help. Here's part of the error message:
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)
Would appreciate if I could get past this and move on. Thanks in advance.
If you have user instances configured on SQL Server (which is the default), you need to change your connection string to this:
Data Source=.\SQLExpress;Integrated Security=true;
initial catalog=database_Name
select * from table_name
Is your database name and table name same?

Connecting to mysql on 000webhost using C#

Im simply just trying to read what there is in the batabase on to a console but i always get an exception on the conn.Open() line. Here is all the code:
SqlConnectionStringBuilder conn_string = new SqlConnectionStringBuilder();
conn_string.DataSource = "mysql14.000webhost.com"; // Server
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxx";
conn_string.InitialCatalog = "a7709578_codecal"; // Database name
SqlConnection conn = new SqlConnection(conn_string.ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("Select name FROM Users");
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1));
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
You need to build the connection string manually or use MySqlConnectionStringBuilder. MySql uses a different format than SQL Server and the SqlConnectionStringBuilder that you're using. You also need to use a MySQL library, SqlConnection, SqlCommand, etc are all build specifically for SQL Server.
MySQL connectors
For MySQL database you are using wrong provider. Those classes you have used in posted code are for SQL Server. Your code should look like below with MySQL provider related classes
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql14.000webhost.com";
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxxxx";
conn_string.Database = "a7709578_codecal";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
Check Related post in SO
Also to point out, you are selecting only one column from your table as can be seen
new SqlCommand("Select name FROM Users");
Whereas trying to retrieve two column value, which is not correct
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1))
000webhost free servers does not allow external connections to the server database.
You can only use your database from your PHP scripts stored on the server.
You can get data from database using PHP and it will return.So i advice to you using php from C# like api.

PostgreSQL DSN Connection string in C#

I am trying to connect PostgreSQL database to C# application. For that I have created ODBC data source, now I need the connection string to include in C#.
Question: How to write DSN connection string for PostgreSQL in C#?
Try this
// PostgeSQL-style connection string
string connstring = String.Format("Server={0};Port={1};" +
"User Id={2};Password={3};Database={4};",
tbHost.Text, tbPort.Text, tbUser.Text,
tbPass.Text, tbDataBaseName.Text );
// Making connection with Npgsql provider
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
// quite complex sql statement
string sql = "SELECT * FROM simple_table";
// data adapter making request from our connection
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
More details here http://www.codeproject.com/Articles/30989/Using-PostgreSQL-in-your-C-NET-application-An-intr
this worked for me
"DefaultConnection": "User ID=postgres;Password=aamir7882;Server=localhost;Port=5432;Database=kingsurplus;Integrated Security=true;Pooling=true;
get server details and database details from pgAdmin 4

is there anyway to connect to sybase from c# without having to add a ODBC DSN connection in control panel

I am looking for a way to connect to sybase from C# without having to setup an ODBC DSN connection locally on the machine.
Is this possible? I tried all of these different connection strings:
static private DataTable Run(string sql)
{
var conn = new OdbcConnection();
const string CONN_STRING2 =
"Data Source='[myServer]';Port=5020;Database=[dbName];Uid=[user];Pwd=[pwd];";
const string CONN_STRING1 =
"Provider=Sybase.ASEOLEDBProvider.2;Server Name=[myServer];Server Port Address=5020;Initial Catalog=[dbName];User ID=[user];Password=[pwd];";
conn.Open();
var da = new OdbcDataAdapter { SelectCommand = conn.CreateCommand() };
da.SelectCommand.CommandText = sql;
var dt = new DataTable();
da.Fill(dt);
da.Dispose();
conn.Close();
return dt;
}
But I got an error stating:
{"ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"}
You are using var conn = new OdbcConnection(). That is why you are getting the error.
You will need to use a sybase oledb client library. I don't know sybase at all but last I heard one needed to purchase a third-party provider. This was almost three years ago so they may have one by now.
You would then need to do something like var connection = new ASEConnection().
Download the DLL from the following link:
Sybase library
Use this library for connection:
ASEconnection connection = new AseConnection();
Use specific ADO.Net data provider stright from manufacturer (SAP now own sybase). I think you can manage to create a connection string yourself using this reference. For example:
var connStr = #"Data Source=\\myserver\myvolume\mypat\mydd.add;User ID=myUsername;
Password=myPassword;ServerType=REMOTE;"
using (ASEConnection conn = new AseConnection(connStr)) {
// use conn
}
Same informaton can be obtained from documentation mentioned earlier.

Categories