On adding data, it show "Too few parameters. Expected 1" - c#

The problem says:
Too few parameters. Expected 1.
Here's my database table:
CustomerOrder [CustomerOrder(OrderId, ProdName, ProdPrice, OrderQty, CatName, OrderDate]
Code:
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO CustomerOrder(OrderId, ProdName, ProdPrice, OrderQty, CatName, OrderDate)values('" + txtOrderCode.Text + "','" + txtProdName.Text + "', '" + txtProdPrice.Text + "', '" + txtOrderQty.Text + "', '" + txtCatName.Text + "', '" + txtOrderDate.Text + "')";
cmd.ExecuteNonQuery();
tabControl1.SelectedTab = tabPage1;
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
int ordercode, orderqty;
double price;
string prodname, catname;
ordercode = Convert.ToInt32(txtOrderCode.Text);
orderqty = Convert.ToInt32(txtOrderQty.Text);
price = Convert.ToDouble(txtProdPrice.Text);
prodname = Convert.ToString(txtProdName.Text);

I would recommend you use parametrised queries instead as it will prevent you from Sql Injection Attacks. Here is a small example of how it could work with your code
String SqlCommand = "insert into CUSTOMERORDER values (#OrderId, #ProdName,#ProdPrice,#OrderQty, #CatName,#OrderDate)";
SqlCommand cmd = new SqlCommand(SqlCommand , //ConnectionString);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.Parameters.AddWithValue("#OrderId", txtOrderCode.Text);
cmd.Parameters.AddWithValue("#ProdName", txtProdName.Text );
cmd.Parameters.AddWithValue("#ProdPrice", txtProdPrice.Text);
cmd.Parameters.AddWithValue("#OrderQty", txtOrderQty.Text);
cmd.Parameters.AddWithValue("#CatName", txtCatName.Text.Text);
cmd.Parameters.AddWithValue("#OrderDate", txtOrderDate.Text);
cmd.ExecuteNonQuery();
conn.Close();
Read up on Sql Injection attacks. Doing it this way is much easier, cleaner and most importantly, safer. Also when looking at your code you are setting the text box values after you have ran the Sql command

Related

How to get message from SQL query into rich textbox in c#

In SQL Server Management studio, when you do a SELECT query, you also get a message aswell as the results. That message i would like to use in a Rich Textbox. Is that possible?
The Message i'm talking about is this:
I have this code so far, that also fills comboboxes with results, but i would like my rich textbox to show the message aswell:
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT USERNAME FROM PERSONAL", Con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
fromComboBox.Items.Add(reader[0]);
toComboBox.Items.Add(reader[0]);
}
Con.Close();
}
The GUI looks like this:
Use SqlConnection.InfoMessage event,
This event occurs when SQL Servers returns a warning or informational message.
You don't need to look at the message. You can just look at the reader's RowsEffected, like this :
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT USERNAME FROM PERSONAL", Con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
fromComboBox.Items.Add(reader[0]);
toComboBox.Items.Add(reader[0]);
}
var recordsEffected = reader.RecordsAffected;
}
ExecuteNonQuery() - returns the number of rows affected.
SqlCommand comm;
// random code
int numberOfRecords = comm.ExecuteNonQuery();
EDIT:
For select queries you can use ExecuteScalar() -
String sqlQuery = "SELECT count(USERNAME) FROM PERSONAL";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
try
{
conn.Open();
//Since return type is System.Object, a typecast is must
count = (Int32)cmd.ExecuteScalar();
}
I got it all to work. Thanks for the big help. Much apprieciated!
I will show it all if any can use any off it :D
Ended up with this:
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT USERNAME FROM PERSONAL", Con);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
fromComboBox.Items.Add(reader[0]);
toComboBox.Items.Add(reader[0]);
}
}
var countUsers = fromComboBox.Items.Count;
movePostMessage.Text = countUsers + " brugere er fundet";
}
}
And on the button click i've made this:
using (SqlConnection Con = new SqlConnection(Connectionstring.selectedBrugerString))
{
Con.Open();
string SQL1 = "UPDATE DEBSALDO SET PERSONALID = (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + toComboBox.Text + "') WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
string SQL2 = "UPDATE SERVHEAD SET PERSONALID = (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + toComboBox.Text + "') WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
string SQL3 = "UPDATE SERVICEB SET PERSONALID = (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + toComboBox.Text + "') WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
string SQL4 = "UPDATE PERSONAL SET ACOUNTCYID = NULL WHERE PERSONALID IN (SELECT PERSONALID FROM PERSONAL WHERE USERNAME = '" + fromComboBox.Text + "')";
SqlCommand cmd1 = new SqlCommand(SQL1, Con);
SqlCommand cmd2 = new SqlCommand(SQL2, Con);
SqlCommand cmd3 = new SqlCommand(SQL3, Con);
SqlCommand cmd4 = new SqlCommand(SQL4, Con);
Int32 rowsAffectedOnUpdate1 = cmd1.ExecuteNonQuery();
Int32 rowsAffectedOnUpdate2 = cmd2.ExecuteNonQuery();
Int32 rowsAffectedOnUpdate3 = cmd3.ExecuteNonQuery();
Int32 rowsAffectedOnUpdate4 = cmd4.ExecuteNonQuery();
movePostMessage.Text = rowsAffectedOnUpdate1 + " regninger flyttet fra tidligere brugers debitor saldo \r\n" + rowsAffectedOnUpdate2 + " regninger flyttet med tidligere bruger som ejer \r\n" + rowsAffectedOnUpdate3 + " ydelser flyttet med tidligere bruger som ejer \r\n" + rowsAffectedOnUpdate4 + " kontoplan nulstillet";
}
And the GUI to it:

