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
Related
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();
}
i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}
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.
Hi I would like to know how I should connect to the external SQL Server database in C# , .NET ?
For example if I have there parameters :
SQL info
Url to get to database (throughout browser also): Sqlweb.companyname.com
Database username: username
Server: Dcms-xxx
Databasename: databaseName
Databasepassword: password
?
I know how to connect to internal : Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.AppDomain.CurrentDomain.BaseDirectory + "..\\Files\\MapPlaces\\Database.mdb;";
But what about external ?
I have tried :
string nowConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Sqlweb.companyname.com;Initial Catalog = databaseName; User Id = Username; Password = Password;";
System.Data.OleDb.OleDbConnection dbcon = new System.Data.OleDb.OleDbConnection(nowConString);
string sql = "SELECT * FROM XXXTable";
dbcon.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbcon);
System.Data.OleDb.OleDbDataReader reader;
reader = cmd.ExecuteReader();
ScriptStuff.Append("Reader created!<br/>");
while (reader.Read())
{
string companyName = reader.GetValue(1).ToString();
ScriptStuff.Append(companyName+"<br/>");
}
Did not work ! Thank you for your help !
Edited from comments:
Yes that was one my mistake, thanks. Since first one was access and YES second is SQL Server. And it is SQL Server 2005. But I am new to .net and all that... I have found first one and second one in that connectionstring.com but I could not find or understand how to use that for this one ...
Could you help, and just post hole connection ? Thanks – Vilius 7 mins ago
I mean do I still need to use OleDB ? should there be "Provider=Microsoft.Jet.OLEDB.4.0;" in that connection string ? Where do i post what (server (that Dcms-xxx), or url of the sql server (sqlweb.companyname.com))? THANKS FOR YOUR HELP ! –
I would add a connectionString to my app/web.config.
<connectionStrings>
<add name="AspnetdbConnectionString"
connectionString="Data Source=<databaseadress>;Initial Catalog=<database>;User Id=<user>;Password=password>"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
The above example is how you specify an connectionstring for a MSSQL connection, and below a way to use this connectionstring.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AspnetdbconnectionString"].ConnectionString))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.Text;
cm.CommandText = "SELECT * FROM ...";
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
while (dr.Read())
{
// do stuff
}
}
}
}
Are you sure that it's a SQL Server database that you are trying to connect to?
Your "internal" example connects to a Microsoft Access database (OLEDB provider and database file extension .mdb)
If your external database is really a SQL Server database, the recommended way is using SqlConnection, SqlDataReader and so on instead of OleDbConnection etc.
Or, if you really want to use OleDb, you need a different connection string.
See connectionstrings.com (for SQL Server 2008, 2005 or 2000, depending what you're trying to connect to).
I would highly recommend taking a look at:
http://www.connectionstrings.com/
It's a quick, "in you face" treatment of the subject of connection strings for all major databases.
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.