Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
private void button4_Click(object sender, EventArgs e)
{
   SqlConnection con = new SqlConnection("data source =" + textBox1.Text + ";initial catalog=" + textBox2.Text + ";integrated security=true");
   con.Open();
   SqlCommand add = new SqlCommand("INSERT INTO Data (id_book,id_person,name_book) VALUES (" + textBox7.Text + "," + textBox8.Text + "," + textBox9.Text + ")",con);
add.ExecuteReader();
   con.Close();
   label11.Text = "سطر مورد نظر اضافه شد";
}

name_book is varchar
how can set it in the textbox?
Posted
Updated 13-May-14 3:33am
v2
Comments
[no name] 13-May-14 7:36am    
In addition to solution 1, you are using string concatenation to construct your query leaving you vulnerable to SQL injection attacks and you left out the single quote characters for your book name.

1.The problem is that you are using an INSERT SQL command, and then you are trying to executed like a reader.

2.If you want to execute an INSERT you must use ExecuteScalar() method and not ExecuteReader().
 
Share this answer
 
Comments
Vedat Ozan Oner 13-May-14 7:44am    
ExecuteScalar returns resultset[0][0]. therefore not for insert statement. see here http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.90%29.ASPX
Raul Iloc 13-May-14 8:11am    
I am not agree with you, and also Microsoft did not agree with you, because in the case of INSERT is indicated to use ExecuteScalar() method, because you will need to read as result the ID of the new inserted row. You can find this info even in the MS article indicated in your comment!<br>
Vedat Ozan Oner 13-May-14 8:42am    
:) ok, then I don't agree with microsoft :p if you check that example carefully, you will see that the sql command has two different parts in the command string. the first one is for insert, the second is for reading an id. ExecuteScalar method is used to read the second part which is a query returning a single scalar value: "SELECT CAST(scope_identity() AS int)".
Raul Iloc 13-May-14 8:54am    
1.You are joking!? Anyway I have used this method successfully in many real projects.
2."ExecuteScalar" method is doing both: the INSERT and the return of the Identity value (new ID).
Vedat Ozan Oner 13-May-14 9:20am    
please see my solution (comparison part).
Yes, Raul Iloc is correct.

Also you can go for ExecuteNonQuery() method as well.
Please refer the below two links to get some idea on it :
1) ExecuteNonQuery : Click[^]
2) ExecuteScalar() Vs ExecuteNonQuery() : Click[^]
 
Share this answer
 
Comments
Raul Iloc 13-May-14 8:05am    
You have my vote!
you should do something like the following:

C#
private static void InsertSomeData()
{
   // http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx
   // create proper connection string
   SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
   sb.DataSource = @"your server";
   sb.InitialCatalog = @"your db";
   sb.IntegratedSecurity = true;

   // sql insert statement
   string cmdStr = "INSERT INTO Data (id_book,id_person,name_book) VALUES (@id_book, @id_person, @name_book)";

   // http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection%28v=vs.90%29.aspx
   // http://msdn.microsoft.com/en-us/library/vstudio/system.idisposable%28v=vs.100%29.aspx

   // use SqlConnection with using statement
   using (SqlConnection conn = new SqlConnection(sb.ConnectionString))
   {
      // open connection
      conn.Open();
      // http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand%28v=vs.90%29.ASPX

      using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
      {
         // use SqlCommand.Parameters to add parameters
         cmd.Parameters.AddWithValue("@id_book", "your value");
         cmd.Parameters.AddWithValue("@id_person", "your value");
         cmd.Parameters.AddWithValue("@name_book", "your value");

         // http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery%28v=vs.90%29.ASPX
         // insert with ExecuteNonQuery since insert statement is not a query
         int insertCount = cmd.ExecuteNonQuery();
      }
   }
}


[update]

comparison of ExecuteScalar & ExecuteNonQuery

SQL
CREATE TABLE [dbo].[TABLE_A](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [NAME] [varchar](100) NOT NULL,
PRIMARY KEY CLUSTERED
(
    [ID] ASC
)


C#
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string connStr = @"data source=.\sqlexpress; initial catalog=TEST; integrated security=true;";
            string cmdStr = @"insert into TABLE_A(NAME) values(@name)";
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
                {
                    cmd.Parameters.AddWithValue("@name", "my name");
                    dynamic o = cmd.ExecuteScalar();
                    Console.WriteLine(o == null ? "null" : o);

                    o = cmd.ExecuteNonQuery();
                    Console.WriteLine(o == null ? "null" : o);
                }
            }
        }
    }
}


and output:
Quote:
null
1
Press any key to continue . . .
 
Share this answer
 
v4
sir, the answer is just simple try replacing the code with this

SqlCommand add = new SqlCommand("INSERT INTO Data (id_book,id_person,name_book) VALUES (" + textBox7.Text + "," + textBox8.Text + ",'" + textBox9.Text + "')",con);


you missed the quotes in the varchar field.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900