XLWorkbook only saving first row of data from an SQL Query - c#

I am trying to use C# to get data from MySql database and export that data into Excel. For some reason, I am only getting the first row of data. I am not sure what is wrong. Below is my code:
public void MySqlConnectionHandler(string SQL_QUERY)
{
try
{
ConnectionString = " SERVER = some_ip_address;"
+ "DATABASE = database ;"
+ "UID=user;"
+ "PASSWORD=password";
connection = new MySqlConnection(ConnectionString);
MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
dataAdapter.SelectCommand = new MySqlCommand(SQL_QUERY,connection);
DataTable dbdataset = new DataTable();
dataAdapter.Fill(dbdataset);
XLWorkbook wb = new XLWorkbook();
wb.Worksheets.Add(dbdataset, "myworktable");
wb.SaveAs("myworktable.xlsx");
MessageBox.Show("Connected");
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message, "MySQL Query Failure");
}
}
static void Main(string[] args)
{
AggAutomation agg = new AggAutomation();
agg.MySqlConnectionHandler("SELECT * FROM data_base;");
}

Resolved. It was a silly mistake. The datatable that I was reading in actually only had one data point

Related

C# Oracle SQL Parameter binding to variable?

I want to bind a variable in a c# oracle SQL parameter. But it doesn't bind. I checked the return from the messagebox, but I still can't get the variable value. If you comment the adapter part, an error appears.
string sql = "SELECT * FROM ITSTEMP WHERE TO_CHAR(WEEK,'YYYYMMDD') = :DTTM";
OracleDataAdapter adapter = new OracleDataAdapter(sql, DBHelper.DBConn);
DataTable date_table = new DataTable();
adapter.SelectCommand.Parameters.Add(new OracleParameter("DTTM", dateTimePicker3.Text));
MessageBox.Show(sql);
try
{
adapter.Fill(date_table);
dataGridView1.DataSource = date_table;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
enter image description here
string sql = "SELECT * FROM ITSTEMP WHERE TO_CHAR(WEEK,'YYYYMMDD') = :DTTM";
OracleDataAdapter adapter = new OracleDataAdapter(sql, DBHelper.DBConn);
DataTable date_table = new DataTable();
//adapter.SelectCommand.Parameters.Add(new OracleParameter("DTTM", dateTimePicker3.Text));
MessageBox.Show(sql);
try
{
adapter.Fill(date_table);
dataGridView1.DataSource = date_table;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
enter image description here
How do I bind?

External table not in expected format

I know this question have been asked couple of times here but I followed the suggestions and still getting an error : External table is not in expected format.
My application has DataGrid that displays properly the excel file content and when I refresh the DataGrid it shows added row in excel file.But when I open the excel file to check if the row is added ,it's not-no new row is saved.
I'd appreciate your help.
My Wpf application has a connection string in App.config:
add name="ExcelConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=excel_file\\events2.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES""
I'm using OLEDB to connect with excel file:
public Events()
{
InitializeComponent();
System.Data.OleDb.OleDbConnection excelConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
var connectionString = ConfigurationManager.ConnectionStrings["ExcelConnectionString"].ToString();
excelConnection = new System.Data.OleDb.OleDbConnection(connectionString);
try
{
String sql = null;
excelConnection.Open();
myCommand.Connection = excelConnection;
sql = "Select * from [events$]";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
System.Data.OleDb.OleDbDataAdapter dataAdp = new System.Data.OleDb.OleDbDataAdapter(myCommand);
DataTable dt = new DataTable("events");
dataAdp.Fill(dt);
dgData.ItemsSource = dt.DefaultView;
dataAdp.Update(dt);
excelConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
excelConnection.Close();
}
}

How to get changes to dataset and save changes to database

I have a program that reads data from database and displays it onto spreadsheetcontrol(devexpress).
I would like your help in enabling the program to get changes to the dataset on button_click, and then save it back into the database.
Thanks
here is a snippet of the code
mentwall_DataDataSet ds = new mentwall_DataDataSet();
mentwall_DataDataSetTableAdapters.DATABASETableAdapter databaseAdapter = new mentwall_DataDataSetTableAdapters.DATABASETableAdapter();
databaseAdapter.Fill(ds.DATABASE);
dv = new DataView(ds.DATABASE);
mentwall_DataDataSet ds2 = new mentwall_DataDataSet();
mentwall_DataDataSetTableAdapters.RegsTableAdapter regsAdapter = new mentwall_DataDataSetTableAdapters.RegsTableAdapter();
regsAdapter.Fill(ds2.Regs);
dv2 = new DataView(ds2.Regs);
This binds the data source
Worksheet worksheet = workbook.Worksheets[2];
worksheet.DataBindings.BindToDataSource(dv, 1, 0);
Worksheet worksheet2 = workbook.Worksheets[3];
worksheet2.DataBindings.BindToDataSource(dv2, 1, 0);
I have done exactly the same, an application which shows content of a SQL table in a DevExpress Grid Control ( Windows Forms ) and when i click save button all changes ( including new rows added or deleted rows ) are persisted to the SQL Server database, here is a snippet of my DAL class which handles the database logic of saving:
the main point here is to use the SqlCommandBuilder class, which must be initialized with at least the select command and then all other commands are generated automatically, I have written this code > 5 years ago and i still use this app daily.
public int UpdateSQLDataTable(string connectionString, string TableName, DataTable dtSource)
{
try
{
using (SqlConnection sConn = new SqlConnection(connectionString))
{
sConn.Open();
var transaction = sConn.BeginTransaction();
try
{
var command = sConn.CreateCommand();
command.Transaction = transaction;
command.CommandText = $"SELECT TOP 1 * FROM {TableName} WITH (NOLOCK)";
command.CommandType = CommandType.Text;
// timeoput of 5 minutes
command.CommandTimeout = 300;
SqlDataAdapter sAdp = new SqlDataAdapter(command);
SqlCommandBuilder sCMDB = new SqlCommandBuilder(sAdp);
int affectedRecords = sAdp.Update(dtSource);
transaction.Commit();
return affectedRecords;
}
catch (Exception /* exp */)
{
transaction.Rollback();
throw;
}
}
}
catch (Exception exc)
{
Logger logger = new Logger();
logger.Error(string.Format("connectionString: '{0}', TableName: '{1}'", connectionString, TableName), exc);
return int.MinValue;
}
}

SQL Query With Scalar Variable Do Not Populate The Datagridview

I have this datadridview that display data in a SQL database table. In here I have used a SQLDataAdapter and a DataTable(). Please refer the below code snippet.
private void btnSrcDataID_Click(object sender, EventArgs e)
{
try
{
dgvInsertInfo.Refresh();
SqlComm = new SqlCommand();
SqlComm.Connection = SqlConn;
SqlComm.CommandText = ("SELECT * FROM MyDataTable WHERE DataID = #SDataID");
SqlComm.Parameters.AddWithValue("#SDataID", txtDataID.Text);
SqlDataTable = new DataTable();
SqlAdapt = new SqlDataAdapter(SqlComm);
//DataSet dsQryDataId = new DataSet();
SqlAdapt.Fill(SqlDataTable);
//Passing data to DatagridView
dgvInsertInfo.DataSource = SqlDataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I think the issue is with either the SQL QueryString or SqlAdapt.Fill(), but I cannot understand the issue. Could you please someone help me on this.
Thanks,
Chiranthaka
Actually in my case the error occurred due to a typo error when passing the value to the Scalar variable #SDataID. So that the SQL statement's syntax is correct. Please refer the correct SQL statement below.
private void btnSrcDataID_Click(object sender, EventArgs e)
{
try
{
dgvInsertInfo.Refresh();
SqlComm = new SqlCommand();
SqlComm.Connection = SqlConn;
SqlComm.CommandText = "SELECT * FROM MyDataTable WHERE (DataID LIKE #SDataID)";
SqlComm.Parameters.AddWithValue("#SDataID", txtSrcDataID.Text);
SqlDataTable = new DataTable();
SqlAdapt = new SqlDataAdapter(SqlComm);
SqlAdapt.Fill(SqlDataTable);
dgvInsertInfo.DataSource = SqlDataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now the data is populating correctly in the DataGridView.
Thanks.

SqlDataAdapter.Update or SqlCommandBuilder not working

I have a form with a datagrid, which is populated wih data from a sqlserver database. The datagrid populates fine but I am having trouble posting back the changes made by the user, to the table in the sql database. My forms code is as follows:
public partial class frmTimesheet : Form
{
private DataTable tableTS = new DataTable();
private SqlDataAdapter adapter = new SqlDataAdapter();
private int currentTSID = 0;
public frmTimesheet()
{
InitializeComponent();
}
private void frmTimesheet_Load(object sender, EventArgs e)
{
string strUser = cUser.currentUser;
cMyDate cD = new cMyDate(DateTime.Now.ToString());
DateTime date = cD.GetDate();
txtDate.Text = date.ToString();
cboTSUser.DataSource = cUser.GetListOfUsers("active");
cboTSUser.DisplayMember = "UserID";
cboTSUser.Text = strUser;
CheckForTimeSheet();
PopulateTimeSheet();
}
private void CheckForTimeSheet()
{
string strUser = cboTSUser.Text;
cMyDate cD = new cMyDate(txtDate.Text);
DateTime date = cD.GetDate();
int newTSID = cTimesheet.TimeSheetExists(strUser, date);
if (newTSID != this.currentTSID)
{
tableTS.Clear();
if (newTSID == 0)
{
MessageBox.Show("Create TimeSheet");
}
else
{
this.currentTSID = newTSID;
}
}
}
private void PopulateTimeSheet()
{
try
{
string sqlText = "SELECT EntryID, CaseNo, ChargeCode, StartTime, FinishTime, Units " +
"FROM tblTimesheetEntries " +
"WHERE TSID = " + this.currentTSID + ";";
SqlConnection linkToDB = new SqlConnection(cConnectionString.BuildConnectionString());
SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
SqlDataAdapter adapter = new SqlDataAdapter(sqlCom);
adapter.SelectCommand = sqlCom;
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Fill(tableTS);
dataTimesheet.DataSource = tableTS;
}
catch (Exception eX)
{
string eM = "Error Populating Timesheet";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
private void txtDate_Leave(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void cboTSUser_DropDownClosed(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void dataTimesheet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
adapter.Update(tableTS);
}
catch (Exception eX)
{
string eM = "Error on frmTimesheet, dataTimesheet_CellValueChanged";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
}
No exception occurs, and when I step through the issue seems to be with the SqlCommandBuilder which does NOT build the INSERT / UPDATE / DELETE commands based on my gien SELECT command.
Can anyone see what I am doing wrong?
What am I missing?
You need to set the UpdateCommand instead of SelectCommand on update:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The question is old, but the provided answer by#Anurag Ranjhan need to be corrected.
You need not to write the line:
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
and enough to write:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
//remove the next line
//adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The Sql update/insert/delete commands are auto generated based on this line
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
You can find the generated update sql by executing the line:
sqlBld.GetUpdateCommand().CommandText;
See the example How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET
The problem said by OP can be checked by reviewing the Sql Statement sent by the client in SQl Server Profiler.

Categories