SqlConnection cn = new SqlConnection(@"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******");
SqlCommand cmd = new SqlCommand();
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=@finish where Name='" + Name + "'";
cmd.Parameters.Add(new SqlParameter("@finish", finish));
cmd.ExecuteNonQuery();
cmd.Clone();
The error message
Executenonquery connection property has not been initialized.
John Saunders
161k26 gold badges247 silver badges397 bronze badges
asked Apr 6, 2013 at 16:02
0
the problem with your current code is that you have not set the Connection
property of the SqlCommand
object. Try this,
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
and you must also parameterized the values set on the name
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=@finish where Name=@name";
cmd.Parameters.Add(new SqlParameter("@finish", finish));
cmd.Parameters.Add(new SqlParameter("@name", Name));
FULL CODE
string finish = DropDownListFi.SelectedValue;
String Name = Request.QueryString["Name"];
string connStr = @"DataSource=dbedu.cs.vsb.cz\SQLDB;
Persist Security Info=True;
User ID=*****;
Password=*******";
string sqlStatement = @"UPDATE navaznost_ukolu
SET finish = @finish
WHERE Name = @Name";
using (SqlConnection conn = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sqlStatement;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@finish", finish));
cmd.Parameters.Add(new SqlParameter("@name", Name));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}
For proper coding
- use
using
statement for propr object disposal - use
try-catch
block to properly handle objects
answered Apr 6, 2013 at 16:03
John WooJohn Woo
259k69 gold badges498 silver badges492 bronze badges
0
The error is self-explanatory, you have not assigned the connection to the command. You can use the constructor:
using(var cn = new SqlConnection(@"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******"))
using(var cmd = new SqlCommand(
"UPDATE navaznost_ukolu SET finish=@finish where Name=@Name"
, cn))
{
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.Parameters.AddWithValue("@finish", finish);
cmd.Parameters.AddWithValue("@Name", Name);
cmd.ExecuteNonQuery();
}
Note that i’ve also used a sql-parameter for the Name
and using
statements to ensure that anything implementing IDisposable
gets disposed, even in case of an exception. This will also close the connection.
answered Apr 6, 2013 at 16:05
Tim SchmelterTim Schmelter
451k74 gold badges686 silver badges939 bronze badges
I am building a database using Visual Studio 2008 c# and when I’m a trying to insert a new record into my database it appears that ExecuteNonQuery
has not initialized. I copy my code, hope anyone can help me in this because I am new.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd.CommandText = "insert into Database1.mdf(Codigo,Nombre,Cantidad,Tipo) values('"+comboBox1.Text+"','"+textBox3.Text+"','"+textBox1.Text+"','"+comboBox2.Text+"')";
cmd.ExecuteNonQuery();
cmd.Clone();
cn.Close();
MessageBox.Show("Acabas de agregar un producto");
}
marc_s
734k176 gold badges1332 silver badges1460 bronze badges
asked Jun 3, 2013 at 18:29
5
You haven’t set the connection to your command:
cmd.Connection = cn;
Eran
388k54 gold badges702 silver badges768 bronze badges
answered Jun 3, 2013 at 18:31
Fabian BiglerFabian Bigler
10.5k6 gold badges47 silver badges70 bronze badges
1
You have numerous problems in your code:
- First: The
insert into
statement requires a target datatable not the name of
the MDF file - Second: Employ the using statement to close and dispose the connections
- Third: Parametrized query to avoid parsing problems and sql
injections -
Fourth: You need to associate the connection to the command (Easily
done at the SqlCommand constructor)using(SqlConnection cn = new SqlConnection(.......)) using(SqlCommand cmd = new SqlCommand("insert into table_name(Codigo,Nombre,Cantidad,Tipo)" + "values (@cod, @nom,@can,@tipo)", con)) { cn.Open(); cmd.Parameters.AddWithValue("@cod", comboBox1.Text); cmd.Parameters.AddWithValue("@nom", textBox3.Text); cmd.Parameters.AddWithValue("@can", textBox1.Text); cmd.Parameters.AddWithValue("@tipo", comboBox2.Text); cmd.ExecuteNonQuery(); MessageBox.Show("Acabas de agregar un producto"); }
EDIT
The information provided by the link added by @RemusRusanu below is very important. The use of AddWithValue, whilst handy, could hinder the performance of your query. The correct approach should be the usage of a proper defined SqlParameter with both explicit datatype and parameter size.
As an example
SqlParameter p = new SqlParameter("@cod", SqlDbType.NVarChar, 255).Value = comboBox1.Text;
cmd.Parameters.Add(p);
But, of course, this requires that you check the exact datatype and size of your columns.
answered Jun 3, 2013 at 18:39
SteveSteve
214k22 gold badges232 silver badges286 bronze badges
6
You did not initialize your SqlCommand
with a connection. Also, you should really enclose everything here with using
. And consider using parametarized commands to avoid SQL Injection.
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into databaseTableName (Codigo,Nombre,Cantidad,Tipo) values (@Codigo, @Nombre, @Cantidad, @Tipo)";
cmd.Parameters.AddWithValue("@Codigo", comboBox1.Text);
cmd.Parameters.AddWithValue("@Nombre", textBox3.Text);
cmd.Parameters.AddWithValue("@Cantidad", textBox1.Text);
cmd.Parameters.AddWithValue("@Tipo", comboBox2.Text);
cmd.Connection = cn; //this was where the error originated in the first place.
cn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Acabas de agregar un producto");
}
}
}
answered Jun 3, 2013 at 18:33
Evan LEvan L
3,8051 gold badge22 silver badges31 bronze badges
1
- Remove From My Forums
-
Question
-
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim connetionString As String, connection As SqlConnection, cmd As SqlCommand connetionString = "Server=MyServerNameHere;Database=MyDB;User Id=MyUserID;Password=MyPassword;" connection = New SqlConnection(connetionString) connection.Open() cmd = New SqlCommand("insert into MyTable (MyField) values (@MyField)") cmd.Parameters.AddWithValue("@MyField", Me.TextBox1.Text) cmd.ExecuteNonQuery() connection.Close() MsgBox("Detail sucussfully Added") End Sub
I am getting error in the cmd.ExecuteNonQuery() line of code. Not sure what I am doing wrong. Please advice.
-
Edited by
Tuesday, February 2, 2016 7:23 AM
-
Moved by
Bob Beauchemin
Tuesday, February 2, 2016 5:16 PM
Moved to client-side SqlClient forum for best response
-
Edited by
Answers
-
You haven’t assign the connection to the command object; Change your code in this way by adding «Connection» as second Parameter to SqlCommand instanziation:
connetionString = "Server=MyServerNameHere;Database=MyDB;User Id=MyUserID;Password=MyPassword;" connection = New SqlConnection(connetionString) connection.Open() cmd = New SqlCommand("insert into MyTable (MyField) values (@MyField)", connection) cmd.Parameters.AddWithValue("@MyField", Me.TextBox1.Text) cmd.ExecuteNonQuery() connection.Close() MsgBox("Detail sucussfully Added")
Olaf Helper
[ Blog] [ Xing] [ MVP]
-
Edited by
Olaf HelperMVP
Tuesday, February 2, 2016 7:59 AM -
Marked as answer by
SixthS.e.n.s.e
Tuesday, February 2, 2016 10:44 AM
-
Edited by
Вам нужно назначить соединение SqlCommand
, вы можете использовать конструктор или свойство:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");
cmd.InsertCommand.Connection = connection1;
Я настоятельно рекомендую использовать using-statement
для любого типа, реализующего IDisposable
как SqlConnection
, он также закроет соединение:
using(var connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True"))
{
SqlDataAdapter cmd = new SqlDataAdapter();
using(var insertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) "))
{
insertCommand.Connection = connection1;
cmd.InsertCommand = insertCommand;
//.....
connection1.Open();
// .... you don't need to close the connection explicitely
}
}
Кроме того, вам не нужно создавать новое соединение и DataAdapter
для каждой записи в foreach
, даже если создание, открытие и закрытие соединения означает не, означает, что ADO.NET создаст, откроет и закроет соединение физическое, но просто заглянет в пул соединений для доступного подключения. Тем не менее это лишние накладные расходы.
See more:
I have the following code on an update button in WinForms VS 2017.
private void btnEdit_Click(object sender, EventArgs e) { if (txtOrder.Text != "") { cmd = new SqlCommand("UPDATE AER_INBOUND_PLASTICS SET [STATUS]=@status,[DATE]=@date,[SOPO_NO]=@order,[SHIPPER]=@shipper,[VENDOR]=@vendor,[WAREHOUSE]=@warehouse,[COMMENTS]=@comments,[PURCH_PART_CODE]=@part1,[PURCH_PART_CODE_2]=@part2,GETDATE(),[MODIFIED_BY]=@user WHERE ID=@id", con); con.Open(); cmd.Parameters.AddWithValue("@id", ID); cmd.Parameters.AddWithValue("@status", comboBoxStatus.SelectedItem.ToString()); cmd.Parameters.AddWithValue("@date", txtLoadtime.Text); cmd.Parameters.AddWithValue("@order", txtOrder.Text); cmd.Parameters.AddWithValue("@shipper", txtShipper.Text); cmd.Parameters.AddWithValue("@vendor", txtVendor.Text); cmd.Parameters.AddWithValue("@warehouse", comboBoxWarehouse.SelectedItem.ToString()); cmd.Parameters.AddWithValue("@comments", txtComments.Text); cmd.Parameters.AddWithValue("@part1", txtPart1.Text); cmd.Parameters.AddWithValue("@part2", txtPart2.Text); cmd.Parameters.AddWithValue("@user", Environment.UserName); cmd.ExecuteNonQuery(); MessageBox.Show("Record Updated Successfully."); con.Close(); dataGridView1.Refresh(); ClearData(); } else { MessageBox.Show("Please Select Record to Update."); } }
The form loads correctly, and the textboxes are populated correctly from the DataGridView SelectedRow. When I modify the textboxes and click on the update button, I get the following error on the cmd.ExecuteNonQuery() line: Additional information: Incorrect syntax near ‘(‘.
I can’t see any parentheses missing anywhere. I can’t seem to track down where the error is in the update process.
What I have tried:
I scoured the code and did find a square bracket missing in the SqlCommand statement, but fixing that has not resolved the problem. I am following the instructions on this site (http://www.c-sharpcorner.com/uploadfile/1e050f/insert-update-and-delete-record-in-datagridview-c-sharp/)