ExecuteNonQuery CommandText property has not been initialized - c#

When I click on this button, I face with this error:
executenonquery commandtext property has not been initialized
private void button_FirstStep_Click(object sender, EventArgs e)
{
SqlConnection Conn = new SqlConnection(Yahya.strcon);
Conn.Open();
int CurrentCount = Convert.ToInt32(label_CurrentCount.Text);
string strcom1 = "select * from vm1 where count = '" + (CurrentCount - 1) + "' and benchmarkid = '" + Structure.BenchmarkID + "' ";
SqlCommand cmd = new SqlCommand(strcom1, Conn);
SqlDataReader reader = cmd.ExecuteReader();
string strcom = "";
while (reader.Read())
{
if (reader["vmid"].ToString() != "")
{
string vmid = reader["vmid"].ToString();
strcom += "update vm1 set pmid = (select pmid from vm1 as VM2 where benchmarkid = '" + Structure.BenchmarkID + "' and vm2.count ='" + (CurrentCount - 1) + "' and vm2.vmid ='" + vmid + "' ) where count = '" + CurrentCount + "' and vmid = '" + vmid + "' and benchmarkid = '" + Structure.BenchmarkID + "' \n";
}
}//end of while
reader.Close();
cmd.CommandText = strcom;
cmd.ExecuteNonQuery();
}

Rene is quite right about his comment, looks like your reader.Read() returns false and that's why your code never goes into your while loop and your CommandText is assigned to "", that's why ExecuteNonQuery throws
ExecuteNonQuery: CommandText property has not been initialized
You can check your strcom is empty string or not to solve your problem but I see more wrong things in your code other than that..
Looks like your count column is numeric value but you supplied your CurrentCount - 1 as a character with single quotes. If it is not numeric, it should. Read: Bad habits to kick : choosing the wrong data type
Based on it's name, benchmarkid should(?) be numeric types as well.
You can solve this two problem with using parameterized queries because this kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connection, command and reader automatically instead of calling Close or Dispose methods manually.
Open your connection just before you execute your command.

You could solve this by simply debugging before asking.
The reason for this error is presumably that your first request returns zero results.
So reader.Read() is always false and strcom stays empty. You set an empty string as cmd.CommandText before the call to ExecuteNonQuery().
To solve this, simply check if the string is empty and execute the last query only if it is not empty:
...
reader.Close();
if (!string.IsNullOrEmpty(strcom))
{
cmd.CommandText = strcom;
cmd.ExecuteNonQuery();
}

Related

C# Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

