Code for connecting to SQLServer

BenTam 1,581 Reputation points
2021-06-27T04:12:17.4+00:00

Dear All,

What is wrong with the following code? The source code was put below in accordance with a picture showing the red lines.

TIA

109567-sqlconn.gif

using System;  
using System.Data;  
using System.Data.SqlClient;  
  
namespace ConnectSql  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            ConnSql.Connect_Sql();  
            Console.WriteLine("Hello World!");  
        }  
    }  
  
    class ConnSql  
    {  
        public void Connect_Sql ()  
        {  
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=WelkinDB;Integrated Security=True");  
            SqlCommand cmd;  
            DataTable dt;  
            SqlDataAdapter da;  
            con.Open();  
            cmd = new SqlCommand("Select * from student", con);  
            da = new SqlDataAdapter(cmd);  
            ds = new DataSet();  
            da.Fill(ds, "testTable");  
            con.Close();  
            dt = ds.Tables["testTable"];  
        }  
    }  
}  
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,814 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,309 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.7K Reputation points
    2021-06-27T07:33:42.64+00:00

    Try adding some static:

    static class ConnSql
    {
       public static void Connect_Sql( )
       {
           . . .
       }
    }
    

    Also add a reference to System.Data assembly (in case of .NET Framework) or System.Data.SqlClient package (using "Manage NuGet Packages" command in .NET 5 or Core).

    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. BenTam 1,581 Reputation points
    2021-06-28T04:10:58.07+00:00

    Viorel, thanks for your reply.

    0 comments No comments

  2. Peter_1985 2,526 Reputation points
    2021-06-28T04:44:57.58+00:00
    1. Ensure that you're able to ping the IP on which the SQL Server database has been set up
    2. Please ensure your connection string is something like

    <connectionStrings>
    <add name="conn2" connectionString="Data Source=192.168.?.?\your_db_instance;Initial Catalog=your_db_schema;Integrated Security=False;User ID=your_db_login;Password=??????" providerName="System.Data.SqlClient"/>
    </connectionStrings>

    within Web.config/app.config file in your project, to ensure the project will work fine with the database.

    0 comments No comments

  3. BenTam 1,581 Reputation points
    2021-06-30T02:57:56.54+00:00

    Hi Jackson. Thanks for your reply.

    0 comments No comments