首页 > 解决方案 > 如何使用 WPF 按钮单击事件将 .txt 文件导入 SQL Server 数据库

问题描述

我有一个按钮单击事件,它打开文件对话框,选择一个 .txt 文件,并在 .txt 中显示文件路径TextBox

我遇到的问题是我不确定如何使用另一个按钮单击事件将该 .txt 文件上传到 SQL Server 中的表。请帮忙,谢谢!

        private void butn_Upload_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog fileDialog = new OpenFileDialog();
        fileDialog.Multiselect = false;
        fileDialog.Filter = "Textfiles|* .txt|All Files|*.*";
        fileDialog.DefaultExt = ".txt";
        Nullable<bool> dialogOK = fileDialog.ShowDialog();

        if (dialogOK == true)
        {
            string sFilenames = "";

            foreach (string sFilename in fileDialog.FileNames)
            {
                sFilenames += ";" + sFilename;
            }
            sFilenames = sFilenames.Substring(1);

            // Show file path in TextBox
            TbxFiles.Text = sFilenames;
        }
    }

此代码是我的第二次单击事件,我想将 .txt 文件插入 SQL Server。

        private void btnUpload_Click(object sender, RoutedEventArgs e)

    {
        //I'm not sure how to take txt file and use it with an Update SQL Statement


        SqlConnection con = new SqlConnection("Data Source=WINDOWS-B1AT5HC\\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");

        try
        {
            SqlCommand cmd = new SqlCommand("UPDATE", con);
            cmd.Parameters.AddWithValue("");
            con.Open();
            cmd.ExecuteNonQuery();

            MessageBox.Show("Data updated!");
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }


enter code here

标签: c#sql-servertext-filesopenfiledialog

解决方案


推荐阅读