C# update database - c#

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)";

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+"'";

Incorrect Syntax when creating table from textbox name

I was trying to create a table based on the name given in textbox1 .I am getting error in the following code :
Incorrect syntax near 'Ramesh'.
Here Ramesh was the value in textbox.
string Customername = Textbox1.text
SqlCommand cmd7 = new SqlCommand("CREATE TABLE '" + CustomerName + "' (ItemCode int,Quantity int,PricePerQuantity int,Brand char(50),Discount int , DateTime datetime)",connection
You don't need single quotes for your table name.
SqlCommand cmd7 = new SqlCommand("CREATE TABLE " + CustomerName + " (ItemCode int,Quantity int,PricePerQuantity int,Brand char(50),Discount int , DateTime datetime)",connection);
But weird part, don't use SqlCommand for MySQL. Use MySqlCommand and related class.
Also I would say that use parameterize queries but since you can't parameterize column name, and looks like you get it as an input, use strong validation or use whitelisting before you put it in your query.
You can read: The BobbyTables culture
remove ' from sides of the table name in query.
string Customername = Textbox1.text
SqlCommand cmd7 = new SqlCommand("CREATE TABLE " + CustomerName + " (ItemCode int,Quantity int,PricePerQuantity int,Brand char(50),Discount int , DateTime datetime)",connection
The immediate cause of the error is that you should not put table name into apostrophes. Something like this:
// put IDisposable into using
using (SqlCommand cmd7 = new SqlCommand(
// Keep SQL readable; "$" - C# 6.0 feature
$#"CREATE TABLE {Textbox1.text}(
ItemCode int,
Quantity int,
PricePerQuantity int,
Brand char(50),
Discount int,
DateTime datetime)",
connection)) {
cmd7.ExecuteNonQuery(); // execute and create the table
}

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

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());

put SELECT COUNT(*) statement result into int variable

I have a SELECT COUNT(*) statement in C#/ASP.NET and I want to store the result as an int to use as an IF condition. However I am getting an error in visual studio:
Error:System.Data.SqlClient.SqlException (0x80131904): The data types text and varchar are incompatible in the equal to operator. at System.Data.SqlClient.SqlConnection.
It tells me its occurring at the int temp line. The columns I'm accessing in the database table are of text type.
conn.Open();
String checkEmail = "select count(*) from Players where PlayerEmail= '" + txtEmailLogIn.Text + "'";
SqlCommand com = new SqlCommand(checkEmail, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp > 0)
{
}
The problem is in your SQL. You can't use = when comparing TEXT data types, instead you can use LIKE:
String checkEmail = "select count(*) from Players where PlayerEmail LIKE '" + txtEmailLogIn.Text + "'";
Be warned though, that you are opening yourself up to SQL injection attacks when composing SQL strings like this.
DavidG's answer above works. However, if you have the opportunity to change the database schema, you could also fix the error by changing the PlayerEmail column from text to varchar(max). The text data type has been deprecated since at least 2005.

Converting Stored Procedure into a query (SQL Server Compact)?

I'm trying to convert the following stored procedure into a query, so that I can use it in SQL Server CE
USE TestResults
GO
CREATE PROCEDURE uspInsertNewTest
(#DeviceSerialNumber nvarchar(50),
#DeviceType nvarchar(50),
#ElapsedTime int)
AS
BEGIN
INSERT INTO [TestResults].[dbo].[Tests]([Date], [Device], [DeviceType], [ExecutionTimeMs])
OUTPUT INSERTED.TestId
VALUES (GETDATE(), #DeviceSerialNumber, #DeviceType, #ElapsedTime)
END
GO
From the above script, all I can understand is that it takes three input parameters
DeviceSerialNumber
DeviceType
ElapsedTime
but it'll update 5 columns in the table Tests including Date and TestId.
Since I can't use stored procedures in SQL Server CE, I've converted the above script into a string query,
string queryString = "INSERT INTO Tests ([Date], [Device], [DeviceType], [ExecutionTimeMs]) VALUES (#Date, #DeviceSerialNumber, #DeviceType, #ElapsedTime)"
Now how to include OUTPUT INSERTED.TestId into the string( queryString ) ?
There's a similar question here, but it doesn't help my problem
Thanks!
You can use ##IDENTITY to return the last inserted identity value:
string queryString = "INSERT INTO Tests " +
"([Date], [Device], [DeviceType], [ExecutionTimeMs]) " +
"VALUES (#Date, #DeviceSerialNumber,#DeviceType, #ElapsedTime); " +
"SELECT ##IDENTITY;"
When you execute your query, you need to set it up to return a single value using the ExecuteScalar method:
var newIdentity;
// set up the queryString variable & command using the above
newIdentity = cmd.ExecuteScalar();
This assumes that the column TestId is an identity column.
Though I accepted Tanner's answer, but I ended up doing like this,
string queryString = "INSERT INTO Tests " + "([Date], [Device], [DeviceType], [ExecutionTimeMs]) " +
"VALUES (#Date, #DeviceSerialNumber,#DeviceType, #ElapsedTime)";
string queryString2 = "SELECT ##IDENTITY";
DbCommand command = factory.CreateCommand ();
command.CommandText = queryString;
// Added Parameters here
command.ExecuteNonQuery ();
command.CommandText = queryString2;
object testId = command.ExecuteScalar ();
So I had to split the query into two string & run ExecuteNonQuery with the first string and run ExecuteScalar with the second string.

Categories

Resources