62,046
社区成员
发帖
与我相关
我的任务
分享
string sql = "EXEC master..xp_cmdshell 'bcp [xxx].[dbo].userproduct out d:\\DT1.txt -c -S -Usa -P'";
//下面是执行查询部分
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["webCon"].ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
conn.Close();
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["webCon"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sqlConn.Open();
cmd.CommandText = "Select * from userproduct1";
DataSet ds = new DataSet();
sda.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
string BcpExec = "";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)//循环取本地文件名
{
BcpExec = @"bcp [cangku].[dbo].userproduct1 out d:\\DT1.xls";
//BcpExec += ds.Tables[0].Rows[i]["path"].ToString();
BcpExec += " -S -Usa -P -c -t,";//组合bcp命令
//Response.Write();//执行bcp命令并显示操作结果
ExeCommand(BcpExec);
}
Response.Write("共" + ds.Tables[0].Rows.Count + "条数据导出成功!");
}
}
/**/
/// <summary>
/// 执行Cmd命令
/// </summary>
/// <param name="commandText"></param>
/// <returns></returns>
public static string ExeCommand(string commandText)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
string strOutput = null;
try
{
p.Start();
p.StandardInput.WriteLine(commandText);
p.StandardInput.WriteLine("exit");
strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
strOutput = e.Message;
}
return strOutput;
}