-5
private void button1_Click(object sender, EventArgs e)
{ 
    string connetionString = null;    

    SqlConnection cnn;
    connetionString = "My_Connection";

    cnn = new SqlConnection(connetionString);

    try
    {
        cnn.Open();

        SqlCommand cmd = new SqlCommand("INSERT INTO person " +
              "(name, lastname, phone) VALUES('@name', '@lastname', '@phone')");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = cnn;

        cmd.Parameters.AddWithValue("@name", txtName.Text);
        cmd.Parameters.AddWithValue("@lastname", txtLastname.Text);
        cmd.Parameters.AddWithValue("@phone", Convert.ToInt32(txtPhone.Text));

        MessageBox.Show("Successful");

        cnn.Close();
    }
    catch (SqlException ex)
    {
        MessageBox.Show("You failed!" + ex.Message);
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
rasool
  • 19
  • 2
  • 1
    It's fairly obvious in this case, but you should state explicitly what the error message is that you are receiving. If you meant to refer to a connection string from a config file, you should state that as well and show the relevant configuration snippet. And take the time to format your code to normal coding conventions (removing all that extra whitespace). – mason Mar 24 '17 at 20:39
  • 1
    What did you think that `connetionString = "MyConnection"` would do? – EJoshuaS - Stand with Ukraine Mar 24 '17 at 21:14
  • 1
    What is `My_Connection` supposed to be? – EJoshuaS - Stand with Ukraine Mar 24 '17 at 21:21
  • `"My_Connection"` is certainly a string, however it is not a connection string. – Andrew Mar 25 '17 at 02:01
  • 1
    You should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and stop using `.AddWithValue()` - it can lead to unexpected and surprising results... – marc_s Mar 25 '17 at 08:51

4 Answers4

5

There is a number of issues with this code. It appears that you're trying to reference a connection string from a configuration file. However, you can't just pass the name to the connection - you must actually retrieve it and assign it to your SqlConnection. Alternatively, you can hardcode a connection string, plenty of examples of those are available at connectionstrings.com.

It is usually not a good idea to put the connection string directly in your application however, as you need to reuse them throughout your application and it's best to have them declared in a central location.

private void button1_Click(object sender, EventArgs e)
{
    // retrieve connection from configuration file
    // requires a reference to System.Configuration assembly in your project
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["My_Connection"].ConnectionString;

    //alternatively, hardcode connection string (bad idea!)
    //string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

    using(SqlConnection connection = new SqlConnection(connectionString))
    using(SqlCommand command = new SqlCommand("INSERT INTO person (name, lastname, phone) VALUES(@name, @lastname, @phone)", connection))
    {
        // you should avoid AddWithValue here, see http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
        // thanks marc_s! http://stackoverflow.com/users/13302/marc-s
        command.Parameters.AddWithValue("@name", txtName.Text);
        command.Parameters.AddWithValue("@lastname", txtLastname.Text);
        command.Parameters.AddWithValue("@phone", Convert.ToInt32(txtPhone.Text));
        connection.Open();
        command.ExecuteNonQuery();          
    }

    MessageBox.Show("Successful");
}

The connection string is passed to the connection in its constructor, and the connection is passed to the command via its constructor.

Notice that there is no need to explicitly close the connection, the using statements take care of those for you. When the variable is out of scope, the connection will be closed, even if there is an exception.

An example of a connection string in your configuration file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="My_Connection" providerName="System.Data.SqlClient" connectionString="Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;" />
  </connectionStrings>
</configuration>
mason
  • 31,774
  • 10
  • 77
  • 121
1

You have to write valid connetionString. If you ask what connection string is?

Here is answer

'In computing, a connection string is a string that specifies information about a data source and the means of connecting to it. It is passed in code to an underlying driver or provider in order to initiate the connection. Whilst commonly used for a database connection, the data source could also be a spreadsheet or text file.

The connection string may include attributes such as the name of the driver, server and database, as well as security information such as user name and password.'

Something like that

Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword; 

They are a number of things to worry about when connecting to SQL Server on another machine.

  • Host/IP Address of the machine
  • Initial Catalog (database name)
  • Valid username/password

Very often SQL server may be running as a default intance which means you can simply specify the hostname/ip address but you may encounter a scenario where it is running as a named instance (Sql Express for instance). In this scenario you'll have to specify hostname\instance name

Fatikhan Gasimov
  • 903
  • 2
  • 16
  • 40
  • Perhaps you should point out why the current connection string isn't valid, what can be done to fix it, or how to pull it from a config file where there may be a connection string with a name of "My_Connection". – mason Mar 24 '17 at 20:41
  • 1
    You have to write like that Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword; – Fatikhan Gasimov Mar 24 '17 at 20:44
  • No need to tell me. I'm pointing out to you that it needs to be *in your answer*. – mason Mar 24 '17 at 20:45
  • 1
    here is explanation of connection string – Fatikhan Gasimov Mar 24 '17 at 21:07
0

Your connection string is missing! Define it or get from your config. "My_Connection" doesn't contain server, database, user, password. Use something like:

var connectionString = "Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;";
IngoB
  • 2,552
  • 1
  • 20
  • 35
  • Go on....I know what you mean. But someone new to development may not know what you mean by missing, since they clearly assign something to something called connection string. Your answer should be explicit in describing what the solution is. – mason Mar 24 '17 at 20:40
  • Yeah, absolutely right, give me some more seconds. :) – IngoB Mar 24 '17 at 20:41
  • There is no way to tell who downvoted the question, votes are anonymous. Anyways, the question is pretty terrible. It was poorly formatted, didn't explain why he though "My_Connection" could possibly be valid, didn't state relevant error message etc. There is a much higher standard for both questions and answers on this site. – mason Mar 24 '17 at 20:50
  • Agreed, mason. :) – IngoB Mar 24 '17 at 20:55
  • Not sure why this was downvoted, this answer's exactly correct. – EJoshuaS - Stand with Ukraine Mar 24 '17 at 21:18
