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();
    }
}
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Raghad
  • 35
  • 1
  • 6
  • 1
    https://stackoverflow.com/questions/3386770/using-on-sqldatareader – VDWWD Jun 25 '19 at 13:01
  • 3
    This code is wide open to a [SQL Injection attack](https://bobby-tables.com/). Please take the time to learn how to securely build your SQL commands to prevent these attacks. – mason Jun 25 '19 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) – Marc Gravell Jun 25 '19 at 13:51

7 Answers7

2

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

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

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();
    }
}
Cleptus
  • 3,446
  • 4
  • 28
  • 34
  • 1
    Please provide answers without errors. SqlCommand is disposable. – Marco Salerno Jun 25 '19 at 13:29
  • using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBS.accdb"].ConnectionString)) ; – Raghad Jun 25 '19 at 13:53
  • 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? – Raghad Jun 25 '19 at 13:55
  • 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. – Chris Dunaway Jun 25 '19 at 14:01
  • @Raghad add reference in the project to "System.Configuration" and after that you can find it in the System.Configuration namespace. – Cleptus Jun 25 '19 at 19:19
1

This is a simple example code and it's working. This might help you. Here NextMonth,NextYear,ProcessedDate are auto calculated values comes from another function don't think about that.

        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);
            }
        }
    }

Connection string can be found in DB properties. right click on DB -> properties and Get the Connection String

0

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.

Assassin
  • 1,296
  • 2
  • 14
  • 17
  • Or integrated security ;-) – Cleptus Jun 25 '19 at 12:50
  • 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. – Assassin Jun 25 '19 at 12:55
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 ! ");
        }
Amin Saadati
  • 719
  • 8
  • 21
  • 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. – Cleptus Jun 25 '19 at 12:56
  • I hope it be forever. i just want to reference to the right web site :) – Amin Saadati Jun 25 '19 at 13:00
  • This is a nice link https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/connection-string-syntax and this one has some sample code https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection?view=netframework-4.8 – Cleptus Jun 25 '19 at 13:03
  • @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 https://stackoverflow.com/questions/4717789/in-a-using-block-is-a-sqlconnection-closed-on-return-or-exception – Amin Saadati Jun 25 '19 at 13:04
  • @bradbury9 if you prefer i will change my above link to this second link you put it in above comment – Amin Saadati Jun 25 '19 at 13:07
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);
        }
    }
}
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32
0

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();
                }
            }
        }
    }
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
Domenico
  • 309
  • 3
  • 6