将列中的数据插入到sql表中

时间:2013-10-01 16:28:49

标签: c# wpf

如何将DataGrid中的列数据插入到sql表中。

        private void btUpload_Click(object sender, RoutedEventArgs e)
    {

        // Configure open file dialog box 
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        // Filter by Excel Worksheets
        dlg.Filter = "Excel Worksheets|*.xls";

        dlg.ShowDialog();

        // Show open file dialog box 
        Nullable<bool> result = dlg.ShowDialog();         

        // Process open file dialog box results 
        if (result == true)
        {

            // Create connection string variable. Modify the "Data Source"
            // parameter as appropriate for your environment.
            String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                "Data Source=" + dlg.FileName+ ";" +
                "Extended Properties=Excel 8.0;";               

            // Create connection object by using the preceding connection string.
            OleDbConnection objConn = new OleDbConnection(sConnectionString);

            // Open connection with the database.
            objConn.Open();

SQL SELECT命令,用于显示工作表中的数据。

            // Create new OleDbCommand to return data from worksheet.
            OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [codereward$]", objConn);

            // Create new OleDbDataAdapter that is used to build a DataSet
            // based on the preceding SQL SELECT statement.
            OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();

            // Pass the Select command to the adapter.
            objAdapter1.SelectCommand = objCmdSelect;

            // Create new DataSet to hold information from the worksheet.
            DataSet objDataset1 = new DataSet();

使用工作表中的信息填充DataSet。

            objAdapter1.Fill(objDataset1, "XLData");

            // Bind data to DataGrid control.
            dgCodeDisp.ItemsSource = objDataset1.Tables[0].DefaultView;

            // Clean up objects.
            objConn.Close();
        }

我的插入命令,这里我想从CodeGrid中的代码中插入代码中的数据。

        sc.Open();
        cmd = new SqlCommand("Insert into RewardCodes (Code, value1, value2, ID) values('" + dgCodeDisp + "','" + ckv1.IsChecked.ToString() + "','" + ckv2.IsChecked.ToString() + "', '" + txtId.Text + "')", sc);
        cmd.ExecuteNonQuery();
    }

1 个答案:

答案 0 :(得分:1)

我认为你的实施中的事情变得复杂了。如果您正在使用SQL Server表,Bulkcopy,则是适当的工具。它会完成你桌子上的所有插入。 Here's a complete tutorial