Displaying data from a oracle sql table graphically - c#

I have programmatically created a chart using ASP.Net, now I just need to figure out how to connect to an oracle sql developer database and retrieve the data to populate the chart.
Would I use an OleDb method (see below), along with some other logic?
using System.Data.OleDb;
OleDbConnection myConnection = new OleDbConnection;();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
myConnection.Close();
Any help would be great.

http://justins-fat-tire.blogspot.com/
I've got some code examples that show how to use a stored procedure to fill a dataset/table and get a generic List of object data. If you're using raw sql you will need to modify the command object a bit.

You would use a DataTable as the data source for the chart. To do this, you first need to populate the table.
public void Populate()
{
Datatable data = GetData();
foreach(DataRow r in data.Rows)
{
/// Populate chart using data
}
}
public DataTable GetData()
{
try
{
OleDbConnection myConnection = new OleDbConnection;();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
OleDbCommand myCommand = myConnection.CreateCommand();
//Set commandtype and text here.
myCommand.CommandType = SOMETYPE;
myCommand.CommandText = "SOMETEXT";
OleDbDataReader reader = myCommand.ExecuteReader();
DataTable t = new DataTable();
t.Load(reader);
return t;
}
catch (Exception e)
{
throw e;
}
finally
{
myConnection.Close();
}
}

Related

How to copy Access table to SQL table in C#?

As title says I've used odbcconnection to sqlconnection and for the life of me cant get it to work.. Copied a bunch of code from this site but cant get them both to work.
The program just hangs so maybe I am doing something wrong, but would appreciate maybe a bare bones template that i could just fill in the connection details and bulk copy the table to table..
using (OdbcConnection myConnection = new OdbcConnection())
{
string myConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=//####/data/Toronto/wrkgrp/wrkgrp30/Business Risk Oversight and Control/DATA INTEGRITY/CDE/CDE Testing Portal Requirements/Migration Requirements/RCM/Mutual Funds/Mutual Funds.mdb;";
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
OdbcCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM RCM_MF_New_Accounts_Samples";
OdbcDataReader reader = cmd.ExecuteReader(); // close conn after complete
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
//myConnection.Close();
string destinationConnectionString = "Data Source=####;Initial Catalog=DYOF_STAGING_BROC;User ID=;Password=;Connection Timeout=999";
SqlConnection destination = new SqlConnection(destinationConnectionString);
SqlBulkCopy bulkData;
//destination.Open();
Exception ex = null;
try
{
Console.WriteLine("step1");
bulkData = new SqlBulkCopy(destinationConnectionString, SqlBulkCopyOptions.FireTriggers);
bulkData.BulkCopyTimeout = 1;
bulkData.DestinationTableName = "Load_CTR_Sample_Account_Opening2";
bulkData.WriteToServer(myDataTable);
bulkData.Close();
Console.WriteLine("moved from here to there");
reader.Close();
//destination.Close();
}
catch (Exception e)
{
ex = e;
}
I actually wrote an ORM to make this kind of task easier.
var accessDS = new AccessDataSource(connectionString1);
var dt = accessDS.From("RCM_MF_New_Accounts_Samples").ToDataTable().Execute();
var sqlDS = new SqlServerDataSource(connectionString2);
sqlDS.InsertBulk("Load_CTR_Sample_Account_Opening2", dt).Execute();
This does not work for .NET Core.
Packages:
https://www.nuget.org/packages/Tortuga.Chain.Access/
https://www.nuget.org/packages/Tortuga.Chain.SqlServer
Read the data from Access into a DataTable:
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;data source=D:\Temp\MyDB.accdb";
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(strConnect))
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM MyTable", con);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
Then use SqlBulkCopy to update SQL:
string strConnect = #"Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlBulkCopy bulk = new SqlBulkCopy(con))
{
bulk.DestinationTableName = "Test";
bulk.WriteToServer(dt);
}
}
Of course, there is a much easier way to go straight from Access to SQL Server, using VBA, SQL , or other methods.
https://support.office.com/en-us/article/import-or-link-to-data-in-an-sql-server-database-a5a3b4eb-57b9-45a0-b732-77bc6089b84e
https://www.sqlshack.com/six-different-methods-to-copy-tables-between-databases-in-sql-server/
Here's a basic example of bulk insert.
public void BulkInsert(DataTable employees)
{
if (employees == null)
throw new ArgumentNullException(nameof(employees), $"{nameof(employees)} is null.");
using (var con = OpenConnection())
using (var sbc = new SqlBulkCopy(con))
{
sbc.DestinationTableName = "HR.Employee";
foreach (DataColumn column in employees.Columns)
sbc.ColumnMappings.Add(column!.ColumnName, column.ColumnName);
sbc.WriteToServer(employees);
}
}
Note the foreach (DataColumn column in employees.Columns) loop. This is required so that it knows the column names are the same in the source and the target table. (If they're not the same, manually map them in the same fashion.)
Source: https://grauenwolf.github.io/DotNet-ORM-Cookbook/BulkInsert.htm#ado.net
Following option need to verify
1) Column Name should be the same.
2) verify the column length.
3) verify the data type.

