简体   繁体   中英

insert data in sqlite using dataset in c#

I have one excel sheet from which I am getting data in dataset using OleDbConnection

private static DataSet ImportExcel(string FileName, bool hasHeaders)
        {
            string HDR = hasHeaders ? "Yes" : "No";
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName +
                             ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\"";

            DataSet output = new DataSet();

            using (OleDbConnection conn = new OleDbConnection(strConn))
            {
                conn.Open();

                DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                foreach (DataRow row in dt.Rows)
                {
                    string sheet = row["TABLE_NAME"].ToString();

                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
                    cmd.CommandType = CommandType.Text;

                    DataTable outputTable = new DataTable(sheet);
                    output.Tables.Add(outputTable);

                    new OleDbDataAdapter(cmd).Fill(outputTable);
                }
            }
            return output;
        }

Now I want to Insert data from this dataset to sqlite table.

This is how we can do it

    SQLiteConnection m_dbConnection; 
    void createDbAndTable()
    {
        SQLiteConnection.CreateFile("MyDatabase.sqlite");
        m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite; Version=3;");
        m_dbConnection.Open();
        string sql = "create table myValues (name varchar(20), highScore int)";
        SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
        command.ExecuteNonQuery();
    }

    void fillTable(DataSet ds)
    {
        var dt = ds.Tables[0];

        foreach (DataRow dr in dt.Rows)
        {
            var name = dr["name"].ToString();
            var score = Convert.ToInt32(dr["value"].ToString());
            string sql = "insert into myValues (name, highScore) values ( '" + name + "'," + score + ")";
            SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
            command.ExecuteNonQuery();
        }
        m_dbConnection.Close();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM