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;
}
Related
I'm develop a new project for Medical Laboratory by using visual studio C# WinForms for user interaction and MYSQL for database. After my successful build its running successfully in my windows machine. But the problem is when I install my project on another windows machine, the front end of UI running well but the database throw an error to me. The error is Authentication to host 'localhost' for user 'root' using method 'caching_sha2_password' failed with message: Unknown database 'login'. I think the error was I need to add MYSQL reference in my project. but I'm absolutely don't know how to do it. I'm really sorry to all coz I'm noob in C# and my English.
and literally thanks to all.
public partial class registration : Form
{
string connectionstring = "server = localhost; user id = root; database = login; password =
qwerty;";
MySqlConnection connection = new MySqlConnection(connectionstring);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "ALTER TABLE register ADD UNIQUE INDEX(rgstrid);";
cmd.CommandText = "INSERT IGNORE INTO register(username, password,confirm) VALUES(#username,#password,#confirm)";
cmd.Parameters.Add("#username", MySqlDbType.VarChar).Value = rgstrusrnmtxtbx.Text;
cmd.Parameters.Add("#password", MySqlDbType.VarChar).Value = rgstrpswdtxtbx.Text;
cmd.Parameters.Add("#confirm", MySqlDbType.VarChar).Value = rgstrcnfrmtxtbx.Text;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(table);
if (cmd.ExecuteNonQuery() == 1)
{
MessageBox.Show("Your Account resgistred Successfully", "information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Account saved Successfully","Success",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
You probably need to include a reference to a library to talk to MySql, like the MySql.Data package. Adding it as a nuget reference should ensure the required files are installed with the rest of the application files.
Your installer also needs to install some software. The database engine itself if you are running a local database, but also a .net connector for the ado.net driver.
At least this is how we do it. You might be able to avoid some components depending how you are accessing the database.
When installing the database you should specify the root password. For example by giving the rootpasswd=qwerty parameter to the MySQLInstallerConsole.exe program.
Your install script also needs to setup the database, i.e. either run sql files to create any tables and fill it with data, or copy the database files themselves, or run some program to create the tables.
I am using VS 2012 express coding in C# and have an issue when adding data from a dataset (I use SQL Server CE) to a reportview. My code is this:
private void button1_Click(object sender, EventArgs e)
{
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MySalon.Properties.Settings.MySalonConnectionString"].ToString();
string sql = "SELECT * FROM CUSTOMER_PAYMENTS;";
try
{
con.Open();
da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con)
ds1 = new DataSet();
da.Fill(ds1, "DayRep");
ReportDataSource datasource;
datasource = new ReportDataSource("DayRep", ds1.Tables[0]);
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(datasource);
con.Close();
reportViewer1.LocalReport.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I can see that datasource has the data but report when pressing the button remains blank (There is no error just blank).
Try to add the following line of code:
reportViewer1.LocalReport.ReportEmbeddedResource =
"Your_Name_Of_Project.Name_Of_Your_Report.rdlc";
It should be if you created your own .rdlc report file so to indicate to reportViewer where to take data from.
Also, where is this line of the code?
this.reportViewer1.RefreshReport();
Usually, it is added by the studio (if you code using it). It should be in the end of the code, just in the end of your try block. Anyway, it is "mustHave", without it your report really will remain blank.
Also, it seems to me that you should replace this line of code:
ds1 = new DataSet();
with this one:
ds1 = new DataSet("myDataSet"); //for exmaple, so to make dataSet have some name
and then rewrite this line of code:
datasource = new ReportDataSource("DayRep", ds1.Tables[0]);
with next:
dataSource = new ReportDataSource("myDataSet", ds1.Tables[0] as DataTable);
UPDATE
Well, you have no need to install rdlc teamplate to run and display reports via ReportViewer.
As is told here, (in examples), you may write it like this
// Set Processing Mode
reportViewer.ProcessingMode = ProcessingMode.Local;
// Set RDL file
using (FileStream stream = new FileStream("report1.rdlc", FileMode.Open))
{
reportViewer.LocalReport.LoadReportDefinition(stream);
}
So, the report will be loaded in the repoerViewer. The main problem here is that I have some .rdlc reports, so I can load them now. To create them without template you can use anther approach, so to create them programmatically - maybe this article can help you. Also, take a look here at MSDN.
UPD2
You can take a look at the text version of rdlc report by using this link. But remember that you won't be able to load exactly this rdlc into your reportViewer and see the data you want it to. That .rdlc is only an example, and every report should be created by the developer of the project. The main reason is that .rdlc I have uses DataSet you do not have cause it got data from dataBase you do not have. So, I think the only reason for you to look through this rdlc is only getting acquainted. To create .rdlc reports successfully, you should use approach I told about before. To get more information, you can try search in google "generate a report definition programmatically" or find some opportunity to create reports in IDE's just like Visual Studio.
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 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
I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?
I'm with, Bruce. I AM using http://system.data.sqlite.org/ with great success as well. Here's a simple class example that I created:
using System;
using System.Text;
using System.Data;
using System.Data.SQLite;
namespace MySqlLite
{
class DataClass
{
private SQLiteConnection sqlite;
public DataClass()
{
//This part killed me in the beginning. I was specifying "DataSource"
//instead of "Data Source"
sqlite = new SQLiteConnection("Data Source=/path/to/file.db");
}
public DataTable selectQuery(string query)
{
SQLiteDataAdapter ad;
DataTable dt = new DataTable();
try
{
SQLiteCommand cmd;
sqlite.Open(); //Initiate connection to the db
cmd = sqlite.CreateCommand();
cmd.CommandText = query; //set the passed query
ad = new SQLiteDataAdapter(cmd);
ad.Fill(dt); //fill the datasource
}
catch(SQLiteException ex)
{
//Add your exception code here.
}
sqlite.Close();
return dt;
}
}
There is also an NuGet package: System.Data.SQLite available.
Microsoft.Data.Sqlite by Microsoft has over 9000 downloads every day, so I think you are safe using that one.
Example usage from the documentation:
using (var connection = new SqliteConnection("Data Source=hello.db"))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText =
#"
SELECT name
FROM user
WHERE id = $id
";
command.Parameters.AddWithValue("$id", id);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var name = reader.GetString(0);
Console.WriteLine($"Hello, {name}!");
}
}
}
I've used this with great success:
http://system.data.sqlite.org/
Free with no restrictions.
(Note from review: Original site no longer exists. The above link has a link pointing the the 404 site and has all the info of the original)
--Bruce
There is a list of Sqlite wrappers for .Net at http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers. From what I've heard http://sqlite.phxsoftware.com/ is quite good. This particular one lets you access Sqlite through ADO.Net just like any other database.
There's also now this option: http://code.google.com/p/csharp-sqlite/ - a complete port of SQLite to C#.
https://github.com/praeclarum/sqlite-net is now probably the best option.
Another way of using SQLite database in NET Framework is to use Fluent-NHibernate.
[It is NET module which wraps around NHibernate (ORM module - Object Relational Mapping) and allows to configure NHibernate programmatically (without XML files) with the fluent pattern.]
Here is the brief 'Getting started' description how to do this in C# step by step:
https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started
It includes a source code as an Visual Studio project.
Here I am trying to help you do the job step by step: (this may be the answer to other questions)
Go to this address , down the page you can see something like "List of Release Packages". Based on your system and .net framework version choose the right one for you. for example if your want to use .NET Framework 4.6 on a 64-bit Windows, choose this version and download it.
Then install the file somewhere on your hard drive, just like any other software.
Open Visual studio and your project. Then in solution explorer, right-click on "References" and choose "add Reference...".
Click the browse button and choose where you install the previous file and go to .../bin/System.Data.SQLite.dll and click add and then OK buttons.
that is pretty much it. now you can use SQLite in your project.
to use it in your project on the code level you may use this below example code:
make a connection string:
string connectionString = #"URI=file:{the location of your sqlite database}";
establish a sqlite connection:
SQLiteConnection theConnection = new SQLiteConnection(connectionString );
open the connection:
theConnection.Open();
create a sqlite command:
SQLiteCommand cmd = new SQLiteCommand(theConnection);
Make a command text, or better said your SQLite statement:
cmd.CommandText = "INSERT INTO table_name(col1, col2) VALUES(val1, val2)";
Execute the command
cmd.ExecuteNonQuery();
that is it.
Mono comes with a wrapper, use theirs!
https://github.com/mono/mono/tree/master/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0 gives code to wrap the actual SQLite dll ( http://www.sqlite.org/sqlite-shell-win32-x86-3071300.zip found on the download page http://www.sqlite.org/download.html/ ) in a .net friendly way. It works on Linux or Windows.
This seems the thinnest of all worlds, minimizing your dependence on third party libraries. If I had to do this project from scratch, this is the way I would do it.
if you have any problem with the library you can use Microsoft.Data.Sqlite;
public static DataTable GetData(string connectionString, string query)
{
DataTable dt = new DataTable();
Microsoft.Data.Sqlite.SqliteConnection connection;
Microsoft.Data.Sqlite.SqliteCommand command;
connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source= YOU_PATH_BD.sqlite");
try
{
connection.Open();
command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);
dt.Load(command.ExecuteReader());
connection.Close();
}
catch
{
}
return dt;
}
you can add NuGet Package Microsoft.Data.Sqlite