connect to tableau postgresql in C# - c#

I want to connect to the tableau PostgreSQL server from my .Net framework to list all the reports and datasources published in the tableau server.
For doing this, I have done the following steps.
Added the npgsql.dll reference that i downloaded online
Added the below two namespaces in my class file
using NpgsqlTypes;
using Npgsql;
I added the connection sting as follows
I also tried with modifying the connection string with port value and renaming the DataSource to Server, Initial catalog to Database and provider Name to Npgsqll
My Method is as follows:
public DataTable getAllDataSourceNames()
{
DataTable dataSourceNames = new DataTable();
NpgsqlConnection conServer = new NpgsqlConnection(conString);
conServer.Open();
string command = #"select * from datasources";
NpgsqlDataAdapter sqlcmd = new NpgsqlDataAdapter(command,conServer);
sqlcmd.Fill(dataSourceNames);
return dataSourceNames;
}`
No error. I can build and run successfully the other links in the website. But cannot cannot establish connection to my postgresql server.
Any idea of how to establish the connection?

Working with Postgres Connection in c#:
private DataSet ds = new DataSet();
private DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}
private void llOpenConnAndSelect_LinkClicked(object sender,
LinkLabelLinkClickedEventArgs e)
{
try
{
// 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);
// i always reset DataSet before i do
// something with it.... i don't know why :-)
ds.Reset();
// filling DataSet with result from NpgsqlDataAdapter
da.Fill(ds);
// since it C# DataSet can handle multiple tables, we will select first
dt = ds.Tables[0];
// connect grid to DataTable
dataGridView1.DataSource = dt;
// since we only showing the result we don't need connection anymore
conn.Close();
}
catch (Exception msg)
{
// something went wrong, and you wanna know why
MessageBox.Show(msg.ToString());
throw;
}
}
The following link may help you: Using PostgreSQL in your C# .NET application

Short answer -- no, not sure what's wrong. Your code doesn't raise any alarm bells.
Somewhat related, and it may help: I'm a big fan of the Connection StringBuilder with Npgsql. Here is a brief example:
NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
sb.ApplicationName = "Tableau " + Environment.GetEvironmentVariable("USERNAME");
sb.Host = "1.2.3.4";
sb.Port = 5432;
sb.Username = "foo";
sb.Password = "bar";
sb.Database = "postgres";
sb.Pooling = false;
sb.Timeout = 120;
conServer = new NpgsqlConnection(sb.ToString());
It demistifies all of this and makes injecting parameters easy. I highly recommend you add the ApplicationName property so that when you are monitoring sessions, you will know who is who.

Related

Update the datatable without using DataAdapter.Fill 2 times

I am writing a program to manage a office. (Getting rid of Excels XD).
I have a DAL class with the following variables:
private MySqlConnection connection;
private DataSet ds;
private Hashtable adapters;
There is this method:
public bool AddTable(string tableName, string sqlStat)
{
if (!ds.Tables.Contains(tableName))
{
MySqlDataAdapter adapter = new MySqlDataAdapter(sqlStat, connection);
MySqlCommandBuilder builder = new MySqlCommandBuilder(adapter);
adapter.InsertCommand = builder.GetInsertCommand();
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.DeleteCommand = builder.GetDeleteCommand();
adapter.Fill(ds, tableName);
adapters.Add(tableName, adapter);
return true;
}
return false;
}
The program will be connected to a server with MySQL database.
I need to make sure that when one client changes something in the database another client will see the new data, but this is not happening.
You need to read up on optimistic concurrency, which helps solve the problem of multiple users reading and updating the same data at the same time.
I suggest you start here:
http://msdn.microsoft.com/en-us/library/aa0416cz%28v=vs.110%29.aspx
http://www.codeproject.com/Articles/114262/6-ways-of-doing-locking-in-NET-Pessimistic-and-opt

C# Winforms control - DataGridView - Update Database

The programs I am using are WAMP server (and its mysql feature in particular) and MS Visual Studio 2010 and I am programming in C#
Basically, here is what I need and can currently do with my application.
I have several datagridview's throughout the project and the first is simple, it loads all data from a specific table in the database at the push of a button. I have another form which I can insert records and have somehow managed to make a delete function which asks the user for 2 fields (first name and last name) and then it places these into a query and carries out the command.
What do I need to do?
I need to be able to implement some way for the form to update the database. I have chosen to do this through a datagridview control so the user can see what they are editting whilst they edit it.
I have the following code which I have tried to update the database based on the data in the datagridview control.
string connString = "server=localhost;User Id=root;database=collegelist;";
MySqlConnection conn = new MySqlConnection(connString);
string selectSQL = "SELECT * FROM collegeemployee";
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(selectSQL, conn);
MySqlCommandBuilder builder = new MySqlCommandBuilder(da);
DataTable table = new DataTable();
try
{
dgView2.Rows.RemoveAt(dgView2.CurrentRow.Index);
da.Update(table);
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
the problem with this code (listed in a method obviously) is that while the grid is able to be modified, it is unable to pass the data back to the database.
Instead of updating your database with the empty table what you should do is.
i.Get the datasource . like
ii. Update/synchronize the data source and data adapter
Here is the code it should work, if it doesn't please comment and tell me the problem.
string connString = "server=localhost;User Id=root;database=collegelist;";
MySqlConnection conn = new MySqlConnection(connString);
string selectSQL = "SELECT * FROM collegeemployee";
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(selectSQL, conn);
MySqlCommandBuilder builder = new MySqlCommandBuilder(da);
BindingSource BindingSourceToUpdate = (BindingSource)dgView2.DataSource; // because direct casting to data table was failing in VS2o1o
try
{
dgView2.Rows.RemoveAt(dgView2.CurrentRow.Index);
da.Update((DataTable)BindingSourceToUpdate.DataSource);
}
catch(exception)
{
}
conn.close();

Network-related or instance-specific error occurred while establishing a connection to SQL Server

I just want to loop through the results in the database. That's all I am trying to do at this point! This is the error I get when I try to debug:
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)
It points to this line:
// fill dataset into named table
myAdapter.Fill(myDataSet, "Sent");
Here is my whole code:
// get connection strings from app.config
string conString = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
// connection object
SqlConnection myConn = new SqlConnection(conString);
// create adapter
SqlDataAdapter myAdapter = new SqlDataAdapter("select * from `Sent`", myConn);
// create command builder
SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter);
// create dataset
DataSet myDataSet = new DataSet();
// fill dataset into named table
myAdapter.Fill(myDataSet, "Sent");
// query using linq
IEnumerable<DataRow> results
= from row in myDataSet.Tables["Sent"].AsEnumerable()
select row;
// enumerate through results
foreach (DataRow row in results)
{
MessageBox.Show(row.ToString());
}
What can I do to fix this? Also, if anyone has an easier way to use databases in C#, I am open to your ideas because this has been ridiculous for me (manipulating a database in c#). Thank you for your help.
Update 6/29/12:
The following code works for me:
// get connection strings from app.config
string conString = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
// connection object
SqlCeConnection myConn = new SqlCeConnection(conString);
// create adapter
SqlCeDataAdapter myAdapter = new SqlCeDataAdapter("select * from [Sent]", myConn);
// create command builder
SqlCeCommandBuilder myCommandBuilder = new SqlCeCommandBuilder(myAdapter);
// create dataset
DataSet myDataSet = new DataSet();
// fill dataset into named table
myAdapter.Fill(myDataSet, "Sent");
// create new row
DataRow newRow = myDataSet.Tables["Sent"].NewRow();
// set field vals
newRow["sendTo"] = sendTo;
newRow["subject"] = subject;
newRow["message"] = message;
// add new row to table
myDataSet.Tables["Sent"].Rows.Add(newRow);
// update database
myAdapter.UpdateCommand = myCommandBuilder.GetUpdateCommand();
int updatedRows = myAdapter.Update(myDataSet, "Sent");
//MessageBox.Show("There were "+updatedRows.ToString()+" updated rows");
// close connection
myConn.Close();
First of all: check your connection string error is telling you straight "Hey, I cannot connect to your Database"
Second: select * from Sent (without apostrophes)
Did you changed the password you use in the machine where the SQL server is installed? I experienced this before, and what I did was to reflect my new password to the SQL Server configuration, then restart the service.
Please also make sure the the TCP/IP setting is enabled in the SQL configuration settings.
this kind of error will arise when we did not change the tcp/ip setting in sql server configuration manager.So we need enable the tcp/ip property to resolve this error
Might be stating the obvious here but have you checked that the SqlExpress service is running?
https://stackoverflow.com/a/4650231/1095373
I wasn't using the correct code (it didn't have anything to do with any connection stuff). This was my first crack at trying to connect to a database in a language other than PHP. Now, I would probably use LINQ or Lambda expressions than this code. But here is what I used which worked:
// get connection strings from app.config
string conString = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
// connection object
SqlCeConnection myConn = new SqlCeConnection(conString);
// create adapter
SqlCeDataAdapter myAdapter = new SqlCeDataAdapter("select * from [Sent]", myConn);
// create command builder
SqlCeCommandBuilder myCommandBuilder = new SqlCeCommandBuilder(myAdapter);
// create dataset
DataSet myDataSet = new DataSet();
// fill dataset into named table
myAdapter.Fill(myDataSet, "Sent");
// create new row
DataRow newRow = myDataSet.Tables["Sent"].NewRow();
// set field vals
newRow["sendTo"] = sendTo;
newRow["subject"] = subject;
newRow["message"] = message;
// add new row to table
myDataSet.Tables["Sent"].Rows.Add(newRow);
// update database
myAdapter.UpdateCommand = myCommandBuilder.GetUpdateCommand();
int updatedRows = myAdapter.Update(myDataSet, "Sent");
//MessageBox.Show("There were "+updatedRows.ToString()+" updated rows");
// close connection
myConn.Close();

Sqlite database utilites class

I am using SQlite as a database in a C# winforms application.
My project involves some select simple queries, inserts, deletes.
Currently, I have written all these sql, Ado.net queries in the codebehind.
For eg:
private void frmPlant_Load(object sender, EventArgs e)
{
FillData();
}
void FillData()
{
dataGridView1.AutoGenerateColumns = true;
string query = #"SELECT * FROM [Table1]";
using (SQLiteConnection conn = new SQLiteConnection(connString))
{
conn.Open();
da = new SQLiteDataAdapter(query, conn);
ds = new DataSet();
da.Fill(ds, "T1");
dt = ds.Tables[0];
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "T1";
dataGridView1.Columns["TId"].HeaderText = "SNo";
dataGridView1.Columns["Tcode"].Visible = false;
dataGridView1.Columns["TID"].Width = 50;
dataGridView1.Columns["Tcode"].Width = 70;
}
}
I have quiet a bit of code like this which interacts with the DB.
Question: Instead of writing these ado.net connections, sql query in the code behind, I want to use a 2 tier/3tier architecture. This should involve writing all the database stuff(ado.net execute scalar, reader, sql queries in another DBUtilitesclass/project and simply calling this DBUtilitesclass from the code behind.
Please suggest any tutorials to do this.
PS: I am using sqlite which does not support stored procedures.
Thank u
Sun
Refer
http://www.switchonthecode.com/tutorials/csharp-tutorial-writing-a-dotnet-wrapper-for-sqlite
http://snipplr.com/view/41708/
http://www.codeproject.com/Articles/22165/Using-SQLite-in-your-C-Application
Hope this helps
Thanks
Deepu

What is the best way to connect to a local database that will be used by two apps?

I'm writting an application in C# that connects to a database that is used by other application. I'm coding the class that access the database like this:
class conexionBD
{
string connString;
protected void miConexion(string ruta)
{
connString = String.Concat("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=", ruta);
}
protected DataTable misEmpleados()
{
string query = "SELECT Fiel1, Field2 FROM Table1";
DataTable dTable = miDatatable(query);
return dTable;
}
protected DataColumn misDptos()
{
DataTable dTable = miDatatable("SELECT OtherField from OtherTable");
return dTable.Columns[0];
}
private DataTable miDatatable(string sqlQuery)
{
OleDbDataAdapter dAdapter = new OleDbDataAdapter(sqlQuery, connString);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
return dTable;
}
}
The app firts calls the method "miConexion" to set the path to the database in the hard disc. Then the app connects and disconnects each time I want to get the data stored in "Table1" and "OtherTable".
The database is likely to be accessed and modified by both apps at the same time. "Connecting and disconnecting" is the best way to access the database in this case?
there are 3 improvements you can make:
abstract the specific database adapter to the configuration file.
dispose of ado.net objects when you are finished with them
use transaction when reading and writing to/from the db.
The database is likely to be accessed and modified by both apps at the
same time.
Then you would need to use transactions.
Also check that you open and close connection and the connection remains open for the shortest possible time. OleDb stack is really old if this is a new application consider moving to ORM or at least ADO.NET.
Use an ORM like Entity Framework (EF) or NHibernate to manage the state of the object (if both applications are .Net)
I would recommend NHibernate as you are using OLE data adapter (but see if there are any connectors for the database you are using for EF as it is far easier to setup)..
This is the modification of the method "miDatatable", it connects to an Access Database:
private DataTable miDatatable(string sqlQuery)
{
using (OleDbConnection connDB = new OleDbConnection(connString))
{
OleDbDataAdapter dAdapter;
OleDbCommandBuilder cBuilder;
OleDbCommand command = new OleDbCommand();
DataTable dTable = new DataTable();
OleDbTransaction trans = null;
try
{
connDB.Open();
trans = connDB.BeginTransaction(IsolationLevel.ReadCommitted);
command.Connection = connDB;
command.Transaction = trans;
command.CommandText = sqlQuery;
dAdapter = new OleDbDataAdapter(sqlQuery, connDB);
cBuilder = new OleDbCommandBuilder(dAdapter);
dAdapter.SelectCommand.Transaction = trans;
dAdapter.Fill(dTable);
trans.Commit();
}
catch
{
try
{
trans.Rollback();
}
catch { }
}
return dTable;
}
}

Categories

Resources