How to update a column in sql database from c# form? - c#

I have this sql statement which references a column in the datagrid, ordName
string qryUpdate = "UPDATE Orders SET show=1 WHERE show=0 AND ordName=" + dto.Rows[i]["ordName"].ToString();
but I get an error message as below
Conversion failed when converting the nvarchar value '021-01072015' to data type int.
I thought that .ToString() would overcome this

Please use a parametrized query
string qryUpdate ="UPDATE Orders SET show=1 WHERE show=0 AND ordName= #ordName ";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(qryUpdate, connection);
command.Parameters.AddWithValue("#ordName", dto.Rows[i]["ordName"].ToString());
}

string qryUpdate = "UPDATE Orders SET show=1 WHERE show=0 AND ordName='#orderName'";
//your command object
cmd.Parameters.AddWithValue("#orderName", dto.Rows[i]["ordName"].ToString());

string qryUpdate = "UPDATE Orders SET show=1 WHERE show=0 AND
ordName= '" + dto.Rows[i]["ordName"].ToString() + "'";
now the update query will be
UPDATE Orders SET show=1 WHERE show=0 AND
ordName= '021-01072015'

string qryUpdate = "UPDATE Orders SET show=1 WHERE show=0 AND ordName='" + dto.Rows[i]["ordName"].ToString()+"'";

Please try this.
var qryUpdate =string.Format("UPDATE Orders SET show={0} WHERE show={1} AND ordName='{2}' ",1,0 ,dto.Rows[i]["ordName"].ToString());

Related

How to return MySQL table entries by specified value ASP.net/C#

I know its probably something simple but its been driving me nuts for 2 days now
In short, what I want to do is return all of the entries from a specific table based on a value fed into the sql string from a label that holds the appropriate value
This is what I have currently, and it works, but I don't want it to be hardcoded to 'admin':
sqlString = "SELECT * FROM mail WHERE fromuser = 'admin'";
The above returns the entries in the table where the fromuser value is 'admin'
Like I said it works fine. What I want to do is something more like this:
sqlString = "SELECT * FROM mail WHERE fromuser = " + lblUsername.Text;
Where the lblUsername.Text is the value of the currently logged in user (in this case its admin just like before)
So my question is how to I feed the label value into the sql string so that I don't need to hardcode it as 'admin' so that what is returned changes with the value of lblUsername.Text?
I think your first issue is you are missing the quotes when you are building the sql. So your query should look like
sqlString = "SELECT * FROM mail WHERE fromuser = '" + lblUsername.Text + "'";
But the that would be a horrible query to run against your database, because you would be very vulnerable for sql injection. Try parameterized query instead.
I'm assuming your connection string is set in connectionString variable
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM mail WHERE fromuser = #fromUser", connection);
cmd.Parameters.Add(new MySqlParameter("fromUser", lblUsername.Text));
MySqlDataReader dataReader = cmd.ExecuteReader();
if (dataReader.HasRows){
//do all your reading.
}
connection.Close();
Also, I would suggest you to look into Dapper dot net, which is an excellent ORM to use rather than this naive ADO.NET code
try
var textInLabel = lblUsername.Text;
sqlString = "SELECT * FROM mail WHERE fromuser ='" + textInLabel + " '";
TRY THIS
sqlString = "SELECT * FROM mail WHERE fromuser = '"+ lblUsername.Text+"'";

c# Updating datetime column in access