Autocomplete in a ComboBox Using Access 2017

I want to make Autocomplete in a ComboBox using Access 2017. So I used this code... But there are some errors, like:
"The name 'da' does not exist in the current context".
Please help me to fix this error.
private void Autocomplete()
{
string query;
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb");
//opening connection
con.Open();
try
{
//initialize a new instance of sqlcommand
OleDbCommand cmd = new OleDbCommand();
//set a connection used by this instance of sqlcommand
cmd.Connection = con;
//set the sql statement to execute at the data source
cmd.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter();
//set the sql statement or stored procedure to execute at the data source
da.SelectCommand = cmd;
//initialize a new instance of DataTable
DataTable dt = new DataTable();
//add or resfresh rows in the certain range in the datatable to match those in the data source.
da.Fill(dt);
foreach (DataRow r in dt.Rows)
{
//getting all rows in the specific field|Column
var rw = r.Field<string>("IMEI");
//Set the properties of a combobox to make it auto suggest.
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
//adding all rows into the combobox
comboBox1.AutoCompleteCustomSource.Add(rw);
}
}
catch (Exception ex)
{
//catching error
MessageBox.Show(ex.Message);
}
//release all resources used by the component
da.Dispose();
//clossing connection
con.Close();
}
Your OleDbDataAdapter da = new OleDbDataAdapter(); is within try { } scope and
da.Dispose(); is outside of that scope, try to place this line within try { } scope or move OleDbDataAdapter da = new OleDbDataAdapter(); outside of try { }scope.
Your OleDbDataAdapter is declare inside the try block, it doesn't exist outside of it, hence the error you're seeing.
The query string presented here is empty.
When you deal with OleDb objects, it's common practice to make use
of using blocks, which take care of disposing the disposable objects you create.
What you rally don't want, is to set those controls properties inside a foreach loop.
It is also more efficient to fill the ComboBox AutoCompleteCustomSource using AddRage(), instead of adding objects one by one.
This is how I propose to edit your code:
// You can set these properties in the Form designer
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
// [...]
string query = "SELECT [Some Field] FROM [Some Table] WHERE [Some Condition]";
List<string> data = new List<string>();
try {
using (var con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb"))
{
con.Open();
using (var cmd = new OleDbCommand(query, con))
using (var reader = cmd.ExecuteReader()) {
if (reader.HasRows) {
while (reader.Read()) {
data.Add((string)reader["IMEI"]);
}
}
}
}
}
catch {
// Notify, log, whatever fits
}
comboBox1.AutoCompleteCustomSource.Clear();
comboBox1.AutoCompleteCustomSource.AddRange(data.ToArray());
data.Clear();

How can I get my return value from stored procedure to display on GridView?

I have a return value from the stored procedure GetTeam, and I want it to be displayed in the Gridview. This is what I have, but it is not displaying in the gridview:
protected void getTeam()
{
SqlConnection con;
string CS = Configuration.Manager.ConnectionStrings["TEAM"].ConnectionString;
DataTable dt = new DataTable();
using(con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("GetTeam",con);
SqlDataAdapter da = new SqlAdapter(cmd);
da.fill(dt);
Gridview1.Datasource = dt;
Gridview1.Databind();
}
}
Could anyone help?
Here try this solution below, keep in this solution we are sending a parameter to help narrow our results to specific team.
using (SqlConnection conn = new SqlConnection())
{
//Connection string
conn.ConnectionString = ConnectionString.DataSourceString;
//Create adapter and assign store procedure name
SqlCommand cmmd = new SqlCommand()
{
CommandType = CommandType.StoredProcedure
};
// Assign to Command type
//exception is caught because it cannot find Stored Procedure
//Insert parameters into row from input text
cmmd.CommandText = "GetTeam";
// Send parameter
cmmd.Parameters.AddWithValue("#PGetDayTeam",
ShiftParameterTextBox.Text.Trim());
cmmd.Connection = conn;
try
{
conn.Open();
//If we do not receive any records
GridView2.EmptyDataText = "No Records Found";
GridView2.DataSource = cmmd.ExecuteReader();
GridView2.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close and dispose connection
conn.Close();
conn.Dispose();
}
// select from grid
protected void GridView2_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
GridViewRow row = GridView2.Rows[e.NewSelectedIndex];
string GetTeam = row.Cells[2].Text;
// You can use it in viewstate or what you choose.
ViewState["GetTeam"] = GetTeam;
}
The Fill operation then adds the rows to destination DataTable objects
in the DataSet, creating the DataTable objects if they do not already
exist. When creating DataTable objects, the Fill operation normally
creates only column name metadata. However, if the MissingSchemaAction
property is set to AddWithKey, appropriate primary keys and
constraints are also created.
You're using sql prosedure. So you already have a Colums' name. You don't need to use DataTable. The Sql adapter can fill dataset also. You need to use DataSet first.
public static DataSet ExecuteDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters);
//create the DataAdapter & DataSet
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);
//return the dataset
return ds;
}
Then you can bind your Gridview with that one.
grdView.DataSource = ds;
grdView.DataBind();

