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

放肆的年华 提交于 2019-12-02 13:04:22

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

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

Also it is very important to use sql Parameters

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");

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:

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();
        }
CSharpAlchemist

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