OleDbConnection con = new OleDbConnection(#constring);
con.Open();
string cmdstring = "UPDATE table SET date=" + DateTime.Parse(datetxt.Text) +" WHERE id ="+id;
OleDbCommand cmd = new OleDbCommand(cmdstring,con);
cmd.ExecuteNonQuery();
con.Close();
I want to update date column which is stored in access database. But it gives me syntax error(missing operator) in query expression '03.03.2016 00:00:00'
In access date column type is Date/Time.
Try with :
string cmdstring = "UPDATE table SET date='" + DateTime.Parse(datetxt.Text).ToString("dd/MM/yyy") +"' WHERE id ="+id;
Apparently it seems a problem in the date format . The solution indicated by Beldi Anouar should funcionarte .
Good luck

DateTime operator giving strange results

I have two SQL query strings, one of which works and one of which doesn't.
The working one:
string updateLoginTime = "UPDATE DeviceUsers SET lastLogin = '" + dateTime + "' WHERE ID = '" + userID + "'";
This one doesn't:
string updateText = "UPDATE DocumentsRead SET timeRead = '" + dateTime + "' WHERE userID = '" + userID + "' AND fileName = '" + fileOnly +"'";
It throws an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
In both queries the dateTime parameter is passed into a web method as a string.
Any ideas why the first one works but the second doesn't?
-EDIT-
The second query is now formatted as follows:
dateTime = DateTime.Now.ToString("dd-MM-yy HH-mm-ss");
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EndUsersConnectionString"].ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "UPDATE DocumentsRead SET timeRead = #timeRead WHERE userID = #userID AND fileName = #fileName";
cmd.Parameters.AddWithValue("#timeRead", dateTime);
cmd.Parameters.AddWithValue("#userId", userID);
cmd.Parameters.AddWithValue("#fileName", fileName);
cmd.ExecuteNonQuery();
}
Still getting the same error.
Never do that. NEVER use string concatenations to build SQL queries. ALWAYS use parametrized queries if you don't want to meet Bobby Tables:
using (var conn = new SqlConnection(someConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "UPDATE DocumentsRead SET timeRead = #timeRead WHERE userID = #userID AND fileName = #fileName";
cmd.Parameters.AddWithValue("#timeRead", someDateTimeInstance);
cmd.Parameters.AddWithValue("#userId", userId);
cmd.Parameters.AddWithValue("#fileName", fileName);
cmd.ExecuteNonQuery();
}
This way not only that you won't meet with Bobby Tables but your query will work correctly.
The golden rule that should be respected when doing SQL development is not never use the + operator.
Double check your datatypes on the table properties.
DeviceUsers.lastLogin type seems to be correctly set to Date, but perhaps DocumentsRead.timeRead isn't correctly configured.
Concatenating sql query is a bad practice in common so it is better to use parametrized query, however in your case you're possibly working in an environment with different locales so the application server and dbms use different date formats (dd/mm/yyyy and mm/dd/yyyy for example)

C# update database

I'm using this string to update database and in this case, it works fine. It updates Znesek_nakupa in in last row:
string sqlUpd = "UPDATE Racun SET Znesek_nakupa='10' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";
But when I'm trying to insert variable and not just 10 it gives me error:
Error converting data type varchar to numeric.
Code example:
double totalPrice = 1.1;
string sqlUpd = "UPDATE Racun SET Znesek_nakupa='totalPrice' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";
How can I do this?
This problem less to do with SQL, and more to do with using strings and variables in C#.
In order to insert the value of a variable in a string in C#, you can't just place the name of the variable in the string. The string doesn't "know" that it contains a variable. Here are a couple of approaches that will work instead:
double totalPrice = 1.1;
// string concatenation
string sqlUpd =
"UPDATE Racun SET Znesek_nakupa='" +
totalPrice +
"' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";
// with string.Format
string sqlUpd = string.Format(
"UPDATE Racun SET Znesek_nakupa='{0}' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)",
totalPrice);
However, the approach of just embedding a variable's value in a SQL query like this is not considered best practice as it risks SQL injection attacks. Usually you would want to use parameterised SQL queries.
A parameterised version of your query would look like this (lifting the example from the page linked to above):
SqlConnection conn = new SqlConnection(_connectionString);
conn.Open();
string s = "UPDATE Racun SET Znesek_nakupa='#totalPrice' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun";
SqlCommand cmd = new SqlCommand(s);
cmd.Parameters.Add("#totalPrice", totalPrice);
SqlDataReader reader = cmd.ExecuteReader();
Ok, I got it.
When I try to save variable totalPrice in database it comes to error, because C# has comma as separator. In database I have to send dot instead. So I simple replace comma with dot and now it works perfect.
So code looks like this now:
string sqlUpd = "UPDATE Racun SET Znesek_nakupa='" + Convert.ToString(totalPrice).Replace(',', '.') + "' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";

Is this query to retrieve data from database correct?

I need to retrieve a value from a field in database. I have the used following code. but the value checkOrderId (which I need) shows the SQL string instead of the value from database. I don't know why it is doing so. Could somebody help me please?
string connectionString = "Data Source = xxyyzz;Initial Catalog = xyz; Integrated Security = True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From" + tableName + "ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
//cmd.ExecuteNonQuery();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == checkOrderId)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
I am new and dont have reputation to answer my question immediately. With everybody's help, i got this one solved...Great help, thanx everybody...following is my code.
string connectionString = "Data Source = EAEDEV;Initial Catalog = GIS; Integrated Security = True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
string valueReturned = (string)cmd.ExecuteScalar();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == valueReturned)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
}
You need to execute the query and check the results, here you are just comparing a string with the query SQL.
Please see here
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson03
for a tutorial.
Your expectation of the result being set into checkOrderId is incorrect. In this instance checkOrderId is just the query to execute and not the actual result.
You need to read the value back from executing the command:
using (var connection = new SqlConnection(connectionString))
using (var comm = new SqlCommand("Select TOP 1 OrderID From [GIS].[SecondaryTraffic].[PotentialBackHauls] ORDER BY InsertDate DESC", connection))
{
connection.Open();
object result = comm.ExecuteScalar(); // This is the key bit you were missing.
if (result != null)
{
// You can cast result to something useful
int orderId = (int)result;
}
} // Both comm and connection will have Dispose called on them here, no need to Close manually.
ExecuteScalar returns the value in the first cell (ie, column 1 row 1) as an object that you can cast to a better type (depending on what type it was in the result-set schema).
If you need to read multiple values, you need to look at ExecuteReader.
There are also other ways of doing this using output parameters, but that would pollute the point of the answer.
You can add space to your query
"Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
Nota : I suggest you to use AddWithValue method with your parameter
string checkOrderId = "Select TOP 1 OrderID From #tableName ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
cmd.Parameters.AddWithValue("#tableName", tableName );
Link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
You don't actually run your command anywhere. Instead of the commented-out cmd.ExecuteNonQuery, you should look into the ExecuteScalar method, which allows you to read back a single result value from a query - which is what your query returns.
Add
int i = (Int32) cmd.ExecuteScalar();
right after
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
then the variable i will contain the order id
No, this is not correct. You are comparing the variable orderId to your query string. I doubt that's what you want to do. I imagine you'd be better off calling cmd.ExecuteScalar() to retrieve the actual OrderID value. As noted by other answers, your query string is missing a space. But most importantly, it is bad practice to construct SQL queries in code. Although I can't see a security issue with this code, if you continue to use this method you will probably write code that is vulnerable to SQL injection. I recommend you learn to either use parameters or LINQ to build your queries.

Categories

Resources