Apologies in advance if I missed an answer to this somewhere but I wasn't quite finding it anywhere. So I'm building an application that scans PDF's of service orders our company gets, parses it, and inserts it into a SQL DB. The problem is at the end of this code. It successfully :
saves the original pdf in the proper folder
scans the pdf and parses it
inserts the correct data into the service order table
grabs PK of service order just created as we need that for the next batch of inserts
Here is where it gets hung up with a Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
I foreach through all the instruments as there are multiples per Service Order, but it is erroring on this somewhere. to be clear I put a break point on the insert statement and all of the data is good and in the proper format ("string" int)
I feel like its in my connection maybe?
Anyways, thanks in advance for the help.
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/PDF/") + filename);
// Now we parse the PDF by creating a new ServiceOrder object and parsing from it.
ServiceOrder so = new ServiceOrder();
// Make sure we load the PDF from the correct path on the server
so.LoadPDF(Server.MapPath("~/PDF/") + filename);
String strConnString = "Data Source=127.0.0.0;Initial Catalog=SOMECATALOG;User ID=SOMEUSER;Password=SOMEPASSWORD";
// Insert Into Service Orders Table
string defaultdate = DateTime.Now.ToString("yyyy-MM-dd");
String strQuery = "insert into TServiceOrders (strServiceOrderNo, intStatusCodeID, strCustomerName, strCustomerNo, strCustomerAddress1, strCustomerAddress2, strCustomerAddress3, intRepID, strServiceDescription, strServiceRequestDate, strServiceOrderDate, strNotes) values ('"
+ so.ServiceOrderNumber.ToString() + "', 2, '"
+ so.CustomerContactName.ToString() + "', '"
+ so.CustomerNumber.ToString() + "', '"
+ so.CustomerContactAddress1.ToString() + "', '"
+ so.CustomerContactAddress2.ToString() + "', '"
+ so.CustomerContactAddress3.ToString() + "', 1, '', '"
+ defaultdate + "', '" + defaultdate + "', '')";
SqlConnection conn = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand(strQuery, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
// Grabbing latest primary key od service order just added for next instrument inserts
int lastid = 999999;
String strPKquery = "select top 1 intServiceOrderID from TServiceOrders order by intServiceOrderID desc";
SqlDataReader rdr = null;
SqlConnection conn2 = new SqlConnection(strConnString);
SqlCommand cmd2 = new SqlCommand(strPKquery, conn2);
try
{
conn2.Open();
rdr = cmd2.ExecuteReader();
while (rdr.Read())
{
lastid = (int)rdr["intServiceOrderID"];
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn2 != null)
{
conn2.Close();
}
}
// Insert Into Service Instruments Tables
SqlConnection conn3 = new SqlConnection(strConnString);
conn3.Open();
foreach (ServiceInstrument sin in so.ServiceInstruments)
{
string sim = "";
sim = sin.ServiceInstrumentModel;
if (String.IsNullOrEmpty(sim))
{
sim = "";
}
else
{
sim = sin.ServiceInstrumentModel.ToString();
}
string sid = "";
sid = sin.ServiceInstrumentDescription;
if (String.IsNullOrEmpty(sid))
{
sid = "";
}
else
{
sid = sin.ServiceInstrumentDescription.ToString();
}
string sis = "";
sis = sin.ServiceInstrumentSerial;
if (String.IsNullOrEmpty(sis))
{
sis = "";
}
else
{
sis = sin.ServiceInstrumentSerial.ToString();
}
string sih = "";
sih = sin.ServiceInstrumentHandle;
if (String.IsNullOrEmpty(sih))
{
sih = "";
}
else
{
sih = sin.ServiceInstrumentHandle.ToString();
}
string sip = "";
sip = sin.ServiceInstrumentParentAsset;
if (String.IsNullOrEmpty(sip))
{
sip = "";
}
else
{
sip = sin.ServiceInstrumentParentAsset.ToString();
}
String strQuery3 = "insert into TServiceInstruments values ('" + sim.ToString() + "', '" + sid.ToString() + "', '" + sis.ToString() + "', '" + sih.ToString() + "', " + sip.ToString() + ", " + lastid + ")";
SqlCommand cmd3 = new SqlCommand(strQuery3, conn3);
cmd3.ExecuteNonQuery();
}
conn3.Close();
When writing insert statements you should always specify the column names. This will protect the code from changes in the order of the columns in the table schema.
You are not using parameters in your sql statements, this leaves your code vulnerable to Sql Injection.
You should use using statements around your SqlConnection instances to ensure they are closed even when an Exception occurs.
Your logic is very difficult to follow, split your code until methods with meaningful names instead of having 1 "God" method that does everything.
If you follow those guidelines the problem will most likely solve itself in your refactoring.
Update Code Fragment
Note that you should always specify the correct types for your columns and the length if applicable. Also pass the actual value and never the string value.
const String strQuery3 = "INSERT INTO TServiceInstruments (sim, sid, sis, sih, sip, lid) VALUES (#sim, #sid, #sis, #sih, #sip, #lid)";
using(var conection = new SqlConnection(strConnString))
using(SqlCommand command = new SqlCommand(strQuery3, connection))
{
command.Parameters.Add(new SqlParameter("#sim", SqlDbType.VarChar, 200){Value = sim});
command.Parameters.Add(new SqlParameter("#sid", SqlDbType.VarChar, 200){Value = sid});
command.Parameters.Add(new SqlParameter("#sis", SqlDbType.VarChar, 200){Value = sis});
command.Parameters.Add(new SqlParameter("#sih", SqlDbType.VarChar, 200){Value = sih});
command.Parameters.Add(new SqlParameter("#sip", SqlDbType.Int){Value = sip});
command.Parameters.Add(new SqlParameter("#lid", SqlDbType.Int){Value = lid});
connection.Open();
command.ExecuteNonQuery();
}
Final note: You really need to learn how to read Exceptions and this includes the Stack Trace which points directly to the line in the call stack where the Exception originated. If you can understand this then debugging becomes much easier.
Maybe this doesn't deserve to be an answer, but I'm trying to build some reputation, so here goes :).
I suspect that your error lies in the "insert into TServiceInstruments ..." statement. Namely, you are giving the table more (or less) columns. As a good practice, always specify the columns, like this:
insert into TServiceInstruments (column1, column2, column3)
values (1, 2, 3)

