Sqlite import to database with button click Winform

Booney 166 Reputation points
2021-04-08T21:38:26.78+00:00

I am in need to import an Excel file into a Sqlite Table by clicking a button.
Use open file dialog select file and insert into table. I searched the Net with
no clear answer. Can someone send me a link or code sniplet?
Thanks

Developer technologies Windows Forms
SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Daniel Zhang-MSFT 9,651 Reputation points
    2021-04-09T06:20:33.467+00:00

    Hi Booney-3048,
    First, you can use OpenFileDialog to choose file and load data into datatable.
    Then you can traverse the datatable and insert each row of data into the Sqlite table.
    I made a test via sql server, and you can use Microsoft.Data.SQLite instead of my System.Data.SqlClient.
    Here is my test code you can refer to.

    DataTable data;  
       
    public void FileSelect()  
    {  
        string filePath = string.Empty;  
        string fileExt = string.Empty;  
        OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file  
        file.Filter = "Discovery Excel|*.xlsx| CSV (Coming Soon)| *.csv";  
        file.Title = "Please select a valid data file";  
      
        if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) //if there is a file choosen by the user    
        {  
            filePath = file.FileName; //get the path of the file    
            fileExt = Path.GetExtension(filePath); //get the file extension   
            if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0)  
            {  
                try  
                {  
                    //load excle data to datatable  
                    Workbook workbook = new Workbook();  
                    workbook.LoadFromFile(filePath);  
                    Worksheet sheet = workbook.Worksheets[0];  
                    data = sheet.ExportDataTable();  
      
                }  
                catch (Exception ex)  
                {  
                    MessageBox.Show(ex.Message.ToString()); ;  
                }  
            }  
            else  
            {  
                MessageBox.Show("Please choose .xlsx or .CSV file only.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); //custom messageBox to show error    
            }  
        }  
                 
        if (data != null && data.Rows.Count > 0)   
        {  
            string connStr ="my connectionString";  
            using (SqlConnection conn = new SqlConnection(connStr))  
            {  
                conn.Open();  
                foreach (DataRow row in data.Rows) //iterate over all rows  
                {  
                    string str = "insert into test(Id,Name) values(@Id,@Name)";  
                    var com = new SqlCommand(str, conn);  
                    com.Parameters.AddWithValue("@Id", Convert.ToInt32(row.Field<string>("Id")));  
                    com.Parameters.AddWithValue("@Name", row.Field<string>("Name"));  
      
                    com.ExecuteNonQuery();  
                    MessageBox.Show("added");  
                }  
            }  
        }  
                  
                  
    }  
      
    private void button1_Click(object sender, EventArgs e)  
    {  
        FileSelect();  
    }  
    

    And FrankM provided a code example via SQLite.
    Beside, here are also some code example you can refer to.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Booney 166 Reputation points
    2022-03-01T18:24:01.287+00:00

    This solved my problem

    private void btn_Upload_Click(object sender, EventArgs e)
            {
                string constring = "Data Source = Document.db; Version=3";
                using (SQLiteConnection con = new SQLiteConnection(constring))
                {
                    con.Open();
    
                    using (var transaction = con.BeginTransaction())
                    using (var command = con.CreateCommand())
    
                    {
                        foreach (DataGridViewRow row in dataGridView1.Rows)
    
                        {
    
                            using (SQLiteCommand cmd = new SQLiteCommand("INSERT INTO Import_Data VALUES(@Id,@Item,@Name" +
                            ",@Feed_Location,@Sub)", con))
                            {
                                cmd.Parameters.AddWithValue("@Id", row.Cells["Column0"].Value);
                                cmd.Parameters.AddWithValue("@Item", row.Cells["Column1"].Value);
                                cmd.Parameters.AddWithValue("@Name", row.Cells["Column2"].Value);
                                cmd.Parameters.AddWithValue("@Feed_Location", row.Cells["Column3"].Value);
                                cmd.Parameters.AddWithValue("@Sub", row.Cells["Column4"].Value);
    
                                cmd.ExecuteNonQuery();
    
                            }
                        }
                        transaction.Commit();
                    }
                    con.Close();
                }
    
                MessageBox.Show("Successful Saved", "Data Inserted", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.