Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

mysql - C# Inserting a DataSet Into SQL Database

I'm trying to insert a dataset into an SQL database but I am having difficulties passing my dataset as an argument to my DB class. I am not sure if it is allowed to pass as an argument. If not, what are my alternatives?

The way I create my dataset:

public static void getLogs() {
    string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"someDir";
    SQLiteConnection cn = new SQLiteConnection("Data Source=" + path + ";Version=3;New=False;Compress=True;");
    cn.Open();
    SQLiteDataAdapter sd = new SQLiteDataAdapter("SELECT * FROM table", cn);

    DataSet ds = new DataSet();
    sd.Fill(ds);

    cn.Close();

    db.InsertLogs(Form1.adminID, Form1.deviceID, ds);
}

My database class and insert method looks like the following:

public void InsertLogs(string user_id, string device_id, DataSet history)
{
    string query = "INSERT INTO table (column1, column2, column3, column4, column5, column6, column7) VALUES (@value1, @value2, @value3, @value4, @value5, @value6, @value7);";

    if (OpenConnection() == true)
    {
        foreach (DataTable table in history.Tables)
        {
            foreach (DataRow row in table.Rows)
            {
                MySqlCommand cmd = new MySqlCommand(query, connection);
                cmd.Parameters.AddWithValue("@value1", int.Parse(user_id));
                cmd.Parameters.AddWithValue("@value2", int.Parse(device_id));
                cmd.Parameters.AddWithValue("@value3", row[0]);
                cmd.Parameters.AddWithValue("@value4", row[1]);
                cmd.Parameters.AddWithValue("@value5", row[2]);
                cmd.Parameters.AddWithValue("@value6", row[3]);
                cmd.Parameters.AddWithValue("@value7", row[4]);
                cmd.ExecuteNonQuery();
            }
        }
        CloseConnection();
    }
}

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can loop through datatables in a dataset and can pass a datatable as a stored procedure paramater, found an example here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...