Home > other >  Simple SQL Server database connection and reading a table on C#
Simple SQL Server database connection and reading a table on C#

Time:10-07

I am new at this but I have a simple table in my SQL Server with one column name and 2 rows in it. I am trying to show up the names when pressing a button, I need to know how to connect the SQL Server database to the C# code and how to read from a specific table.

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString;
            SqlConnection cnn;
            connetionString = @"Data Source=DESKTOP-REB699D\SQLEXPRESS;Initial Catalog=DBdemo";
            cnn = new SqlConnection(connetionString);
            cnn.Open();
            MessageBox.Show("Connection Open  !");
            cnn.Close();
        }
    }
}

But that didn't work, it crashes at the cnn.open(); line of code.

CodePudding user response:

If you are not using any credentials, its windows authentication.

Does adding Integrated Security=True to the connection string help?

Can you login to the DB without credentials on SSMS using Windows authentication option? If so, you don't need user credentials for connecting to DB. If you require a Username and password there,

  1. you either need to include that in the connection string or
  2. you need to enable SQL Server and Windows Authentication option under security tab to access the database without credentials
  • Related