I am creating a Windows Forms application and now at certain point I need to make a database connection, I have inserted the values to database easily, but now its not updating my data, I am using following query for this purpose:
MySqlCommand sda = new MySqlCommand(#"Update shedulling.tablelayout1 set date = '"
+ date + "',line = " + line + ",col1 = '" + first_textbox.text + "', col2 = '"
+ sec_textbox.text + "',col3_textbox.text = '" + thi_textbox.text
+ "',col4_textbox.text = '" + four + "' where date = '" + date + "' AND line = '"
+ line.ToString() + "' ", conn);
conn is a connection string which is written fine, and date and line are string and integer values send as an argument to this function.
You have missed single quotes in line part. Change it like this line = '" + line + "'.
Also there is one more notable thing in your code: you are trying to find the record in the table that is not exist yet in where clause where date = '" + date + "' AND line = '" + line.ToString() + "' note in this line date and line are the new values not old values so no rows affected in the update query. You should use old values of date and line in the where clause.
Also you should always use parameterized queries. This kind of string concatenations are open for SQL Injection.
Try debugging the code, there must be INSERT statement executing somewhere in your code.
UPDATE: If "line" is integer variable then you need to convert it into string. You have converted it after WHERE clause but not after SET clause.
You may want to post some more code to get exact answer.
Related
I am using WinForms and I want to use SQL if statement in my code.
Here is a small example. I am using SQL long query and I want to use IF statement to do two different functions. Here is example.
string query =
"SELECT U1.UserID,
U1.FirstName,
U1.LastName,
C1.UserID,
C1.FriendID
FROM USERS U1
INNER JOIN Chat C1 ON U1.UserID = C1.UserID
WHERE C1.UserID = '" + MyName.Uid + "'
AND C1.FriendID = '" + friendid + "'
OR C1.UserID = '" + friendid + "'
AND C1.FriendID = '" + MyName.Uid + "'
ORDER BY C1.ChatID";
There is some more stuff in there. But here is what I need. I know this gonna be wrong, I need someone to help me to write correct if statement.
if (C1.UserID = '" + MyName.Uid + "' and C1.FriendID = '" + friendid + "') {
// some code.
}
You cannot use use SQL Query this way.
First you have to execute your query to get data from database. Once you have it, you can do your if statement to get what you wanted.
And for your if statement you should use Equals to test strings equality.
if (C1.UserID.Equals(someString) && C1.FriendID.Equals(anotherString))
{
//some code.
}
I'm having problem with regards to update my database when I remove a row/s in my datagrid.
I tried using RowsRemoved event but it returns me an error that there is no value in the row deleted.
So when I try searching I have come to this similar problem, all similar problems I have found so far is by adding or subtracting a certain number (like + 1 or - 1). So I matched the code with my parameters.
private void dataGridSales_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
using (SqlConnection conn = new SqlConnection(#"Server=" + ip + "," + port + "; Database=records; User ID=" + sqlid + "; Password=" + sqlpass + ""))
{
conn.Open();
int addqty = Convert.ToInt32(dataGridSales.SelectedRows[0].Cells[1].Value.ToString());
string part = dataGridSales.SelectedRows[0].Cells[5].ToString();
using (SqlCommand cmd = new SqlCommand(#"UPDATE [dbo].[products]
SET Quantity = [Quantity] + '" + addqty + "' WHERE [Part No.] = '" + part + "'", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
The problem is, it did not update my database. I also tried this in my SQL
Quantity = Quantity + '" + addqty + "'
Quantity += '" + addqty + "'
Im using SQL Server 2014
This is the value of the addqty and part at the breakpoint
This are my datagridview columns. ColumnIndex = 5 is where the part value, and RowIndex is the selected row.
EDIT:
I have solve the issue. It was a minor mistake that I wasn't checking the syntax correctly (even there are no errors shown).
string part = dataGridSales.SelectedRows[0].Cells[5].ToString();
Forgot to add .Value
string part = dataGridSales.SelectedRows[0].Cells[5].Value.ToString();
Quantity = Quantity + '" + addqty + "'
You define addqty as an int but use it as a string in the SQL. Remove the single quotes to use the value as a number rather than text.
Quantity = Quantity + " + addqty + "
try to replace dataGridSales.SelectedRows[0].Cells[1].Value.ToString() anddataGridSales.SelectedRows[0].Cells[5].ToString(); by
dataGridSales.SelectedRows[e.RowIndex].Cells[1].Value.ToString();
dataGridSales.SelectedRows[e.RowIndex].Cells[5].ToString();
layout and db
if (!(string.IsNullOrEmpty(b.ToString())))
{
string connection = "server=127.0.0.1; database=accounts;user=root; password='';";
MySqlConnection conn = new MySqlConnection(connection);
conn.Open();
string SQL = "INSERT INTO payment_voucher (voucher_no, paid_to, date, account_cr, account_dr, description, student_emp_id, amount, total ) values ('" + label8.Text.ToString() + "','" + textBox1.Text + "', '" + dateTimePicker1.Value + "','" + a + "','" + b + "', '" + richTextBox1.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + label11.Text.ToString() + "');";
MySqlCommand command = new MySqlCommand(SQL, conn);
command.ExecuteNonQuery();
conn.Close();
}
i dont know why it is happening. front end is in C#.
That statement will not insert two rows.
You have a few things to check here:
Check if that code is being called twice
Check if there is other similar code that is also being called
Make sure there are no triggers on the table that do an additional insert
Make sure you don't have some weird Try/Catch/Fail logic that causes that entire thing to be run again
And most importantly:
Run a SQL Profiler trace to see exactly what is being sent to the database
Query the table when you've checked those with a raw SELECT query in Enterprise Manager and make sure there is one row.
That code above would not duplicate rows unless called twice.
the error says, "Error converting data type varchar to numeric."
This is my set of codes:
private void btnSearchCustomer_Click(object sender, EventArgs e)
{
//Get Customer Records
DataSet dsCustomer = new DataSet();
dsCustomer = GetRecords("Customers");
frmBasicSearch newSearch = new frmBasicSearch();
newSearch.myDataSet = dsCustomer;
newSearch.ShowDialog();
int myRowPosition = newSearch.myRowPosition;
if (myRowPosition != -1) //will display the value inside the textboxes
{
//concuntinated values
this.txtCustomerNo.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerNo"].ToString();
this.txtCustomerName.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerName"].ToString();
this.txtCustomerAddress.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerAddress"].ToString();
groupProduct(true); //this will activate the buttons from the Product Section
}
cn.Close();
cn.Open();
SqlCommand cmdInsert = new SqlCommand();
cmdInsert.Connection = cn;
cmdInsert.Transaction = trnOrder;
cmdInsert.CommandType = CommandType.Text;
cmdInsert.CommandText =
"INSERT INTO ShoppingCart " +
"(OrderDate, CustomerNo, CustomerName, CustomerAddress, PurchaseOrderNo, AgentNo, AgentName, InvoiceNo, TotalAmount, OrderStatus) " +
"VALUES ('" +
dtpOrderDate.Value.Date.ToString() + "', '" +
txtCustomerNo.Text + "', '" +
txtCustomerName.Text + "', '" +
txtCustomerAddress.Text + "', '" +
DBNull.Value + "', '" +
DBNull.Value + "', '" +
DBNull.Value + "', '" +
DBNull.Value + "', '" +
DBNull.Value + "', '" +
"''Void'); " +
"SELECT TOP 1 ShoppingCartNo FROM ShoppingCart " +
"ORDER BY ShoppingCartNo DESC;";
cmdInsert.ExecuteNonQuery();
cn.Close();
}
the highlighted error part is the
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
I cannot seem to know where is the problem? thank you for helping
and here is my data schema,
ShoppingCartNo is in primary key and the is identity is auto incriminated by 1
ExecuteScalar executes a SELECT statement and returns the first column of the firest returned row. For INSERT statements use ExecuteNonQuery. It will return an integer, containing the number of inserted lines, so no conversion is needed, simply write
int nShoppingCart = cmdInsert.ExecuteNonQuery();
The error comes from inserting the string 'NULL' into the numeric column TotalAmount.
"'" + DbNull.Value + "'"
will result in 'NULL' (probably, I didn't check, but it definitely is a string, not a numeric value).
You do not need to insert NULL values into columns that can hold NULL values. Simply do not insert these columns, jjust insert the columns containing data.
After that, execute a query using ExecuteScalar, using the mentioned SCOPE-IDENTITY()
ExecuteScalar is typically used in case where your SQL part is returning some rows. Try using ExecuteNonQuery instead while inserting.
Then use your select part with ExecuteScalar. that should work.
Why -
Right now, you have 2 queries - when your run your 2 queries in Management studio - you'd get 'N rows affected' & your ShoppingCartNo. As per your current code, only the first part is returned (due to ExecuteScalar) which results in type conversion error.
First and foremost: this is not the proper way to retrieve the auto-incremented key. Use SCOPE_IDENTITY() instead, or use OUTPUT clause of INSERT. the way you're doing it is incorrect from multiple points of view:
it returns the wrong ID. Two threads insert, both select the same ID (last).
it returns the wrong ID if the IDENTITY was reset
it can return empty result set if the (only) row is deleted between the INSERT and SELECT.
So why don't just use SCOPE_IDENTITY() instead?
The following is my MS sql-server statement, which is used in my C# Windows application. As the title suggests, it selects all product numbers that are between the Textbox dates. I'm fairly inexperienced with SQL, so my attempt may be an atrocity. SQL seems to think so.
string strSQL = "SELECT * FROM HISTORY ORDER BY productNumber WHERE (#strt_date >= '" + Convert.ToDateTime(KHDate1Box.Text) + "' and #end_date <= '" + Convert.ToDateTime(KHDate2Box.Text) + "')";
SQL error message: "Incorrect syntax near the keyword 'WHERE'."
string strSQL = "SELECT * FROM HISTORY ORDER BY productNumber WHERE (#strt_date >= '" + Convert.ToDateTime(KHDate1Box.Text) + "' and #end_date <= '" + Convert.ToDateTime(KHDate2Box.Text) + "')";
That's because the WHERE clause should come before ORDER BY
string strSQL = "SELECT * FROM HISTORY WHERE (#strt_date >= '" + Convert.ToDateTime(KHDate1Box.Text) + "' and #end_date <= '" + Convert.ToDateTime(KHDate2Box.Text) + "' ORDER BY productNumber)" ;
" SELECT * FROM HISTORY
WHERE (#strt_date >= '" + Convert.ToDateTime(KHDate1Box.Text) + "' and #end_date <= '" + Convert.ToDateTime(KHDate2Box.Text) + "')
ORDER BY productNumber "
the order by goes after the where clause
If it's only dates, there's not much chance of SQL injection especially if you validate it.
If you must pass a date as string to SQL Server, it should be in the unambiguous YYYYMMDD format. But I'd also add the validation of the input as date.
Have this before that statement
CultureInfo provider = CultureInfo.InvariantCulture;
Then, change it to
string strSQL = "SELECT * FROM HISTORY ORDER BY productNumber WHERE (#strt_date >= '" +
DateTime.ParseExact(KHDate1Box.Text, "d", provider).ToString("yyyyMMdd")
+ "' and #end_date <= '" +
DateTime.ParseExact(KHDate2Box.Text, "d", provider).ToString("yyyyMMdd") + "')";
Catch errors from failing to parse the date.
Reference: I used "d" but here's the list of Standard Datetime Formats
I have noticed that you are using #strt_date and #end_date (which are T-SQL variables) as column names. Also, the ORDER BY clause should be after the WHERE clause.
As an aside, there are a variety of reasons why you should not code a query in this way. Google "SQL Injection" for a very eye opening security issue.
Instead use parameterized queries. They are safer and less prone to syntax errors caused by invalid characters in the value fields.
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06