Finisar.SQLite.SQLiteException: SQL logic error or missing database: - database

hello i have a sqlite database, i hhave a table called Archive inside, but using my code it is saying Finisar.SQLite.SQLite Ex ception: SQL logic er ror or missing database:
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SQLiteConnection cn = new SQLiteConnection(#"Data Source=./database.db;Version=2;New=False;Compress=True;");
this.dataGridView1.SelectionMode =
DataGridViewSelectionMode.FullRowSelect;
SQLiteDataAdapter da = new SQLiteDataAdapter("SELECT * FROM Archive", cn);
try
{
cn.Open();
da.Fill(DT);
this.dataGridView1.DataSource = DT;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
cn.Close();

Related

Save excel file in database using c#

I have an excel file. Now I need to save data of excel file in database. What is the simplest way to do that using c# with simple example? Thank in advance
This will do what you want.
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\your_path\\Import_List.xls;Extended Properties=Excel 8.0;");
ExcelConnection.Open();
string expr = "SELECT * FROM [Sheet1$]";
OleDbCommand objCmdSelect = new OleDbCommand(expr, ExcelConnection);
OleDbDataReader objDR = null;
SqlConnection SQLconn = new SqlConnection();
string ConnString = "Data Source=Your_Database_Name;Initial Catalog=Table_Name;Trusted_Connection=True;";
SQLconn.ConnectionString = ConnString;
SQLconn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLconn))
{
bulkCopy.DestinationTableName = "tblTest";
try
{
objDR = objCmdSelect.ExecuteReader();
bulkCopy.WriteToServer(objDR);
ExcelConnection.Close();
//objDR.Close()
SQLconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
To copy from a SQL Server table to an Excel file, try the following.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
Or, with a 'Where' clause, you can have more control of the output.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Update [Sheet1$] set name = 'New Name' where id=1";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

Pass operation from user control to Worker_DoWork in other window

I am just new woking with ProgressBar in WPF. I have a user control like this:
public partial class Import : UserControl
{
public Import()
{
InitializeComponent();
}
private void filePickerButton_Click(object sender, RoutedEventArgs e)
{
// Create the OpenFIleDialog object
Microsoft.Win32.OpenFileDialog openPicker = new Microsoft.Win32.OpenFileDialog();
// Add file filters
// We are using excel files in this example
openPicker.DefaultExt = ".xslt";
openPicker.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
// Display the OpenFileDialog by calling ShowDialog method
Nullable<bool> result = openPicker.ShowDialog();
// Check to see if we have a result
if (result == true)
{
// Application now has read/write access to the picked file
filePathTextBox.Text = openPicker.FileName.ToString();
}
}
private void btn_Import_Click(object sender, RoutedEventArgs e)
{
//import all data from excel file to datatable
Workbook wb = new Workbook(filePathTextBox.Text);
// Accessing the worksheet in the Excel file
Worksheet worksheetPro = wb.Worksheets[1];
Worksheet worksheetCat = wb.Worksheets[0];
// Exporting all data by ExportDataTable
DataTable dataTablePro = worksheetPro.Cells
.ExportDataTable(1, 0, worksheetPro.Cells.Rows.Count - 1, worksheetPro.Cells.Columns.Count, false);
DataTable dataTableCat = worksheetCat.Cells
.ExportDataTable(1, 0, worksheetCat.Cells.Rows.Count - 1, worksheetCat.Cells.Columns.Count, false);
//dump data from datatable to SQL server
string connectionString = #"Data Source=DESKTOP-L6OBVA4\SQLEXPRESS;Initial Catalog=QLDB;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
//mapping columns of Datatable with the name of DB
bulkCopy.ColumnMappings.Add(dataTablePro.Columns[0].ColumnName, "Tên");
bulkCopy.ColumnMappings.Add(dataTablePro.Columns[1].ColumnName, "Giá");
bulkCopy.ColumnMappings.Add(dataTablePro.Columns[2].ColumnName, "Số Lượng");
bulkCopy.ColumnMappings.Add(dataTablePro.Columns[3].ColumnName, "Miêu Tả");
//set the destination table name in DB will be affected
bulkCopy.DestinationTableName = "dbo.Products";
try
{
//coppy all rows from nominated datatable and dump it to DB
bulkCopy.WriteToServer(dataTablePro);
dataTablePro.Clear();
using (SqlBulkCopy bulkCopyCat = new SqlBulkCopy(connection))
{
bulkCopyCat.ColumnMappings.Add(dataTableCat.Columns[0].ColumnName, "Loại");
bulkCopyCat.DestinationTableName = "dbo.Categories";
bulkCopyCat.WriteToServer(dataTableCat);
dataTableCat.Clear();
MessageBox.Show("Success!!!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
The purpose of this user control is: Choose an excel file, then import all data to datatable, finally, dump all data to SQL server. I need to make a processing bar for operation of dumping from datatable to SQL server cause I think it takes long time. So next thing, I create a Process bar window:
public partial class ProgressBar : Window
{
public ProgressBar()
{
InitializeComponent();
}
private void Window_ContentRendered(object sender, EventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.ProgressChanged += worker_ProgressChanged;
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
(sender as BackgroundWorker).ReportProgress(i);
//do my operation here
}
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbStatus.Value = e.ProgressPercentage;
}
}
you can see above snippet code, I have a method named:
worker_DoWork()
it is where I plan to put my operation. And the last thing, I want to take these code lines from user control then put it into worker_DoWork() cause I think these lines take time to handle:
try
{
//coppy all rows from nominated datatable and dump it to DB
bulkCopy.WriteToServer(dataTablePro);
dataTablePro.Clear();
using (SqlBulkCopy bulkCopyCat = new SqlBulkCopy(connection))
{
bulkCopyCat.ColumnMappings.Add(dataTableCat.Columns[0].ColumnName, "Loại");
bulkCopyCat.DestinationTableName = "dbo.Categories";
bulkCopyCat.WriteToServer(dataTableCat);
dataTableCat.Clear();
MessageBox.Show("Success!!!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
what should I do to get it? I heard about delegate and event can give me a choice but i could not find it out by myself. Thanks!
If you do not care about multiple instances of progress dialog. Then try something like this:
Import.xaml:
<Grid>
<Button x:Name="filePicker" Content="ClickMe" Click="filePicker_Click" DockPanel.Dock="Top"/>
<ProgressBar x:Name="progressBar" Minimum="0" Maximum="100" Value="75" DockPanel.Dock="Top" Visibility="Collapsed" />
</Grid>
Import.xaml.cs:
private void filePicker_Click(object sender, RoutedEventArgs e)
{
progressBar.Visibility = Visibility.Visible;
// here you call your batch code
var task = new Task(() => Thread.Sleep(3000));
// after task is done hide progress dialog
task.ContinueWith(x => Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.progressBar.Visibility = Visibility.Collapsed)));
task.Start();
}
(I did not bother with updating the status. It is always 75%.).

How do I export data from a datagridview/data set into an Access Database? [C#]

So my title is pretty self explanatory, so thus far I have read Microsofts Documentation and watched some Youtube videos regarding my issue here.
Firstly my project code here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
foreach (DataRow r in dsEquipment.Tables[0].Rows)
{
DataRow dr = sQTDBDataSet.tblEquipment.NewRow();
dr[0] = r[0];
dr[1] = r[1];
dr[2] = r[2];
dr[3] = r[3];
dr[4] = r[4];
dr[5] = r[5];
dr[6] = r[6];
dr[7] = r[7];
dr[8] = r[8];
dr[9] = r[9];
dr[10] = r[10];
dr[11] = r[11];
dr[12] = r[12];
dr[13] = r[13];
dr[14] = r[14];
dr[15] = r[15];
dr[16] = r[16];
sQTDBDataSet.tblEquipment.Rows.Add(dr);
}
//tblEquipmentTableAdapter.Update(sQTDBDataSet.tblEquipment);
//tableAdapterManager.UpdateAll(sQTDBDataSet);
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
this.Validate();
this.tblEquipmentBindingSource.EndEdit();
this.tblEquipmentTableAdapter.Update(this.sQTDBDataSet.tblEquipment);
MessageBox.Show("Update successful");
}
catch (System.Exception ex)
{
MessageBox.Show("Update failed");
}
}
private void btnReadExcel_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
if (OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = OFD.FileName;
txtFileName.Text = strfilename;
}
}
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void tblEquipmentBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.tblEquipmentBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.sQTDBDataSet);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'sQTDBDataSet.tblEquipment' table. You can move, or remove it, as needed.
this.tblEquipmentTableAdapter.Fill(this.sQTDBDataSet.tblEquipment);
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
try
{
// Establish connection between the c# application and the excel file.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + txtFileName.Text + ";Extended Properties=Excel 12.0");
// Reading the data from the excel file.
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Equipments$]", con);
// All data from the file will be loaded into the dataset.
da.Fill(dsEquipment);
// Show in a message box how many rows of data there is.
//MessageBox.Show(dsEquipment.Tables[0].Rows.Count.ToString());
// Show the data in the data grid view.
dgEquipment.DataSource = dsEquipment.Tables[0];
}
catch
{
MessageBox.Show("Please select the SQT2 Excel sheet.");
}
}
}
}
So my first attempt at tackling the problem was this:
//tblEquipmentTableAdapter.Update(sQTDBDataSet.tblEquipment);
//tableAdapterManager.UpdateAll(sQTDBDataSet);
I get no errors but for some reason my Access Database is not showing the updates.
My second attempt was the following:
private void btnOpenFile_Click(object sender, EventArgs e)
{
try
{
// Establish connection between the c# application and the excel file.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + txtFileName.Text + ";Extended Properties=Excel 12.0");
// Reading the data from the excel file.
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Equipments$]", con);
// All data from the file will be loaded into the dataset.
da.Fill(dsEquipment);
// Show in a message box how many rows of data there is.
//MessageBox.Show(dsEquipment.Tables[0].Rows.Count.ToString());
// Show the data in the data grid view.
dgEquipment.DataSource = dsEquipment.Tables[0];
}
catch
{
MessageBox.Show("Please select the SQT2 Excel sheet.");
}
}
Which was a seperate button and I obtained this code from Microsofts documentation and changed the variables of the dataset and the database table, no errors... yet STILL my access database is not updating!
Completely stuck right now and any help is appreciated! :)
Thank you!

