How do I make a query using my connected SQL Server Database in Visual Studio 2022?

Viewed 33

Context:

Running Visual Studio 2022

Using the Blazor Server project template

I have connected an existing database - hosted on a network sql server - to my project using the Project -> Connected Services -> Add -> Sql Server Database

How do I then use this connection to query the database using C# code in my project?

The amount of data I want to access from this database is quite small compared to the size of the database, so I'm trying to avoid using Entity Framework to model the database, even in part. Essentially, I just want to be able to ask the database "Is [name] in [x] table?"

Connected Database in solution explorer

1 Answers

The winform project of the asp.netframework framework queries the database to realize the login function.

code logic:

     private void button1_Click(object sender, EventArgs e)
    {
        Dao dao = new Dao();
     
        string sql = $"select * from t_user where id='{textBox1.Text}' and psw='{textBox2.Text}'";
        IDataReader dc = dao.read(sql);
        if (dc.Read())
        {
            
            MessageBox.Show("welcome: " + dc["name"].ToString());

            
        }
        else
        {
            MessageBox.Show("Login failed");

        }
        dao.DaoClose();
    }

Encapsulates the query to the database:

  internal class Dao
 {
    SqlConnection conn;
    public SqlConnection connection()
    {
        // write database connection string
        string connStr = "Data source=localhost;Initial Catalog=student;User ID=sa;Password=123456";
        conn = new SqlConnection(connStr);
        conn.Open();
        return conn;
    }

    public SqlCommand command(string sql)
    {
        SqlCommand cmd = new SqlCommand(sql, connection());
        return cmd;
    }

    public int Execute(string sql)
    {
        return command(sql).ExecuteNonQuery();
    }

    public SqlDataReader read(string sql)
    {
        return command(sql).ExecuteReader();
    }
    public void DaoClose()
    {
        conn.Close();
    }
}

Project run:

enter image description here

Hope it helps you.

Related