I can't connect to SQL Server database with C# code [closed]

耗尽温柔 提交于 2019-12-20 07:38:37

问题


I was trying to create registration form but when I run my project am getting this error message

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

My code:

using System;
using System.Data;
using System.Data.SqlClient;

namespace Registration{
private void Register_Click(object sender, EventArgs e)
{

     SqlConnection con = new SqlConnection("Data Source=SHAB 
     SQLEXPRESS;InitialCatalog=Phonebook;Integrated Security=True"); 

     SqlCommand cmd = new SqlCommand(@"INSERT INTO [dbo].[registration]([username[fullname],[Password]) VALUES('" + username.Text+"', '"+fullname.Text+"', '"+password.Text+"')");

     con.Open(); 
     cmd.ExecuteNonQuery(); 
     con.Close(); 
     MessageBox.Show("Congradulation You have been Registered");
}

The error appears on the line con.open();.

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


回答1:


You are missing a comma between [username] and [fullname]. Try like:

INSERT INTO ... ([username], [fullname], ...

Also it is very important to use sql Parameters




回答2:


First Check SQL Server Service is running. after that check Data Source value in your Connection String, if you are using SQLExpress then it may be SqlConnection con = new SqlConnection("Data Source=SHAB\SQLEXPRESS;InitialCatalog=Phonebook;Integrated Security=True");




回答3:


A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.

As the error indicates, your connection unable to reach SQL Server, make sure you are able to do telnet SHAB 1433

If Telnet fails:

  • Make sure TCP/IP protocol enabled, you can verify it via SQL Server Configuration manager (following screenshot for reference)
  • Verify the custom port NOT Configured (via SQL Server Configuration manager) for SQL Express service

If the custom port NOT configured

  1. Make sure SQL Browser service is running
  2. Create a rule in Windows Firewall to accept incoming connections on TCP ports 1433 and 1434 (TCP and UDP) - This must be done at the server where SQL Service is running
  3. Restart SQL Browser service
  4. Your connection should work here with DataSource=SHAB\\SQLEXPRESS. You can do telnet SHAB 1433 to verify

If the custom port configured

  1. Create a rule in Windows Firewall to accept incoming connections on Custom TCP ports - This must be done at the server where SQL Service is running
  2. Restart SQL Service
  3. Your connection should work here when you use DataSource = SHAB,<custom port>. However, you can do telnet SHAB <custom port> to verify

SQL Server Configuration manager:




回答4:


Your connection string must be in app.config file

<connectionStrings>
    <add name="DbConnection" connectionString="Data Source=.\SQLEXPRESS;Initial 
    Catalog=dbname;Integrated Security=True" 
    providerName="System.Data.EntityClient"
<connectionStrings>

import configuration from

using System.Configuration;

Add DB Connection

public string DbCon = 
 ConfigurationManager.ConnectionStrings["DbConnection"].ToString();

var Query=@"INSERT INTO [dbo].[registration]([username[fullname],[Password]) VALUES('" + username.Text+"', '"+fullname.Text+"', '"+password.Text+"')"
using (con = new SqlConnection(DbCon))
        {
            con.Open();
            SqlCommand com = new SqlCommand(Query, con);
            com.ExecuteNonQuery();
            con.Close();
        }



回答5:


I think that you just have omitted the username and the password in your connection string. Try the following code.

Data Source=YourServer;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=YourPassword


来源:https://stackoverflow.com/questions/57756059/i-cant-connect-to-sql-server-database-with-c-sharp-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!