gpt4 book ai didi

c# - SQL Server 和连接到 C# 的问题

转载 作者:行者123 更新时间:2023-11-30 22:58:42 25 4
gpt4 key购买 nike

我是编程新手。我希望我的程序连接到 C#,但出现此错误:

System.Data.SqlClient.SqlException:
'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)'

我的代码:

namespace HesabDarinAnbarDari
{
public partial class FrmTanzimat : Form
{
public FrmTanzimat()
{
InitializeComponent();
}

SqlConnection con = new SqlConnection("Data source=(local);initial catalog=HesabDariDB;integrated security=true");
SqlCommand cmd = new SqlCommand();

private void FrmTanzimat_Load(object sender, EventArgs e)
{
}

private void btnSave_Click(object sender, EventArgs e)
{
cmd.Connection = con;
cmd.Parameters.Clear();
cmd.CommandText = "insert into Tanzimat (NameFroshqah, Tel, Mobile, Address. Tozih) values (@a, @b, @c, @d, @e)";

cmd.Parameters.AddWithValue("@a", txtNameFroshgah.Text);
cmd.Parameters.AddWithValue("@b", txtTel.Text);
cmd.Parameters.AddWithValue("@c", txtMobile.Text);
cmd.Parameters.AddWithValue("@d", txtAddress.Text);
cmd.Parameters.AddWithValue("@e", txtTozih.Text);

con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("done");
}
}
}

SQL 代码:

CREATE TABLE [dbo].[Tanzimat] 
(
[idTanzimat] INT IDENTITY (1, 1) NOT NULL,
[NameFroshgah] NVARCHAR(50) NULL,
[Tel] NVARCHAR(50) NULL,
[Mobile] NVARCHAR(50) NULL,
[Address] NVARCHAR(MAX) NULL,
[Tozih] NVARCHAR(MAX) NULL,

CONSTRAINT [PK_Tanzimat] PRIMARY KEY CLUSTERED ([idTanzimat] ASC)
);

最佳答案

当这个异常抛出时,意味着C#找不到你的数据源(local)

(local) 替换为您在 Sql Server Management Studio 中的服务器名称。

关于c# - SQL Server 和连接到 C# 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52822385/

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