Reputation: 37
I'm new to programing. I want my program connect to C# but I'm getting this error:
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)'
My code:
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 code :
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)
);
Upvotes: 2
Views: 173
Reputation: 3001
The error says that you are not connecting to SQL Server, which suggests a problem with your connection string or server. Try replacing (local) with (localhost) if you have an instance of SQL Server running locally (but be aware that this connection string will break as soon as you try to run your code on a different computer.)
If that doesn't work, go to the Server Explorer pane (View -> Server Explorer). Right-click Data Connections and choose Add Connection. Use that wizard to find your server and click Test Connection to make sure you're good to go. Click OK. Now in server explorer, click on your new data connection to select it, and look in the properties pane. You will see the connection string there. You can copy and paste from there into your code.
Upvotes: 0
Reputation: 1976
When this exception throw, it means C# can't find your Data source (local)
Replace the (local)
with your server name in the Sql Server Management Studio .
Upvotes: 3