1.面图:
2.代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace ConsoleSqlInsert { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // 打开选择文件弹窗 OpenFileDialog file = new OpenFileDialog(); DialogResult result = file.ShowDialog(); if (result == DialogResult.OK) { this.textBox1.Text = file.FileName; } } /// <summary> /// 插入数据到数据库 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { //数据库服务实例 string ServerName = ConfigurationManager.AppSettings["ServerName"].ToString(); //数据库用户:sa string UserID= ConfigurationManager.AppSettings["UserID"].ToString(); //数据库密码 string Password = ConfigurationManager.AppSettings["Password"].ToString(); //针对导入的数据库 string DatabaseName = ConfigurationManager.AppSettings["DatabaseName"].ToString(); // 数据库连接字符串 string connction = ConfigurationManager.ConnectionStrings["master"].ConnectionString; string filePath = this.textBox1.Text; if (!string.IsNullOrEmpty(filePath)) { string argument = string.Format(" -S {0} -U {1} -P {2} -d {3} -i {4}", ServerName, UserID, Password, DatabaseName, filePath); try { using (SqlConnection conn = new SqlConnection(connction)) { conn.Open(); if (conn.State == ConnectionState.Open) { var process = Process.Start("SqlCmd", argument); process.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 process.StartInfo.CreateNoWindow = true; //不显示程序窗口 process.StartInfo.RedirectStandardError = true; //重定向标准错误输出 process.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息 process.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息 process.Start(); //while (true) //{ // // wait for the process exits.The WaitForExit() method doesn't work // if (process.HasExited) // { // break; // } // Thread.Sleep(500); //} process.Close(); } conn.Close(); MessageBox.Show("导入完成"); } } catch { MessageBox.Show("连接数据库失败"); } } else { MessageBox.Show("请选择导出的sql脚本文件"); } } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void button3_Click(object sender, EventArgs e) { // 退出,结束对应进程 System.Environment.Exit(0); } } }
3.App.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> </startup> <appSettings> <add key="ServerName" value="DESKTOPIBN"/> <add key="UserID" value="sa"/> <add key="Password" value="123"/> <add key="DatabaseName" value="PDDOW"/> </appSettings> <connectionStrings> <add name="master" connectionString="Server=DESKTOPIBN;Database=Crawler;User Id=sa;Password=123;Connection Timeout=3000;" /> </connectionStrings> </configuration>