I have PostgresQL database, and I develop interface application using C# and Npgsql to connect to the database, how can I assign the Npgsql connection to TableAdapter?
Thanks,
I'm in the exact same boat with PostgreSQL.
I don't believe that's possible. Npgsql has its own data adapter (see http://npgsql.projects.postgresql.org/docs/manual/UserManual.html and search for text "adapter"). The downside to this is that you can't use the Visual Studio Designer.
So instead, I'm using .NET's ODBC DataSource. For this to work, you will need to install the postgresql odbc driver, which is available here: http://www.postgresql.org/ftp/odbc/versions/msi/. After installing, you can go to Control Panel -> Administrative Tools -> Data Soruces (ODBC) to add a DSN (Data Source Name). Finally, in Visual Studio go to the Server Explorer, right click "Data Connections" and select "Add Connection...", and change the data source of Microsoft ODBC Data Source. Here you can select the DSN you provided earlier, and viola! You're in business.
(Note that for some crazy reason bools come in as strings. You can change this in the ODBC Data Source Administrator by clicking "Configure" on your PostgreSQL datasource, going to Datasource options, and unchecking "Bools as Char".)
Sorry its a bit late however here is how you would do it, use the data adapter.
create a datagrid
create a datatable
fill the datatable with the dataAdapter, // function is provided - dataTableName.fill()
set the datagrid to display default view of the dataTable
try
{
using (var Connection = new NpgsqlConnection(PG_Connection_String))
NpgsqlDataAdapter da = new NpgsqlDataAdapter("myQuery", connectionString))
{
Connection.Open();
myTable = new System.Data.DataTable();
da.Fill(myTable);
postgresql_dataGrid.DataSource = myTable.DefaultView;
Connection.Close();
}
}
catch (Exception Ex)
{
MessageBox.Show("Your Error", "Connection Error");
}
}
Bob's your uncle, I'm using it successfully. I would suggest that if you wish to prepare the grid for custom headers etc, do it BEFORE setting the default view of your datagrid
Related
I am working on a plugin for the software Autocad in Visual Studio (C#) and would like to import a MS Database manually. I looked a bit online and saw that you can connect to a database via the toolbar but I'd like for the user to import a .accdb file by clicking on a button from WinForms. Is it possible for me to do something like that? I'm thinking of a library or any helpful tool (like System.Xml) so that I can access the database via code and potentially SQL queries.
To make things clearer, here is an example of how the plugin would work:
Open Autocad and the Plugin
WinForms window pops up with a button: Import Database
After successful import, data will be loaded in a dropdown and you can select one of the values
Every suggestion and tip is appreciated! :)
Use System.Data and System.Data.OleDb.
You'll have to look up your connection string for your database. This isn't a robust solution, but it gets the job done quick.
public DataSet GetDataSet(string sql)
{
DataSet dataSet = new DataSet();
using (OleDbConnection conn = new OleDbConnection(connString))
{
try
{
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
adapter.Fill(dataSet);
}
catch (Exception ex) { throw new Exception(ex.Message); }
finally { conn.Close(); }
}
return dataSet;
}
Here is everything that I did:
In a visual studio 2013 C# project, I created a service database (.mdf file). Note: I changed the name from Database1.mdf to fghLocalDB.mdf.
I opened this database in the server explorer.
I created 2 tables called Country and CarbonDioxide using the table designer.
I added an entry to the Country table as shown by the Data Table of the Country table.
I did the following to create a DataSet my application can use. I created a Data Source by clicking on the "Project" option on the top menu bar and clicking on the "Add New Data Source ..." option from the drop down.
This is what my project files looked like at this point.
I wrote the following code in the main method thinking that this would be all I need to write to the database.
// Create a connection to the DataSet and TableAdapters that will communicate with our
// local database to handle CRUD operations.
fghLocalDBDataSet dataSet = new fghLocalDBDataSet();
fghLocalDBDataSetTableAdapters.CountryTableAdapter countryTableAdapter =
new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
try
{
// Insert a row into Country table. EDIT 1 Will comment after first program run.
Console.WriteLine(countryTableAdapter.Insert("United States"));
// Actually writeback information to the database?
// dataSet.AcceptChanges(); EDIT 2 commented this as LeY suggested it was not needed.
// EDIT 3 Validation code as suggested by Ley.
var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
adapter.Fill(dt);
foreach (var row in dt)
{
// This does not get executed after a second run of the program.
// Nothing is printed to the screen.
Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();
}
catch(SqlException exception){
Console.WriteLine("ERROR: " + exception.ToString());
}
Console.ReadLine();
I ran the program and everything seemed fine.
I opened the tables by right clicking on these tables in the server explorer and pressing "Show Data Table".
The "United States" row was not added as wanted.
I think it has to do with the connectionstring. I right clicked on my project and opened properties.
Here I made sure the connection string matched that of the local database by looking at the string in the properties of the database. They are the same.
I copied and pasted the actual text for each connection string:
Connection string of project:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True
Connection string of actual database (.mdf file):
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True
I am assuming |DataDirectory| is equal to C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf; since in the picture above when I clicked on the button to expand the Value of the connection string the connection properties window opened up and had this path for the database file name.
My question in a nutshell is does instantiating a DataSet object in the code automatically create a connection to a SQL service-based database for CRUD operations?
If not how do I connect my DataSet object to my sql database so that way I can actually write to the database when using the TableAdapters?
I read the following links:
Insert method of TableAdapter not working?
TableAdapter Insert not persisting data
Use connectionstring from web.config in source code file
Do I need an actual SqlConnection object? and how to I connect this to the DataSet & TableAdapters?
I never used tableadpter.insert() method. But I tried it on my local machine, and it works.
I can't figure out your problem based on the information you provided, sorry, but I can point you a direction.
If you created everything from wizard, you don't need to worry about the connection, the table Adapters will handle the connection for you. The connection string (you circled) will be added to your app.config file as well as your setting class automaticly. That is how your application (or you) uses it.
var countryTableAdapter = new CountryTableAdapter();
countryTableAdapter.Insert("United States");
This 2 lines of code are enough to insert the row into database if there is no exception thrown, I don't know why it doesn't work for you. Maybe the way you verify it somehow goes wrong, but you can verify it in another way.
The countryTableAdapter.Insert method will return the number of row get affected, in your case , should be one. So put the following code in , and set a breakpoint after it. if the rowAffected == 1, then the insertion works.
var rowAffected = countryTableAdapter.Insert("Test2")
If you need more confirmation , try this.
var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new CountryTableAdapter();
adapter.fill(dt);
foreach (var row in dt){
Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();
you will see all the records in your table.
I hope this will help.
By the way, from your code
dataSet.AcceptChanges();
The line of code above doesn't update the database at all. It only modify your local data storage.
it overwrites your dataRow original version using current version and change the current version row state to unchanged.
Only the tableadapters can talk to database (not true I know, but I just want to make a point that Dataset can not talk to database directly).
And I usually only need tableadapte.Update method and pass the dataSet or dataTable in with correct RowState.
The tableAdapter.update method will call AcceptChanges on each row eventually if it successfully updated the database.
You should never need to call AcceptChanges explicitly unless you only want update your dataset in memory.
I recommend you to read ADO.NET Architecture to get the big picture how DataSet and TableAdapter worked.
It was my connection string after all. In my original post, I said I had two connection strings:
Connection string in project settings:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True
Actual connection string in fghLocalDB.mdf file:
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True
Something went wrong with
|DataDirectory| = C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;
in my App.config.
My Solution:
What I did was copy the actual connection string of the .mdf file from the .mdf properties panel and paste it into the project properties => Settings => Value field of the connection string set up.
Afterwards I ran my code again and sure enough the data persisted in the tables.
I did not need dataSet.AcceptChanges(); as #LeY pointed out. I also did not need a TableAdapter.Update(dataset) call as posted in other solutions. I just needed the TableAdapter.Insert("...") call.
EDIT: ALSO Most importantly to answer my original question, instantiation a DataSet does not create a connection with the local database. Instead instantiating a TableAdapter does establish a connection with the database!
We want to add a table programmatically to our local stored Microsoft SQL Server Compact 3.5 Database. The code below creates the table.
using (SqlCeConnection con =
new SqlCeConnection("Data Source=|DataDirectory|\\Database.sdf"))
{
con.Open();
using (SqlCeCommand com =
new SqlCeCommand("create table test (id int not null)", con))
{
Console.WriteLine("Response: " + com.ExecuteNonQuery());
}
con.Close();
}
The code is working fine, but the table isn't listed up in the Server Explorer of the specified database table. We can insert values into the table and read data out of the table.
Do you know any solutions for this problem?
Afterwards we want to add a dynamic datamodel, which we want to use as a provider of our tables.
Thank you in advance.
The use of |DataDirectory| means that you have 2 copies of the file in your project folders.
Your application is using the one in Root\bin\debug.
Your tools are looking in \Root.
Right, I have been tasked with developing a new application in MVC3 that unfortunately has to integrate very slightly with a classic asp web site. This won't be forever as the old site will get an update at some point, but not yet. In the mean time however the new MVC3 application will need a little bit of access to the database for the old site, which is a old MS Access .mdb whereas the new app will be using sql server 2008.
I would greatly appreciate it if someone could give me some examples of how to connect to the access db, aswell as how to execute sql queries (i am fine writing the sql, just got no idea how to execute against the database from my mvc3 app).
thanks in advance
EDIT: I've not got much experience with the old site, but it appears to use the JET adaptor if that helps! ;-)
Your question requires an answer too extensive to be given in detail
I will give you a check list of things and class to research
Define the connection string used to reach your database [see
here]
Create and open the OleDbConnection
Define your OleDbCommand and the command text to be executed
Create and use an OleDbDataReader to read your data line by line
Create and use an OleDbDataAdapter to read your data and load a
DataSet or DataTable
Now don't forget to close your connection and use parametrized query
string connectionString = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
public void InsertRow(string connectionString, string insertSQL)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OleDbCommand command = new OleDbCommand(insertSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}
I have installed SQLite and am using the wrapper from: http://sqlite.phxsoftware.com/
I have created my database and table in the server explorer in VS2010 but when I create the connection, I don't understand what to do from there and how to get it to work.
Can someone provide code examples on how to connect to a db, get a table, insert data into the table and select data from a table and output it.
I would really appreciate it.
Thanks
Server Explorer is overkill, SQLite is meant to be simple and light. Just use plain code as follows.
SQLiteConnection connection = new SQLiteConnection("Data source=PATH_TO_YOUR_DB;Version=3");
connection.Open();
SQLiteCommand command = connection.CreateCommand();
command.CommandText = "insert into something values (1,2,3)";
command.ExecuteNonQuery();
connection.Close();
Hope it helps.
OK here is what I did (assuming that you have that s**t installed):
1.-right click on server explorer
2.-then click on add conection
3.-on data source click Change then select sqlite
4.-fill out da details
5.-you are done... you can now add datasets....