Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.11/5 (2 votes)
See more:
I want to know how I can do an insert in an sql database with C #


What I have tried:

string setting = ConfigurationManager.AppSettings["setting1"];
            string conn = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
            using (SqlConnection sqlConn = new SqlConnection(conn))
            {
                //string sqlQuery2 = @"UPDATE testenumserie " + "SET Estado = " + comboBox1.Text + " WHERE NumSerie = '" + textBox2.Text + "'" ;
                string sqlQuery2 = @"INSERT into dbo.testenumserie(Estado) VALUES ('" + comboBox1.Text + "')" + " WHERE NumSerie = '" + textBox2.Text + "'";
                MessageBox.Show(sqlQuery2);
                SqlCommand cmd2 = new SqlCommand(sqlQuery2, sqlConn);
                SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
                DataTable table2 = new DataTable();


I tried this code but the insert did not work.
Posted
Updated 17-Aug-17 2:49am
v2
Comments
Richard Deeming 17-Aug-17 9:50am    
And this is just another version of the same question you posted last week, which is marked as "solved":
https://www.codeproject.com/Questions/1201026/How-to-insert-data-into-a-SQL-table[^]

Hi,

Below is the code to solve the problem.
C#
string connectionstring = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
SqlConnection sqlConn = new SqlConnection(connectionstring);
sqlConn.Open();
 
string sqlQuery2 = @"UPDATE dbo.testenumserie SET ESTADO = @estado WHERE NumSerie = @numSeries"; 

SqlCommand SQLcm = new SqlCommand();
SQLcm.Connection = sqlConn;
SQLcm.CommandText = sqlQuery2;
SQLcm.CommandType = CommandType.Text;
SQLcm.Parameters.AddWithValue("@estado", comboBox1.Text);
SQLcm.Parameters.AddWithValue("@numSeries", textBox2.Text);
SQLcm.ExecuteNonQuery();
sqlConn.Close();
 
Share this answer
 
v8
Comments
PedroAzevedo1234 17-Aug-17 8:20am    
Give this error "System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'WHERE'.'"
PedroAzevedo1234 17-Aug-17 8:27am    
this error appered "
System.Data.SqlClient.SqlException occurred
HResult = 0x80131904
Message = Can not insert the value NULL into column 'NumSeries', table 'testedopedro.dbo.testenumserie'; Column does not allow nulls. INSERT fails."
PedroAzevedo1234 17-Aug-17 8:28am    
But my table allows nulls as you can see in this print http://prntscr.com/g9lzib
Sheila Pontes 17-Aug-17 8:31am    
Hi,
To use the "where" clause in the insert, you need to use insert with select command. I change the code above correcting the insertion.
This article can help you undestand better.
https://technet.microsoft.com/pt-br/library/ms188263(v=sql.105).aspx
Sheila Pontes 17-Aug-17 8:38am    
Hi,
insert the value also in the numseries column.
 
string sqlQuery2 = @"INSERT into dbo.testenumserie(Estado, NumSerie) SELECT '" + comboBox1.Text + "', '" + textBox2.Text + '" from dbo.testenumserie WHERE NumSerie = '" + textBox2.Text + "'";
Oki first of all, consider reading up on sql injection, because you REALLY don't want to use variables directly from a user interface in a query.

Update Estado in a specific numseries

C#
string estado = CheckMyUiValues(comoBox1.Text); //Must make that method ;)
string nums = CheckMyUiValues(comoBox1.Text);

var sql = "UPDATE dbo.testenumserie SET ESTADO = '{0}' WHERE NUMSERIE = '{1}'";
using(var cn = new GetOpenConnection()){   //Could have a method to make here too
    using(var cmd = new SqlCommand(cn, string.format(sql, estado, nums)){
        cmd.ExecuteNonQuery();
    }
}


or in a somewhat more crude way
C#
string estado = comoBox1.Text; 
string nums = comoBox1.Text;
//TODO: Implement ui variable checking
var sql = "UPDATE dbo.testenumserie SET ESTADO = '{0}' WHERE NUMSERIE = '{1}'";
string conn = "put your connection string details in here";
using(var cn = new SqlConnection(conn)){   
    using(var cmd = new SqlCommand(cn, string.Format(sql, estado, nums)){
        cmd.ExecuteNonQuery();
    }
}
 
Share this answer
 
v4
Comments
PedroAzevedo1234 17-Aug-17 8:55am    
I need to change the value of the "Estado" of a specific "NumSerie"
Thomas Nielsen - getCore 17-Aug-17 9:00am    
ok, please see updated suggestion
PedroAzevedo1234 17-Aug-17 9:05am    
It give me error with this "CheckMyUiValues" and this "GetOpenConnection" and this "format"
Thomas Nielsen - getCore 17-Aug-17 9:08am    
:) it's not just copy paste friend. I'm implying you'll make a method CheckMyUiValues to prevent sql injection and GetOpenConnection To instantiate a connection and open it .... if you dont want to remove CheckMyUiValues method and assign directly and just new up an SqlConnection with your appropriate sql connection string ... just not something i'd write myself or incourage anybody to. Oh and string.Format should have a capital F.
PedroAzevedo1234 17-Aug-17 9:11am    
the string.format give me a error is not possible to conver to system.data.SqlClient.SqlConnection
To execute your sql you would do cmd2.ExecuteNonQuery();. You do not need the DataAdapter nor the DataTable.

You'll also want to change to using parameters. Your code is very insecure right now. Your database could be easily hacked. Instead do something like:
C#
string sqlQuery2 = @"INSERT into dbo.testenumserie(Estado) VALUES (@estado) WHERE NumSerie = @numSeries";            
...
cmd2.Parameters.AddWithValue("@estado", comboBox1.Text);
cmd2.Parameters.AddWithValue("@numSeries", textBox2.Text);
cmd2.ExecuteNonQuery();


Also, you should name your controls using better names. For example, your textBox2 should be named txtNumSeries. It will save you a lot of time later on to name your controls properly.
 
Share this answer
 
Comments
PedroAzevedo1234 17-Aug-17 8:15am    
It gives a error "System.InvalidOperationException:ExecuteNonQuery requires an open and available Connection."
ZurdoDev 17-Aug-17 8:16am    
You need to open the connection.
PedroAzevedo1234 17-Aug-17 8:19am    
And now it says this error "System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'WHERE'.'"
ZurdoDev 17-Aug-17 8:20am    
Then fix the Syntax. Just do whatever the error tells you to do.
PedroAzevedo1234 17-Aug-17 8:21am    
How can I fix this ?

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