gpt4 book ai didi

c# - 如何将数据表复制到SQL Server?

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:40 25 4
gpt4 key购买 nike

我需要将一个数据表复制到一个新的 SQL Server 表中。我没有任何架构,但我知道数据表有哪些列(Year,Month,Day,MeanTemp,TotalPrecip,MaxGustSpeed)

根据我的研究,我发现我需要使用 SqlBulkCopy 但无法使其工作。该项目是 VS 2010 中的一个 win 应用程序。不知道这里是否有人可以帮助我。

非常感谢

ps:这是我在这里的第一篇文章,不确定我是否包含了足够的细节,请让我知道是否还有其他需要提及的地方。我也是初学者,所以如果你能以一种易于理解的方式帮助我

这是我尝试过的:

string connectionString = "server=localhost;database=CPSdata;Trusted_Connection=True";

//Open a connection with destination database;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();

using (SqlBulkCopy bulkcopy = new SqlBulkCopy(connection))
{
bulkcopy.DestinationTableName = "dbo.climateRawDataTable";

try
{
bulkcopy.WriteToServer(dt);
}
catch (Exception ex)
{
}

connection.Close();
}
}

我得到的错误是:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

最佳答案

第一个问题是您的应用无法连接到数据库。可能的原因:

  1. 您没有启用 TCP 连接
  2. 您正在使用 SQL Express(使用“server=.\SQLEXPRESS”)
  3. 您的应用运行所用的身份无权连接
  4. 您正在运行命名实例(您的代码尝试连接到默认实例)

您可以使用 Management Studio 连接吗?

关于c# - 如何将数据表复制到SQL Server?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8549928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com