Retain a value defined inside of a while statement

I'm trying to use the value assigned to the variable BinId outside of the while statement as below:
cmd.CommandText = "SELECT max(binID) from bin";
MySqlDataReader idReader = cmd.ExecuteReader();
int BinId;
while (idReader.Read())
{
BinId = idReader.GetInt32(0);
System.Diagnostics.Debug.WriteLine(BinId);
}
is there a way I can do this?
Edit: This is what I'm trying to do with BinId
cmd.CommandText = "insert into mydb1.missedbin values (null, '" + personIDdata + "','" + dateFound + "','"+ BinId +"')";
Change while to if. This is because you are only getting a single value so there is no need for a while, there will only ever be 1 record. You should also check the value of the resulting binId to ensure it is a positive number (which I assume would be the expected result if there is a record).
int BinId = 0;
cmd.CommandText = "SELECT max(binID) from bin";
// wrap your reader in a using block
using(MySqlDataReader idReader = cmd.ExecuteReader())
{
if (idReader.Read())
{
BinId = idReader.GetInt32(0);
System.Diagnostics.Debug.WriteLine(BinId);
}
if(BinId < 1)
return; // You did not get a value so exit your method or do something....
}
// NOTE: DO NOT DO THIS, always use parameterized queries
cmd.CommandText = "insert into mydb1.missedbin values (null, '" + personIDdata + "','" + dateFound + "','"+ BinId +"')";
About your insert statement, do not write queries like this ever. Always use parameterized queries.

Sending textbox value to sql database

There is a textbox called tbTodo, which gets information from the database:
SELECT `todo` FROM `user` WHERE `username` LIKE '" + _naam + "'";
which works. The problem now is, i have no idea how to update the todo list in the database: how to send the textbox value and overwrite the one from the database. Code i have so far (which could be totally wrong):
db_connection();
MySqlCommand cmdRead = new MySqlCommand();
cmdRead.CommandText = "SELECT `todo` FROM `user` WHERE `username` LIKE '" + _naam + "'";
cmdRead.Connection = connect;
MySqlDataReader tdOphalen = cmdRead.ExecuteReader();
if (tdOphalen.Read())
{
tbTodo.Text = tdOphalen.GetString(0);
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
}
syntax of UPDATE command is
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
In your case it would be something like
"UPDATE `user` set `todo` = '" + tbTodo.Text + "' FROM `user` WHERE `username` LIKE '" + _naam + "'";
It should be good for a first try and learn how update values on a database.
Next steps is learn how to use prepared statement ;)

OleDb Exception

