0

I've always used Oledb Connection. but now I need to connect with my Database via Sql connection yet I don't know how to do so, can some one provide me an example of a database connected with sql connection?

this code needs a sql connection to be done successfully.

protected void Button1_Click(object sender, EventArgs e)
{
    string st = this.TextBox1.Text;
    string sqlstr2 = "select * from hsinfo WHERE rname='"+st+ "'";

    SqlCommand cmd = new SqlCommand(sqlstr2,);
    using (SqlDataReader rd = cmd.ExecuteReader())
    {
        this.Label1.Text = rd["rmail"].ToString();
    }
}
3
  • 1
    stackoverflow.com/questions/3386770/using-on-sqldatareader Commented Jun 25, 2019 at 13:01
  • 3
    This code is wide open to a SQL Injection attack. Please take the time to learn how to securely build your SQL commands to prevent these attacks. Commented Jun 25, 2019 at 13:21
  • if you know what to do with Oracle, then it is virtually identical for SQL Server, except you use SqlConnection instead of OracleConnection...? (but: please please fix the SQL injection problem; tools like "Dapper" make that trivial) Commented Jun 25, 2019 at 13:51

8 Answers 8

2

You can check the official Microsoft page for more details SqlConnection Class, but I will reproduce the given example below:

private static void CreateCommand(string queryString,
   string connectionString)
{
   using (SqlConnection connection = new SqlConnection(
              connectionString))
   {
       SqlCommand command = new SqlCommand(queryString, connection);
       command.Connection.Open();
       command.ExecuteNonQuery();
   }
}

Additionally you can check also the Connection String Syntax linked in the previous link.

Sign up to request clarification or add additional context in comments.

6 Comments

Please provide answers without errors. SqlCommand is disposable.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBS.accdb"].ConnectionString)) ;
I found the code above but i don't have a configuration manager,so it doesn't work for me, so how can I get it, and what is it in the first place?
If you get an error on ConfigurationManager, then you need to make sure you have a reference to System.Configuration and add using System.Configuration to the top of your code.
@Raghad add reference in the project to "System.Configuration" and after that you can find it in the System.Configuration namespace.
|
1

There is no enougth information to build connection for you, but in the shortes you sth like this:

Server=...;Database=...;User ID=...;Password=...;

For more information just check ConnectionStrings website.

2 Comments

Or integrated security ;-)
This is a good option as well, the problem is that the poster did not add any information about connection and the ConnectionStrings sites describe all available options.
1

Here NextMonth, NextYear, and ProcessedDate are auto-calculated values that come from another function; don't worry about them.

String cs = @"Data Source=LENOVO-G510;Initial Catalog=Nelna2;Persist Security Info=True;User ID=sa;Password=123";

protected void Save_Click(object sender, EventArgs e)
{
    // SqlConnection con = new SqlConnection(cs);

    using (SqlConnection con = new SqlConnection(cs))
    {
        try
        {
            SqlCommand command5 = new SqlCommand("insert into MonthEnd (month,year,ProcessedDate) values (@month2,@year2,@ProcessedDate2) ", con);

            command5.Parameters.AddWithValue("@month2", NextMonth);
            command5.Parameters.AddWithValue("@year2", NextYear);
            command5.Parameters.AddWithValue("@ProcessedDate2", ProcessedDate);

            command5.ExecuteNonQuery();

        }
        catch (SqlException ex)
        {
            Response.Write(ex.Message);
        }
    }
}

The connection string can be found in the database properties. Right-click on the database -> select Properties and get the Connection String

1 Comment

Why do you declare the connection string in a variable instead of declaring it during the SqlConnection declaration?
0

try below code and for more information about c# SQL server connection see this SQL Server Connection

string connetionString = null;
        SqlConnection cnn ;
        connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
        cnn = new SqlConnection(connetionString);
        try
        {
            cnn.Open();
            MessageBox.Show ("Connection Open ! ");
            cnn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Can not open connection ! ");
        }

5 Comments

Better link to the official documentation, its more likely to be long lived. Consider using using to proper handling the connection similar to other IDisposable classes.
I hope it be forever. i just want to reference to the right web site :)
@bradbury9 you are right , but i just wanted to show a simple sample of using SqlConnection . exactly Using Using is so fine for above code like this link stackoverflow.com/questions/4717789/…
@bradbury9 if you prefer i will change my above link to this second link you put it in above comment
0

I would do something like this:

public static List<Test> GetTests(string testVariable)
{
    DataTable result = new DataTable();
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
    {
        connection.Open();

        GetQuery(
            connection,
            QueryGetTests,
            ref result,
            new List<SqlParameter>()
            {
                new SqlParameter("@testVariable", testVariable)
            }
        );

        return result.Rows.OfType<DataRow>().Select(DataRowToTest).ToList();
    }
}

private static void GetQuery(SqlConnection connection, string query, ref DataTable dataTable, List<SqlParameter> parameters = null)
{
    dataTable = new DataTable();
    using (SqlCommand command = new SqlCommand(query, connection))
    {
        command.CommandTimeout = 120;
        if (parameters != null)
        {
            foreach (SqlParameter parameter in parameters)
            {
                command.Parameters.Add(parameter);
            }
        }
        using (SqlDataAdapter reader = new SqlDataAdapter(command))
        {
            reader.Fill(dataTable);
        }
    }
}

Comments

0

Trick:

  1. Create a file with .udl Extension on your Desktop
  2. Run it by Double click
  3. Compile form by Choosing provider, username, password, etc...
  4. Test connection and save
  5. Close the form
  6. Open now the .udl file with Notepad
  7. You will see the connection string that you can use with ADO.NET

Comments

0

Try this.

    protected void Button1_Click(object sender, EventArgs e)
    {
        string _connectionString = "";
        string st = this.TextBox1.Text;
        string query = "select top(1) * from hsinfo WHERE rname='" + st + "'";

        using (SqlConnection conn = new SqlConnection(_connectionString)) 
        {
            conn.Open();
            using (SqlCommand command = new SqlCommand(query, conn)) 
            { 
                var reader = command.ExecuteReader();
                reader.Read();
                this.Label1.Text = rd["rmail"].ToString();
            }
        }
    }

Of course you need to provide valid connection string that points to your database and lets you open the connection. It can be either stored in constructor, in the method, or provided from Configurastion Manager if yu use it

Here are examples of valid connection strings, where zou just replace the values related to your database.

Connection strings examples

Comments

-1

I think this can help you.

    string sqlString = "select * from hsinfo WHERE rname=@st";

    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(sqlString, conn))
        {
            cmd.Parameters.Add("@st", st);

            using (SqlDataReader rd = cmd.ExecuteReader())
            {
                if (rd.Read())
                {
                    this.Label1.Text = rd["rmail"].ToString();
                }
            }
        }
    }

2 Comments

i don't have a configuration manager,so it doesn't work for me, so how can I get it, and what is it in the first place?
You have to include System.Configuration

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.