0
public partial class Form1 : Form
{
    SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dimmer\Documents\Visual Studio 2013\Projects\Manage components\Manage components\Database1.mdf;Integrated Security=True");

    SqlCommand cmd = new SqlCommand();
    SqlDataReader dr;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        cmd.Connection = cn;
        loadlist();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (txtid.Text != "" & txtname.Text != "")
        {
            cn.Open();
            cmd.CommandText = "insert into info (id,name) values ('"+txtid.Text+"'.'"+txtname.Text+"')";
            cmd.ExecuteNonQuery();
            cmd.Clone();
            MessageBox.Show("Record instered!");
            txtid.Text = "";
            txtname.Text = "";
            loadlist();
        }
    }
}

I am new to C# and I have been trying for some hours with a insert code to a service-based database. I have tested the connection to it and it works.

I got this error message:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Incorrect syntax near 'xxxx'.

Where xxxx is what I insert into my 2nd textbox. The code stops at

cmd.ExcecuteNonQuery();

I have been searching for an answers for hours, I believe there is something wrong with the database.

Sorry if this code looks ugly, but I had some problems with spaces :P

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dim
  • 3
  • 1
  • 3
  • 1
    What are the values of `txtid.Text` and `txtname.Text` exactly? And you should always use parameterized queries. This kind of string concatenations are open for _SQL Injection_ attakcs. – Soner Gönül Nov 16 '13 at 22:33

1 Answers1

2

You didn't tell us what are txtid.Text and txtname.Text exactly but..

You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

cmd.CommandText = "insert into info (id,name) values (@id, @name)";
cmd.Parameters.AddWithValue("@id", txtid.Text);
cmd.Parameters.AddWithValue("@name", txtname.Text);
cmd.ExecuteNonQuery();

Looks like you're reusing a connection and you probably have not closed it last time.

You should always close a connection immediately as soon as you're finished with it. Use using statement like;

using(var cn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(query, cn))
{
    if (txtid.Text != "" & txtname.Text != "")
    {
       cmd.CommandText = "insert into info (id,name) values (@id, @name)";
       cmd.Parameters.AddWithValue("@id", txtid.Text);
       cmd.Parameters.AddWithValue("@name", txtname.Text);
       cn.Open();
       cmd.ExecuteNonQuery(); 
       cn.Close();
       ...
    }
}  
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Hello thanks alot for the fast reply! I did change the code to what you suggested and it brought me forward! I can see that my input is now recorded into the database but instead i get the error after input: An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll Additional information: The connection was not closed. The connection's current state is open. – Dim Nov 16 '13 at 22:46
  • 1
    I would recommend not to use `SqlDbType.Text` - use `SqlDbType.VarChar` or something like that instead .... `TEXT` is deprecated ... – marc_s Nov 16 '13 at 22:48
  • You are using cmd.Clone(); instead of cn.Close(); – flo scheiwiller Nov 16 '13 at 22:54
  • @user3000443 Updated in my answer. – Soner Gönül Nov 16 '13 at 22:59
  • Thanks alot, I am starting to get this working. The problem I got now is that the parameters id and name is Always set. Even if i Close the Connection. I have tryed to use cmd.Parameters.Remove("@id") etc, but it wont let me set these to null. – Dim Nov 16 '13 at 23:38
  • OK I solved it with my code: cmd.Parameters.Clear(); in front of the other code. Thanks alot for all the help! – Dim Nov 17 '13 at 00:38