Failing to connect to SQL Server from C#

I am trying to import excel file into SQL Server 2005 in C#, but I', getting an error.
Here's my code:
namespace excel
{
public partial class Csharp_Excel : Form
{
public Csharp_Excel()
{
InitializeComponent();
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
private void button1_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
path = Path.Combine(path, "csharp-Excel.xls");
string connStr = #"Server=.\\SQLEXPRESS;Data Source= C:\\Users\\adil pc\\Documents\\Visual Studio 2008\\Projects\\excel\\excel\\bin\\Debug\\csharp-Excel.xls;Initial Catalog=RMS;Integrated Security=SSPI;";
SqlConnection con = new SqlConnection(connStr);
string strCmd = "select * from [sheet1$A1:E7]";
SqlCommand cmd = new SqlCommand(strCmd, con);
try
{
con.Open();
ds.Clear();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
}
}
private void btnsend_Click(object sender, EventArgs e)
{
}
}
The error that I am getting is:
System.Data.SqlClient.SqlException: A network-related or instance-specified error occurred while establishing a connection to SQL Server
I think I got it working I made some changes in connection string :
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\csharp-Excel.xls;Extended Properties=\"Excel 8.0;HDR=Yes;\";
it is working on demo havent implement in actual project once I do will update.

Why do I get an exception when I reference DataGridView CurrentRow?

I'm trying to get a "changed currentcell" event in DataGridView, but every time I try to load the form (which is a child of another form), I get an exception in the datagridview_currentcell event:
SystemNullReferenceException: object not set to an instance of an object.
I guess it's because I haven't selected any row. Of course I can use catch and try to bypass, but I want a more elegant way and to know what am I doing wrong.
Here's my code:
Form2.CS:
namespace AsefotSystem
{
public partial class ownerReport : Form
{
public ownerReport()
{
InitializeComponent();
loadDB();
setGrid();
}
private void loadDB()
{
string connetionString = null;
OleDbConnection connection;
OleDbDataAdapter oledbAdapter;
DataSet ds = new DataSet();
string sql2 = null;
connetionString = ConfigurationManager.ConnectionStrings["RiskDB"].ConnectionString;
sql2 = "select * From tbl2_asefot";
connection = new OleDbConnection(connetionString);
try
{
connection.Open();
oledbAdapter = new OleDbDataAdapter(sql2, connection);
oledbAdapter.Fill(ds, "Asefot");
oledbAdapter.Dispose();
connection.Close();
dsAsefotGrid = ds;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void setGrid()
{
Controls.Add(dataGridView1);
dataGridView1.DataSource = dsAsefotGrid.Tables[0];
}
private void dataGridView1_CurrentCell(object sender, EventArgs e)
{
try
{
textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString();
textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
DataSet dsAsefotGrid;
}
}
Form2.Designer.CS:
this.dataGridView1.CurrentCellChanged += new System.EventHandler(this.dataGridView1_CurrentCell);
Instead of the try{} catch{}, you could test if the CurrentCell or even CurrentRow is not null.
if(dataGridView1.CurrentCell != null)
{
textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString();
textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
}
Your dataGridView Cell has no value and you are trying to save a string of null.
Try catching the exception and inform the user that he has to write something in the cell
try
{
textBox1.Text = dataGridView1.Rows[dataGridView1.
CurrentRow.Index].Cells[2].Value.ToString();
}
catch(NullReferenceException)
{
MessageBox.Show("You cannot process an empty cell");
}
Please find more information under the following link:

Resources