insert sql commands by textbox

I created win forms, and I wanna insert sql commands and get data from database. If I put query directly into code sql commands, everything is ok, if I put query by textbox I have a lot of bugs like:
$exception {"Could not find stored procedure 'select * from uczniowie'."}
System.Exception {System.Data.SqlClient.SqlException }
this {MateuszLab4.connectDB} MateuszLab4.connectDB
question "\"select * from uczniowie\"" string
dataTable {} System.Data.DataTable
sqlDataReader null System.Data.SqlClient.SqlDataReader
sqlCommand {System.Data.SqlClient.SqlCommand} System.Data.SqlClient.SqlCommand
Here is my code:
private void buttonSearch_Click(object sender, EventArgs e)
{
string query = textBoxQuery.Text;
connectDB databaseWin = new connectDB("(localdb)\\v11.0", "Mat");
dataGridViewAdvanced.DataSource = databaseWin.DataDownload(query);
}
When I put into string query sql commands (for example string query = "select * from students" ) everything is working very well. If I replaced with data from textbox sth is wrong. Could you give me some tips guys?
here is my class with datadownloada:
public DataTable DataDownload(string question)
{
DataTable dataTable = new DataTable();
SqlDataReader sqlDataReader;
SqlCommand sqlCommand;
sqlCommand = new SqlCommand(question);
sqlCommand.Connection = this.DBconnection;
sqlDataReader = sqlCommand.ExecuteReader();
dataTable.Load(sqlDataReader);
return dataTable;
}
Try this code.
public DataTable DataDownload(string question)
{
using (var ada = new SqlDataAdapter(question, DBconnection))
{
// Use DataAdapter to fill DataTable
DataTable dt = new DataTable();
ada.Fill(dt);
return dt;
}
}

How to connect C# app with SQLite database

I want to connect to a SQLite database. Please show me example code which WORKS. Also I want to link datagridview with the database.I use this code but it doesn't work:
private DataTable dt;
public Form1()
{
InitializeComponent();
this.dt = new DataTable();
}
private SQLiteConnection SQLiteConnection;
private void DataClass()
{
SQLiteConnection = new SQLiteConnection("Data Source=PasswordManager.s3db;Version=3;");
}
private void GetData()
{
SQLiteDataAdapter DataAdapter;
try
{
SQLiteCommand cmd;
SQLiteConnection.Open(); //Initiate connection to the db
cmd = SQLiteConnection.CreateCommand();
cmd.CommandText = "select*from PasswordManager;"; //set the passed query
DataAdapter = new SQLiteDataAdapter(cmd);
DataAdapter.Fill(dt); //fill the datasource
dataGridView1.DataSource = dt;
}
catch(SQLiteException ex)
{
//Add your exception code here.
}
SQLiteConnection.Close();
You could use the System.Data.SQLite ADO.NET provider. Once you download and reference the assembly, it's pretty straightforward ADO.NET code:
using (var conn = new SQLiteConnection(#"Data Source=test.db3"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id FROM foo";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = reader.GetInt32(reader.GetOrdinal("id"));
...
}
}
}
In addition to the answer provided by Darin, there is no "create database" command in SQLite (from what I remember). When you initiate a "SQLiteConnection", if the given database (.db3) does not exist, it automatically creates it... from there, you can then create your tables.

Categories