0
using (SqlConnection connection = new SqlConnection("Data Source=ServerName; Initial Catalog=DatabaseName;User ID=UserName;Password=Password"))
{
using (SqlCommand command = new SqlCommand())
{
    command.Connection = connection;            // <== lacking
    command.CommandType = CommandType.Text;
    command.CommandText = "INSERT INTO person " +
                  "(name,lastname,phone) VALUES('@name', '@lastname', '@phone')";
    cmd.Parameters.AddWithValue("@name", txtName.Text);
    cmd.Parameters.AddWithValue("@lastname", txtLastname.Text);
    cmd.Parameters.AddWithValue("@phone", Convert.ToInt32(txtPhone.Text));

    try
    {
        connection.Open();
        int recordsAffected = command.ExecuteNonQuery();
    }
    catch(SqlException)
    {
        // error here
    }
    finally
    {
        connection.Close();
    }
}
}

Here is the working code.

Sincerely,

Thiyagu Rajendran

**Please mark the replies as answers if they help and unmark if they don't.

  • No, they quite clearly put *something* in the connection string in the question. Please read the code again. And there is absolutely no need to close the connection in a finally block when you have it wrapped in a using statement. – mason Mar 24 '17 at 20:46
  • Why did you put "lacking" comment in your code? What was lacking? Why are you closing the connection in a finally block? Why isn't your code properly formatted with C# conventions? – mason Mar 24 '17 at 20:52
  • Have you ever handled database? You should not leave connections open.. In a large scale application if database allow only 5000 connections it will not allow new user to create connection until the previous connections closed. – Thiyagu Rajendran Mar 24 '17 at 21:00
  • I've been working with databases in C# since about 2011. The `using` statement will close and dispose the connection for you. Explicitly closing it when you have a using statement is a waste of time and misleading. – mason Mar 24 '17 at 21:02
  • using statement - Connections that are not explicitly closed might not be added or returned to the pool. I agree with it. Is there anything wrong if connection is disposed? – Thiyagu Rajendran Mar 24 '17 at 21:05
  • The using statement handles closing it for you. See [this question](http://stackoverflow.com/questions/18588049/sqlconnection-close-inside-using-statement). – mason Mar 24 '17 at 21:15