For 5 hour searching i can't find my mistake. I get this exception. What is wrong?
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in MyDictionary.exe
Additional information: Syntax error in INSERT INTO statement.
My code:
public void Insert(Word word)
{
string language=FindLanguage();
try
{
command.CommandText ="INSERT INTO "+language+" ( Native , Foreign , Definition , AddingDate) values ( '" + word.Native + "' , '" + word.Foreign + "' , '" + word.Definition + "' ,'" + word.AddingDate + "')";
command.CommandType = System.Data.CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
You should use parameters in your insert statement.Also looks like you are missing command.Connection = connection;.
Note that your SQL is prone for SQL Injection
command.CommandText ="INSERT INTO "+language+"([Native],[Foreign],[Definition],[AddingDate]) VALUES (#Native,#Foreign,#Definition,#AddingDate)";
command.Parameters.AddWithValue("#Native", word.Native);
command.Parameters.AddWithValue("#Foreign",word.Foreign);
command.Parameters.AddWithValue("#Definition",word.Definition);
command.Parameters.AddWithValue("#AddingDate",word.AddingDate);
command.CommandType = System.Data.CommandType.Text;
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
In OleDb the correct syntax of the INSERT INTO statement involves usage of the SELECT clause even though you're appending static values. So you need to change your query like bellow example.
Further, don't construct try...catch..finally if you don't actually handle a raised exception. In the sake of disposal use using() { } block instead. So here it is:
public void Insert(Word word)
{
string language=FindLanguage();
using (var connection = new OleDbConnection("connection string goes here"))
using (var command = new OleDbCommand...)
{
command.CommandText = #
"INSERT INTO " + language + "(Native, Foreign, Definition, AddingDate)" +
"SELECT '"
+ word.Native + "' AS Native, '"
+ word.Foreign + "' AS Foreign, '"
+ word.Definition + "' AS Definition, '"
+ word.AddingDate + "' AS AddingDate"
;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}

Update statement in MySQL using C#

I've been building a small inventory system for my workplace and have stumbled on an error that I cannot seem to fix
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
// "UPDATE Inventory SET Inventorynumber='"+ num +"',Inventory_Name='"+name+"', Quantity ='"+ quant+"',Location ='"+ location+"' Category ='"+ category+"' WHERE Inventorynumber ='"+ numquery +"';";
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "' Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = serverconnection;
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
I have no idea what to change here.
Any help would be appreciated.
Problem: You are missing the comma after location parameter in your query.
Solution: You need to separate the parameters using a comma.
Suggestion : Use parameterized queries to avoid SQL Injection Attacks.
Try this:
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
// "UPDATE Inventory SET Inventorynumber='"+ num +"',Inventory_Name='"+name+"', Quantity ='"+ quant+"',Location ='"+ location+"' Category ='"+ category+"' WHERE Inventorynumber ='"+ numquery +"';";
string query = "UPDATE Inventory SET Inventorynumber=#Inventorynumber,Inventory_Name=#Inventory_Name, Quantity =#Quantity ,Location =#Location,Category =#Category WHERE Inventorynumber =#Inventorynumber";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Inventorynumber",Convert.ToInt16(num));
cmd.Parameters.AddWithValue("#Inventory_Name",name);
cmd.Parameters.AddWithValue("#Quantity",quant);
cmd.Parameters.AddWithValue("#Location",location);
cmd.Parameters.AddWithValue("#Category",category);
cmd.Parameters.AddWithValue("#Inventorynumber",Convert.ToInt16(numquery));
cmd.Connection = serverconnection;
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
Yes the error is in the missing comma, but this is the result of all that mess with string concatenation that ends always in subtle syntax errors.
Why don't you use a parameterized query? It is a lot simpler to write and you avoid parsing errors like this and (more important) you avoid Sql Injections
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
string query = "UPDATE Inventory SET Inventorynumber=#num, Inventory_Name=#name, " +
"Quantity =#qty,Location =#loc, Category =#cat " +
"WHERE Inventorynumber =#numquery";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, serverconnection);
cmd.Parameters.AddWithValue("#num", Convert.ToInt16(num));
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#qty", quant);
cmd.Parameters.AddWithValue("#loc", location);
cmd.Parameters.AddWithValue("#cat", category);
cmd.Parameters.AddWithValue("#numquery", Convert.ToInt16(numquery));
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
As a side note I have some doubts about some parameters type. Are you sure that quantity is really a string as implied by the presence of quotes around your original value?
Also the numquery and num variables are of type string, you try to convert then to short integer and then you put them inside quotes (meaning that in the database the fields are of type text). This makes no sense at all. If the database expects numbers then do not use quotes, if the database expects strings then do not try to convert. Another reason to use a parameterized query that force you to reflect on these issues.
You are missing a Comma between location and category. You have heard this million times befor i know, but its really much better using prepared statements so you do not have to take care of this kind of things and your code is much more readable.
You missed the comma
Location ='" + location + "', Category ='" + category + "'
// see the `,` between Location and Category
you have missed comma(,) in query:
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "' Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
Make it as:
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "', Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
Try removing the ' single quotes around the integers?

Categories

Resources