which library needs to add for craete a connection with sql server ?

Pooja Borate 1 Reputation point
2022-07-25T14:34:31.137+00:00

I want to Sql connection class in this code but here its not come after, I using the System.Data.SqlClient liabrary what I do for this I use visual studio 2022 here//

using System.Data;  
using System.Data.SqlClient;  
namespace WinFormsApp1  
{  
    public partial class Student : Form  
    {  
        public Student()  
        {  
            InitializeComponent();  
        }  
         
        private void button2_Click(object sender, EventArgs e)  
        {  

            String sname = txtsname.Text;  
            String fname = txtfname.Text;  
            String mname = txtmname.Text;  
            String sdob = dateTimePicker1.Text;  
            String gender1 = "";  
            if (radioButton1.Checked)  
                gender1 = radioButton1.Text;  
            else if (radioButton2.Checked)  
                gender1 = radioButton2.Text;  
            else  
                gender1 = radioButton3.Text;  
            String sdd = txtadd.Text;  
            String cno = txtcno.Text;  
            String s_std = comboBox1.SelectedItem.ToString();  
            String s_class = comboBox2.SelectedItem.ToString();  

            String str = @"Data Source=DESKTOP-68J9FUT\SQLEXPRESS;Initial Catalog=Stu_registration;Integrated Security=True;Context C";  
        }  
    }  
}  
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,838 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,307 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,196 Reputation points
    2022-07-26T08:43:19.07+00:00

    In Solution Explorer, double click the project name and paste in the following, press CTRL+S.

    <ItemGroup>  
      <PackageReference Include="System.Data.SqlClient" Version="4.8.2" />  
    </ItemGroup>  
    

    For code, here is a raw example, note that the code should not be put into the form but instead in a class. See the following example that simple connects to a database.

    public static void StarterExample()  
    {  
        var selectStatement = "TODO";  
      
        using var cn = new SqlConnection("Your connection string");  
        using var cmd = new SqlCommand { Connection = cn, CommandText = selectStatement };  
      
        cn.Open();  
      
        /*  
         * If a SELECT  
         * cmd.ExecuteReader()  
         *  
         * If INSERT  
         * cmd.ExecuteNonQuery()  
         */  
      
    }  
    

    New code

    I had a few minutes to write up starter code, class project to add a record and a forms project to pass data to the class project

    226099-screen.png

    1 person found this answer helpful.
    0 comments No comments

  2. ShuaiHua Du 636 Reputation points
    2022-07-26T13:06:59.57+00:00

    Hi ,

    I think you are using ADO.NET for persistent your data in a WinForm application.

    If you using ADO.NET, you can add a package from Here

    And I wrote some sample code for your code as below:

    using System.Data;  
    using System.Data.SqlClient;  
      
    namespace WinFormsApp1  
    {  
        public partial class Student : Form  
        {  
            public Student()  
            {  
                InitializeComponent();  
            }  
      
            private void button2_Click(object sender, EventArgs e)  
            {  
                String sname = txtsname.Text;  
                String fname = txtfname.Text;  
                String mname = txtmname.Text;  
                String sdob = dateTimePicker1.Text;  
                String gender1 = "";  
                if (radioButton1.Checked)  
                    gender1 = radioButton1.Text;  
                else if (radioButton2.Checked)  
                    gender1 = radioButton2.Text;  
                else  
                    gender1 = radioButton3.Text;  
                String sdd = txtadd.Text;  
                String cno = txtcno.Text;  
                String s_std = comboBox1.SelectedItem.ToString();  
                String s_class = comboBox2.SelectedItem.ToString();  
                String str = @"Data Source=DESKTOP-68J9FUT\SQLEXPRESS;Initial Catalog=Stu_registration;Integrated Security=True;Context C";  
      
                //Do persistent  
                InsertStudent(str, sname, fname, mname, ....);  
      
            }  
      
            private int InsertStudent(string connectionString, string sname, string fname, string mname,...)  
            {  
                try  
                {  
                    SqlParameter[] studentParams = GetStudentarameters();  
                    SqlCommand cmd = new SqlCommand();  
      
                    studentParams[0].Value = sname;  
                    studentParams[1].Value = fname;  
                    studentParams[2].Value = mname;  
      
                    foreach (var item in studentParams)  
                    {  
                        cmd.Parameters.Add(item);  
                    }  
      
                    using (SqlConnection connection = new SqlConnection(connectionString))  
                    {  
                        connection.Open();  
                        string commandText = "INSERT INTO [You Student TableName] VALUES (@sname,@fname,@mname...)";  
      
                        int result = SQLHelper.ExecuteNonQuery(connection, CommandType.Text, commandText, studentParams);  
      
                        return result;  
                    }  
                }  
                catch (Exception ex)  
                {  
                    throw ex;  
                }  
      
            }  
      
            private static SqlParameter[] GetStudentarameters()  
            {  
                return new SqlParameter[] {  
                        new SqlParameter("sname", SqlDbType.VarChar, 80),  
                        new SqlParameter("fname", SqlDbType.VarChar, 80),  
                        new SqlParameter("mname", SqlDbType.VarChar, 80),  
                        ... //You student database parameters  
      
            }  
        }  
    }  
    

    The SQLHelper.cs references from Microsoft Official:

    //===============================================================================  
    // This file is based on the Microsoft Data Access Application Block for .NET  
    // For more information please go to   
    // http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp  
    //===============================================================================  
      
    using System.Collections;  
    using System.Data;  
    using System.Data.SqlClient;  
      
    namespace WinFormsApp1  
    {  
      
        /// <summary>  
        /// The SqlHelper class is intended to encapsulate high performance,   
        /// scalable best practices for common uses of SqlClient.  
        /// </summary>  
        public abstract class SQLHelper  
        {  
      
            private static string connectionString;  
      
            //Database connection strings   
            public static string ConnectionString  
            {  
                get  
                {  
                    if (connectionString == null)  
                    {  
      
                        //You can set the connectionString here.  
                        //e.g: Get connection string from you configuration file.  
                    }  
                    return connectionString;  
                }  
            }  
      
      
            // Hashtable to store cached parameters  
            private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());  
      
            /// <summary>  
            /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string   
            /// using the provided parameters.  
            /// </summary>  
            /// <remarks>  
            /// e.g.:    
            ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
            /// </remarks>  
            /// <param name="connectionString">a valid connection string for a SqlConnection</param>  
            /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>  
            /// <param name="commandText">the stored procedure name or T-SQL command</param>  
            /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>  
            /// <returns>an int representing the number of rows affected by the command</returns>  
            public static int ExecuteNonQuery(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)  
            {  
      
                SqlCommand cmd = new SqlCommand();  
      
                using (SqlConnection conn = new SqlConnection(connString))  
                {  
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);  
                    int val = cmd.ExecuteNonQuery();  
                    cmd.Parameters.Clear();  
                    return val;  
                }  
            }  
      
            /// <summary>  
            /// Execute a SqlCommand (that returns no resultset) against an existing database connection   
            /// using the provided parameters.  
            /// </summary>  
            /// <remarks>  
            /// e.g.:    
            ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
            /// </remarks>  
            /// <param name="conn">an existing database connection</param>  
            /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>  
            /// <param name="commandText">the stored procedure name or T-SQL command</param>  
            /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>  
            /// <returns>an int representing the number of rows affected by the command</returns>  
            public static int ExecuteNonQuery(SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)  
            {  
      
                SqlCommand cmd = new SqlCommand();  
      
                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);  
                int val = cmd.ExecuteNonQuery();  
                cmd.Parameters.Clear();  
                return val;  
            }  
      
            /// <summary>  
            /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction   
            /// using the provided parameters.  
            /// </summary>  
            /// <remarks>  
            /// e.g.:    
            ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
            /// </remarks>  
            /// <param name="trans">an existing sql transaction</param>  
            /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>  
            /// <param name="commandText">the stored procedure name or T-SQL command</param>  
            /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>  
            /// <returns>an int representing the number of rows affected by the command</returns>  
            public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)  
            {  
                SqlCommand cmd = new SqlCommand();  
                PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);  
                int val = cmd.ExecuteNonQuery();  
                cmd.Parameters.Clear();  
                return val;  
            }  
      
            /// <summary>  
            /// Execute a SqlCommand that returns a resultset against the database specified in the connection string   
            /// using the provided parameters.  
            /// </summary>  
            /// <remarks>  
            /// e.g.:    
            ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
            /// </remarks>  
            /// <param name="connectionString">a valid connection string for a SqlConnection</param>  
            /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>  
            /// <param name="commandText">the stored procedure name or T-SQL command</param>  
            /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>  
            /// <returns>A SqlDataReader containing the results</returns>  
            public static SqlDataReader ExecuteReader(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)  
            {  
                SqlCommand cmd = new SqlCommand();  
                SqlConnection conn = new SqlConnection(connString);  
      
                // we use a try/catch here because if the method throws an exception we want to   
                // close the connection throw code, because no datareader will exist, hence the   
                // commandBehaviour.CloseConnection will not work  
                try  
                {  
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);  
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);  
                    cmd.Parameters.Clear();  
                    return rdr;  
                }  
                catch  
                {  
                    conn.Close();  
                    throw;  
                }  
            }  
      
            /// <summary>  
            /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string   
            /// using the provided parameters.  
            /// </summary>  
            /// <remarks>  
            /// e.g.:    
            ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
            /// </remarks>  
            /// <param name="connectionString">a valid connection string for a SqlConnection</param>  
            /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>  
            /// <param name="commandText">the stored procedure name or T-SQL command</param>  
            /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>  
            /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>  
            public static object ExecuteScalar(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)  
            {  
                SqlCommand cmd = new SqlCommand();  
      
                using (SqlConnection conn = new SqlConnection(connString))  
                {  
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);  
                    object val = cmd.ExecuteScalar();  
                    cmd.Parameters.Clear();  
                    return val;  
                }  
            }  
      
            /// <summary>  
            /// Execute a SqlCommand that returns the first column of the first record against an existing database connection   
            /// using the provided parameters.  
            /// </summary>  
            /// <remarks>  
            /// e.g.:    
            ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
            /// </remarks>  
            /// <param name="conn">an existing database connection</param>  
            /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>  
            /// <param name="commandText">the stored procedure name or T-SQL command</param>  
            /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>  
            /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>  
            public static object ExecuteScalar(SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)  
            {  
      
                SqlCommand cmd = new SqlCommand();  
      
                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);  
                object val = cmd.ExecuteScalar();  
                cmd.Parameters.Clear();  
                return val;  
            }  
      
            /// <summary>  
            /// add parameter array to the cache  
            /// </summary>  
            /// <param name="cacheKey">Key to the parameter cache</param>  
            /// <param name="cmdParms">an array of SqlParamters to be cached</param>  
            public static void CacheParameters(string cacheKey, params SqlParameter[] cmdParms)  
            {  
                parmCache[cacheKey] = cmdParms;  
            }  
      
            /// <summary>  
            /// Retrieve cached parameters  
            /// </summary>  
            /// <param name="cacheKey">key used to lookup parameters</param>  
            /// <returns>Cached SqlParamters array</returns>  
            public static SqlParameter[] GetCachedParameters(string cacheKey)  
            {  
                SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];  
      
                if (cachedParms == null)  
                    return null;  
      
                SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];  
      
                for (int i = 0, j = cachedParms.Length; i < j; i++)  
                    clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();  
      
                return clonedParms;  
            }  
      
            /// <summary>  
            /// Prepare a command for execution  
            /// </summary>  
            /// <param name="cmd">SqlCommand object</param>  
            /// <param name="conn">SqlConnection object</param>  
            /// <param name="trans">SqlTransaction object</param>  
            /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>  
            /// <param name="cmdText">Command text, e.g. Select * from Products</param>  
            /// <param name="cmdParms">SqlParameters to use in the command</param>  
            private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)  
            {  
      
                if (conn.State != ConnectionState.Open)  
                    conn.Open();  
      
                cmd.Connection = conn;  
                cmd.CommandText = cmdText;  
      
                if (trans != null)  
                    cmd.Transaction = trans;  
      
                cmd.CommandType = cmdType;  
      
                if (cmdParms != null)  
                {  
                    foreach (SqlParameter parm in cmdParms)  
                        cmd.Parameters.Add(parm);  
                }  
            }  
        }  
    }  
    

    For more about ADO.NET, please refer:

    ADO.NET

    If you want to know more about modern data persistence, please reference EFCore:

    EF Core

    If right, please Accept.
    Enjoy programming!!!

    1 person found this answer helpful.
    0 comments No comments

  3. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2022-07-26T07:06:42.223+00:00

    @Pooja Borate , Welcome to Microsoft Q&A, you could try the following code to create a connection with sql server.

      private void button1_Click(object sender, EventArgs e)  
            {  
                String str = @"Data Source=DESKTOP-68J9FUT\SQLEXPRESS;Initial Catalog=Stu_registration;Integrated Security=True;";  
      
                SqlConnection connection=new SqlConnection(str);  
                connection.Open();  
                // do some operation in sql  
      
                connection.Close();  
            }  
    

    Also, Please note that Context C is the extra string, we need to remove it.

    Hope my code could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  4. Rijwan Ansari 746 Reputation points MVP
    2022-07-30T11:22:03.003+00:00

    Hi @Pooja Borate

    You need below 2 package for SQL connection and operations using ADO.NET
    Packages:
    using System.Data;
    using System.Data.SqlClient;

    Since you are using Visual Studio, you can add using NuGet Package as shown in this link.

    And then you can do SQL connection and operations.
    Sample
    https://www.c-sharpcorner.com/UploadFile/201fc1/sql-server-database-connection-in-csharp-using-adonet/

    0 comments No comments