So, I have been trying to fix this for about two months. It all started when my "dev" machine went kaput and I set it up on my laptop. It was working fun on my old PC but, it does not work on my new PC and never did on laptop.
I structured the SQL Server as much like the first one as I could remember but, it started giving me SQLExceptions. I googled it, I searched on here for it, I tried different solutions. Nothing.
I will post the offending code and I am hoping someone will be able to help me see my flaw. I am sure it is something stupid.
SqlCommand sc = sqlc.CreateCommand();
sc.CommandText = "SELECT pNumber FROM database WHERE pNumber = '" + Number.ToString() + "'";
SqlDataReader sdr = sc.ExecuteReader();
if (sdr.Read().ToString() != null)
{
sdr.Close();
sc.CommandText = "UPDATE word SET word = '" + Word + "' WHERE pNumber = '" + Number.ToString() + "'";
HERE IS WHERE THE ERROR OCCURS----> sc.ExecuteReader();
}
else
{
sdr.Close();
sc.CommandText = "INSERT INTO database VALUES(" + Number.ToString() + ",'" + Word + "',0, 0, 0)";
sc.ExecuteNonQuery();
sc.CommandText = "SELECT * FROM database WHERE pNumber = '" + Number.ToString() + "'";
SqlDataReader dataRead = sc.ExecuteReader();
for (int x = 0; x < 6; ++x)
{
User[x] = dataRead.GetString(x);
}
}
sqlc.Close();
EDIT: SqlException: Invalid object name: 'word'.
at System.Data.SqlClient.SqlConnection.OnError(...
Change your input values to parameters. It's much safer, and might fix your issue if it's a problem caused by accidental SQL injection.
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx
Like this:
sc.CommandText = "INSERT INTO database VALUES(#number,#word,0, 0, 0)";
sc.Parameters.Add("#number", SqlType.Int).Value = number;
sc.Parameters.Add("#word", SqlType.Int).Value = Word
sc.CommandText = "UPDATE word SET word = '" + Word + "' WHERE pNumber = '" + Number.ToString() + "'";
should probably read
sc.CommandText = "UPDATE database SET word = '" + Word + "' WHERE pNumber = '" + Number.ToString() + "'";
I changed the tablename in the SQL query, that is all.
Where your code reads
sc.CommandText = "SELECT pNumber FROM database WHERE pNumber = '" + Number.ToString() + "'";
does that mean your user-defined database is actually named "database"? The word "database" is a reserved word, and this could be causing you grief.
Related
This question already has answers here:
SQL update statement in C#
(10 answers)
Closed 5 years ago.
enter image description here
I am trying to update data in a SQL Server table. I get a message that data is saved, after a query execution.
But when I check in that table, I find that the data is not saved. Is anything wrong in my query?
I am using SQL Server 2008 and C# for coding.
SqlCommand cmd1 = new SqlCommand("UPDATE Inward_Rpt SET Date='" + date + "',Cashier_Name='" + cashier_name + "',Supplier_Code='" + sup_code + "',Supplier_Name='" + name + "',Payment_Mode ='" + p_method + "',Total_Bill='" + tot_bill + "',Total_Paid='" + tot_paid + "',Previous_Due = '" + total_due + "',Current_Due ='" + c_due + "',Remark ='" + remark + "'WHERE Supplier_Name='" + name + "'", con);
cmd1.ExecuteNonQuery();
MessageBox.Show("Data Saved..");
I think I found your error. Your WHERE clause is using the same name that you are updating the Supplier Name to. Assuming this is a new name, you will never find the record you want to update. The below code is cleaner, not prone to injection issues, and it should work the way you want.
Note that you will have to provide a new variable to cater to the name / sup_name situation.
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd1.CommandText = #"
UPDATE Inward_Rpt
SET Date = #date
, Cashier_Name = #cashier_name
, Supplier_Code = #sup_code
, Supplier_Name = #sup_name
, Payment_Mode = #p_method
, Total_Bill = #tot_bill
, Total_Paid = #tot_paid
, Previous_Due #total_due
, Current_Due = #c_due
, Remark = #remark
WHERE Supplier_Name = #name";
cmd1.Parameters.AddWithValue("#date", date);
cmd1.Parameters.AddWithValue("#cashier_name", cashier_name);
cmd1.Parameters.AddWithValue("#sup_code", sup_code);
cmd1.Parameters.AddWithValue("#sup_name", sup_name);
cmd1.Parameters.AddWithValue("#p_method", p_method);
cmd1.Parameters.AddWithValue("#tot_bill", tot_bill_name);
cmd1.Parameters.AddWithValue("#tot_paid", tot_paid);
cmd1.Parameters.AddWithValue("#total_due", total_due);
cmd1.Parameters.AddWithValue("#c_due", c_due);
cmd1.Parameters.AddWithValue("#remark", remark);
cmd1.Parameters.AddWithValue("#name", name);
cmd1.ExecuteNonQuery();
MessageBox.Show("Data Saved..");
Is the All the Fields are String Datatype in your Database Table? Check the Datatypes Because u give Single Quotes for all Data. If the Table Datatype is Number Remove the Single Quotes.
SqlCommand cmd1 = new SqlCommand("UPDATE Inward_Rpt SET Date='" + date + "',Cashier_Name='" + cashier_name + "',Supplier_Code=" + sup_code + ",Supplier_Name='" + name + "',Payment_Mode ='" + p_method + "',Total_Bill='" + tot_bill + "',Total_Paid='" + tot_paid + "',Previous_Due = '" + total_due + "',Current_Due ='" + c_due + "',Remark ='" + remark + "'WHERE Supplier_Name='" + name + "'", con);
This is my code:
OleDbConnection con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + "/shoping mall.mdb");
con.Open();
OleDbCommand cmd = new OleDbCommand("update RecordofItems set RecordofItems.Bill_no = " + textBox1.Text + ", RecordofItems.Received_from = '" + textBox62.Text + "', RecordofItems.Item_Code = " + textBox2.Text + ", RecordofItems.Quantity = " + textBox32.Text + ", RecordofItems.Sale_Rate = " + textBox47.Text + " where Item_Name = '" + textBox17.Text + "'", con);
int x = 0;
x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("record deleted" + x);
}
else
{
MessageBox.Show("no record exixt");
}
con.Close();
I want to update selected columns in my "RecordofItems" table that has 10 columns but I want to update only 6 selected columns, when I run the query it shows error "no value for one or more required paremeter" What to do ? please help me as soon as you can.
the error No value given for one or more required parameters usually comes when you have misplaced single quote.
try these two.
try assigning your numerical db columns a numerical value viz update your query with these:
RecordofItems.Bill_no = " + Convert.ToInt32(textBox1.Text) + ",
RecordofItems.Item_Code = " + Convert.ToInt32(textBox2.Text) + ",
RecordofItems.Quantity = " + Convert.ToInt32(textBox32.Text) + ",
RecordofItems.Sale_Rate = " + Convert.ToInt32(textBox47.Text) +
or use whatever suitable numerical converter applies to your columns.
one of your text fields might have a single quote in it, so try replacing/updating your text fields like this:
RecordofItems.Received_from = '" + textBox62.Text.Replace("'","''") + "',
so basically, replace single quote with two single quotes.
see if these solve your issue.
Also, do note, never create your sql query by concatenating textboxes(strings). use command parameters. they will save you from sql injection.
I have to update table on SQL Server but first i have to check for existing data in table so if data is there update it, if not make a new insert:
cmd_sql.CommandText = " SELECT BrDok as id_dok " +
" FROM ordersstavke " +
" WHERE SifParFil = '" + rw_mat["sifskl_kor"] + "'" +
" AND DokumentTip = '" + rw_mat["vrst_dok"] + "'";
MySqlDataAdapter sql_adapter = new MySqlDataAdapter(cmd_sql);
DataSet dt_dok = new DataSet("DOK_MAT_EXCHANGE");
sql_adapter.Fill(dt_dok);
if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
{
myQuery = " INSERT INTO ordersstavke (BrDok, DocumentTip, SifParFil) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["vrst_dok"] + "', '" +
rw_mat["sifskl_kor"] + "')";
}
else
{
UPDATE DATA
}
But I have an error in the code, the error is here if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
Object reference not set to an instance of an object.
The problem is in this if statement...
DOK_MAT_EXCHANGE is the name of the DataSet, not of the first table.
You should test with
if (dt_dok.Tables[0].Rows.Count == 0)
Also, I think is better to use a syntax like this to discover how many records are presents
cmd_sql.CommandText = "SELECT COUNT(BrDok) as id_dok " +
" FROM ordersstavke " +
" WHERE SifParFil = ?p1 " +
" AND DokumentTip = ?p2";
cmd_sql.Parameters.AddWithValue("?p1", rw_mat["sifskl_kor"] );
cmd_sql.Parameters.AddWithValue("?p2", rw_mat["vrst_dok"] );
int rowCount = (Int32)cmd_sql.ExecuteScalar();
change
DataSet dt_dok = new DataSet("DOK_MAT_EXCHANGE");
to
DataSet dt_dok = new DataSet("ordersstavke ");
and
if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
to
if (dt_dok.Tables["ordersstavke "].Rows.Count == 0)
Accessing the first table via the dataset name is incorrect, that's for setting the XML.
Instead use
dt_dok.Tables[0].Rows.Count;
That being said, you're better off writing this as a single SQL statement instead of a separate select && insert. This way you're not going to the DB multiple times.
var sql = #"if exists(select * from ordersstavke where SifParFil = ? and DokumentTip = ?)
then
-- do insert statement
else
-- do update
end if";
This might also be better done with a stored proc, so you don't have as much SQL code in C#. It's easier to manage multiple operations that way.
And for crying out loud, use SqlParameters, not string concatenation! That's just asking for trouble!
Ok, thanks guys, I wrote it like this
if (ds_dok.Tables[0].Rows.Count <= 0)
{
myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "')";
}
else if (ds_dok.Tables[0].Rows.Count >= 1)
{
myQuery = "UPDATE ordersstavke " +
"SET BrDok = '" + rw_mat["brdok"] + "', " +
"SifParFil = '" + rw_mat["sifskl_kor"] + "', " +
"WHERE BrDok = " + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString() + "'";
}
But there is a small problem in the section update: s_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString(), here it give me that loving error : Object reference not set to an instance of an object.
Maybe the update on MySQL goes on different way, I'm referencing on example on sql server and there update goes differently
String strSql = "insert into BaseData (Item," + dataGridView1.Columns[3].Name + "," + dataGridView1.Columns[4].Name + ") values ('" + row.Cells[0].Value + "','" + row.Cells[3].Value + "','" + row.Cells[4].Value + "')";
objCmd = new OleDbCommand(strSql, lConn);
objCmd.ExecuteNonQuery();
strSql = "select id from BaseData where Item = '" + row.Cells[0].Value + "' and " + dataGridView1.Columns[1].Name + " = '" + row.Cells[3].Value + "' And " + dataGridView1.Columns[2].Name + " = '" + row.Cells[4].Value + "'";
OleDbCommand command = new OleDbCommand(strSql, lConn);
OleDbDataReader reader = command.ExecuteReader();
String id = "";
while (reader.Read())
{
id = reader.GetString(0);
}
reader.Close();
strSql = "insert into tranjaction (Base_id,quentity,price,other) values ('" + id + "' , ' " + row.Cells[2].Value + "','" + row.Cells[1].Value + "')";
objCmd = new OleDbCommand(strSql, lConn);
objCmd.ExecuteNonQuery();
When I run this, Microsoft Visual Studio Error occur on Line 10. (ExecuteReader)
The Error is here.
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: No value given for one or more required
parameters.
How could I fix this error?.
Either your field names are wrong (quentity?) or it's because you have unbalanced fields to parameters. You are inserting into 4 fields, but you are only supplying 3 values. Use parameters instead, it would make your life easier.
Try changing it to this:
strSql = "insert into tranjaction (Base_id,quentity,price,other) values (#id , #quentity, #price, #other)";
using (OleDbCommand cmd = new OleDbCommand(sqlSql, IConn)) {
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#quentity", row.Cells[2].Value);
cmd.Parameters.AddWithValue("#price", row.Cells[1].Value);
cmd.Parameters.AddWithValue("#other", other); // <- missing
cmd.ExecuteNonQuery();
}
When I've received this error in the past it has always been because of a simple typo. Like the others have mentioned it looks like you spelled "quantity" wrong which could be part of the problem.
In this line
strSql = "insert into tranjaction (Base_id,quentity,price,other) values ('" + id + "' , ' " + row.Cells[2].Value + "','" + row.Cells[1].Value + "')";
you are inserting 4 values (Base_id,quentity,price,other), but you are only inserting 3 values (id, row.Cells[2].Value, row.Cells[1].Value). Giving a value for other should fix the problem.
Another thing that would cause this error, which is probably your situation, is if you've spelled one of the column names incorrectly. And since you are using column names from your datagridview, and some of your written column names seem mis-spelled, you should double check the spelling in your query strings.
Okay, so in the past few weeks I've probably written about 40 select statements. So, I know how to do it. And I've just written another one, but this time I need to use ComboBox values to match against, and it keeps resulting in the names of the column (the right column, mind you), instead of what's inside the column.
string st = "SELECT '" + txtchange.Text + "'
FROM mysql_9269_dbase." + pages.Text + "";
MySql.Data.MySqlClient.MySqlCommand cd = new MySql.Data.MySqlClient.MySqlCommand(st, msc);
cd.CommandType = CommandType.Text;
MySql.Data.MySqlClient.MySqlDataReader msdr = cd.ExecuteReader();
while(msdr.Read())
{
txt.Text = msdr[0].ToString();
}
Now, why is it returning the column name instead of the content of that column?
Lose the single quotes.
Change
"SELECT '" + txtchange.Text + "' "
to
"SELECT " + txtchange.Text + " "
In sql you can do it like this.
string query = "Execute("+"'SELECT " + txtchange.Text + " FROM mysql_9269_dbase." + pages.Text + "')";