Invalid attempt to call read when reader is closed when inserting data

i have a button that when clicked inserts data from textbox and combobox fields into database tables, but every time i insert it gives me "Invalid attempt to call read when reader is closed". How can i get rid of this error. And tips on optimising the code are welcome, because i know im a total noob. thanks
private void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query1 = "insert into location(Storage, Shelf, columns, rows) values(" + txtWarehouse.Text + ", " + txtShelf.Text + ", " + txtColumn.Text + ", " + txtRow.Text + ")";
SqlCommand sqlCmd = new SqlCommand(Query1, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
sqlCon.Close();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query3 = "SELECT LOCATION_ID FROM LOCATION WHERE storage='" + txtWarehouse.Text + "' AND shelf='" + txtShelf.Text + "' AND columns='"
+ txtColumn.Text + "' AND rows='" + txtRow.Text + "'";
SqlCommand sqlCmd1 = new SqlCommand(Query3, sqlCon);
SqlDataReader dr = sqlCmd1.ExecuteReader(); ;
while (dr.Read())
{
string LocationId = dr[0].ToString();
dr.Close();
string Query2 = "insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID) values ('" + txtSku.Text + "','" + txtNimetus.Text + "', '"
+ txtMin.Text + "', '" + txtMax.Text + "', '" + txtQuan.Text + "', '" + LocationId + "', '" + (cbCat.SelectedIndex+1) + "', '" + (cbMail.SelectedIndex+1) + "')";
SqlCommand sqlCmd = new SqlCommand(Query2, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
}
sqlCon.Close();
}
catch (Exception ed)
{
MessageBox.Show(ed.Message);
}
}
Let's try to make some adjustments to your code.
First thing to consider is to use a parameterized query and not a
string concatenation when you build an sql command. This is mandatory
to avoid parsing errors and Sql Injections
Second, you should encapsulate the disposable objects in a using statement
to be sure they receive the proper disposal when you have finished to
use them.
Third, you can get the LOCATION_ID from your table without running a
separate query simply adding SELECT SCOPE_IDENTITY() as second batch to your first command. (This works only if you have declared the LOCATION_ID field in the first table as an IDENTITY column)
Fourth, you put everything in a transaction to avoid problems in case
some of the code fails unexpectedly
So:
SqlTransaction tr = null;
try
{
string cmdText = #"insert into location(Storage, Shelf, columns, rows)
values(#storage,#shelf,#columns,#rows);
select scope_identity()";
using(SqlConnection sqlCon = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, sqlCon))
{
sqlCon.Open();
using( tr = sqlCon.BeginTransaction())
{
// Prepare all the parameters required by the command
cmd.Parameters.Add("#storage", SqlDbType.Int).Value = Convert.ToInt32(txtWarehouse.Text);
cmd.Parameters.Add("#shelf", SqlDbType.Int).Value = Convert.ToInt32(txtShelf.Text);
cmd.Parameters.Add("#columns", SqlDbType.Int).Value = Convert.ToInt32(txtColumn.Text );
cmd.Parameters.Add("#rows", SqlDbType.Int).Value = Convert.ToInt32(txtRow.Text);
// Execute the command and get back the result of SCOPE_IDENTITY
int newLocation = Convert.ToInt32(cmd.ExecuteScalar());
// Set the second command text
cmdText = #"insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID)
values (#sku, #nimetus,#min,#max,#qty,#locid,#catid,#ordid)";
// Build a new command with the second text
using(SqlCommand cmd1 = new SqlCommand(cmdText, sqlCon))
{
// Inform the new command we are inside a transaction
cmd1.Transaction = tr;
// Add all the required parameters for the second command
cmd1.Parameters.Add("#sku", SqlDbType.NVarChar).Value = txtSku.Text;
cmd1.Parameters.Add("#nimetus",SqlDbType.NVarChar).Value = txtNimetus.Text;
cmd1.Parameters.Add("#locid", SqlDbType.Int).Value = newLocation;
.... and so on for the other parameters required
cmd1.ExecuteNonQuery();
// If we reach this point the everything is allright and
// we can commit the two inserts together
tr.Commit();
}
}
}
}
catch (Exception er)
{
// In case of exceptions do not insert anything...
if(tr != null)
tr.Rollback();
MessageBox.Show(er.Message);
}
Notice that in the first command I use parameters of type SqlDbType.Int because you haven't used single quotes around your text. This should be verified against the real data type of your table columns and adjusted to match the type. This is true as well for the second command where you put everything as text albeit some of those fields seems to be integer (_location_id_ is probably an integer). Please verify against your table.

how to update data without change existing data c# ms access

Hi guys when I want to update without changing old data I get this error
Syntax error (missing operator) in query expression 'data.[Phone Number]+ ' ' +0770444 +'.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE data SET data.[Phone Number] = data.[Phone Number]+ ' ' +"+textBox23.Text+" + WHERE data.([ID]) = " + textBox15.Text + " ";
cmd.Connection = con;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt;
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
MessageBox.Show("Data Updated Successfully");
con.Close();
Start using Command Parameters and you will avoid problems like this:
cmd.CommandText = #"UPDATE data SET [Phone Number] = [Phone Number] + ' ' + #NewPhoneNumber WHERE ID = #ID ";
cmd.Parameters.AddWithValue("#ID", textBox15.Text);
cmd.Parameters.AddWithValue("#NewPhoneNumber", textBox23.Text);
cmd.Connection = con;
Also this will protect you from Sql Injection. Be aware you should provide proper naming of your controls(textboxes), this names means nothing for other programmers. Write your columns together PhoneNumber it is annoying to escape them all the time, you are creating more work for yourself for no reason.
Other points wrap your OleDbConnection and OleDbDataAdapter in using blocks
using(OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb"))
{
con.Open();
//... stuff
DataTable dt;
using(OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
//stuff relate to db adapter
}
}
Using is representing try/catch/finally with calling Dispose() in finally block. This will protect if your code have an exception your connection will be closed. In your current format this is not happening. OleDbDataAdapter is using unmanaged resources so it should be Dispose() too.
Your command seems to be wrong it should be
cmd.CommandText = "UPDATE data SET data.[Phone Number] = " + "'" + data.[Phone Number] + textBox23.Text + "' WHERE data.([ID]) = " + textBox15.Text;
Whereas it is always recommended that we should use the Parameterized Query instead of string concat.
thanks guys I resolved it by this
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE data SET [Phone Number] = [Phone Number]+\n'" + textBox3.Text + "' WHERE ID = " + textBox15.Text + " ";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("New Number Inserted Successfully to ID " + textBox15.Text);
con.Open();

eliminating duplicate records insertion into database

The below is my code to insert gridview data into a database. However, using this I want to check and restrict insertion into the database where records have the same name, location, education and salary. If all of these are the same and those already present in database they should not get inserted. If any one column is different then they should get inserted.
protected void btn_insert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert command", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
UploadStatusLabel.Text = "Records Inserted Successfully";
}
I think hitting the database inside a for loop is a very bad idea when you have other options. I'm not tackling this issue in the below sample.
Your code may be subject to SQL Injection, you need to use parameters to pass your values. If someone filled the input with ";DROP TABLE OpenOfficetext;" and they have DROP permissions, it will be a problem if you're just concatenating strings.
To avoid duplicates, you can check first if a similar record exists.
foreach (GridViewRow g1 in GridView1.Rows)
{
string insertCommand = "insert into OpenOfficetext(Name, Location, Education, Salary) values(#p1, #p2, #p3, #p4)";
string selectCommand = "SELECT COUNT(*) FROM OpenOfficetext WHERE Name = #p1 AND Location = #p2 AND Education = #p3 AND Salary = #p4";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(selectCommand, con);
con.Open();
cmd.Parameters.AddWithValue("#p1", g1.Cells[0].Text);
cmd.Parameters.AddWithValue("#p2", g1.Cells[1].Text);
cmd.Parameters.AddWithValue("#p3", g1.Cells[2].Text);
cmd.Parameters.AddWithValue("#p4", g1.Cells[3].Text);
if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
{
cmd.CommandText = insertCommand;
cmd.ExecuteNonQuery();
}
con.Close();
}
please use the below code
if not exist (select * from OpenOfficetext where Name='" + g1.Cells[0].Text + "' and Location='" + g1.Cells[1].Text + "' and Education = '" + g1.Cells[2].Text + "' and Salary = '" + g1.Cells[3].Text + "' )
Begin
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert into OpenOfficetext(Name,Location,Education,Salary) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
End

Want to create a comment system in asp.net

i am coding for a commenting system in asp.net C# but i am stopped at delete command because of i am not using any type of serial numbers to comments posted, then how can i able to delete a specific comment, i am just using a username, date, time, and text in comment. Can anyone help me please that how to use a delete command in this condition??
here is my code for posting:
protected void pospost_Click(object sender, EventArgs e)
{
string login;
if (HttpContext.Current.Session["UserName"] != null)
{
login = HttpContext.Current.Session["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from mobiles_pos";
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
DataRow rw = ds.Tables[0].NewRow();
rw[0] = Model.Text.ToString();
rw[1] = titlepos.Text.ToString();
rw[2] = txtpos.Text.ToString();
rw[3] = DateTime.Today.Date.ToString();
rw[4] = DateTime.Now.TimeOfDay.ToString();
rw[5] = login.ToString();
ds.Tables[0].Rows.Add(rw);
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd1.CommandText = "insert into mobiles_pos values('" + Model.Text + "','" + titlepos.Text + "','" + txtpos.Text + "','" + DateTime.Today.Date + "','" + DateTime.Now.TimeOfDay + "','" + login + "')";
da.InsertCommand = cmd1;
da.Update(ds);
con.Close();
titlepos.Text = "";
txtpos.Text = "";
//DataList2.DataSource = ds;
//DataList2.DataBind();
BindDataList2();
}
}
Best - Add a Primary key to the "mobiles_pos" table since your using sql just use an identity field it will auto increment for you.
or
Quick - Use a combination of the User name and date comment was intered you must use the full date time or it will delete everything that user entered that day.
"Delete from mobiles_pos where username = #UserName and createdDate = #createdDate"

Categories