Query works in SSMS but not from the C#? - c#

It's a basic car rent application, but I simplified it. Think that, there is only two variables in the table:
rentID: int
carID: int
When I do THIS at SQL Server, this works:
UPDATE tblCars SET rentID=15 where carID=4
And this is the C# version. This line totally works with some basic commands. But since this has a lot of " and ' it doesn't work somehow? What am I doing wrong here?
SqlCommand cmd = new SqlCommand("update tblCars SET rentID= '" + Convert.ToInt32(rentID) +"'where carID='" + Convert.ToInt32(carID) + "'", con);

I recommend you parameterize your SQL to avoid things like SQL injection:
using (SqlCommand cmd = new SqlCommand("UPDATE tblCars SET rentID=#rentId WHERE carID=#carId;", con))
{
cmd.Parameters.AddWithValue("#rentId", Convert.ToInt32(rentID));
cmd.Parameters.AddWithValue("#carId", Convert.ToInt32(carId));
cmd.ExecuteNonQuery();
}

Related

Unable to update SQL Database, Using C# Win Form

My Application (C# Win Form) was working perfectly a while ago - i.e (Update, insert, delete...).
But after I close the program and open the Database there are no changes being made.
I'm not getting any errors during running.
I'm using VS2013 professional, SQL Database, C#.
using (SqlConnection connection = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand("UPDATE [FullInk] SET [InStock] = '" +
newSum + "' Where [Catalog] = '" + catalog + "'");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
In the absence of any additional transaction such as a TransactionScope or SqlTransaction (which we can't see in your code), there is no reason why the update will be rolled back. I believe you might not actually be updating the data you think.
Although not necessarily the solution, it is much better practice to use parameterized queries rather than using strings - this has security (Sql Injection), performance (query plan caching) and also helps to eliminate bugs relating to quotes, escaping, and type conversion (which might be the case here - e.g. you are inserting newSum which could imply a numeric value into InStock using quotes, which implies a char type). e.g.
using (var connection = new SqlConnection(conString))
using (var cmd = new SqlCommand("UPDATE [FullInk] SET [InStock] = #InStock Where [Catalog] = #Catalog"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#InStock", newSum);
cmd.Parameters.AddWithValue("#Catalog", catalog);
connection.Open();
cmd.ExecuteNonQuery();
}
Other minor modifications include disposing of the SqlCommand, and also note that disposing a connection will also close it, so you won't need to explicitly close it (although doing so won't hurt).
Try This: It Might work for you...
string Query = "UPDATE FullInk SET InStock = '" + newSum + "' Where Catalog = '" + catalog + "'";
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand cmd = new SqlCommand(Query, sql_con);
cmd.ExecuteNonQuery();
connection.Close();
Also add breakpoints and check weather your code is executing or not
Cause your code seems fine,& should be working

How to initialize Access Number field in C-Sharp

I know how to use Text Box value in Access query for string fields, but i am unable to understand how to use it for int fields.
I am writing the following query and receiving error messages.
ERROR MESSAGE: No value given for one or more required parameters.
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " +textBox2.Text , conn);
conn.Open();
cmd.ExecuteNonQuery();
I also tried to convert textBox2 into int, but its also given me an error message.
Input string was not in a correct format.
int Id= Convert.ToInt16(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " + Id , conn);
conn.Open();
cmd.ExecuteNonQuery();
This answer corrects your problem
First, the TextBox for Name is not the same Textbox used for ID
Second, do not concatenate strings to build sql commands. It is very error prone and open to a well know sql vulnerability called Sql Injection
string queryText = Update Table1 Set Name= ? where ID= ?";
OleDbCommand cmd = new OleDbCommand(queryText, conn);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", Convert.ToInt32(TextBox2.Text));
conn.Open();
cmd.ExecuteNonQuery();
Here I have removed the string concatenation and inserted two parameters placeholders (?),
then I have added to the OleDbCommand two parameters and their values.
When executing the query the OleDb code will replace the placeholders with the actual values checking for invalid characters and invalid sql statements

C# 'select count' sql command incorrectly returns zero rows from sql server

I'm trying to return the rowcount from a SQL Server table. Multiple sources on the 'net show the below as being a workable method, but it continues to return '0 rows'. When I use that query in management studio, it works fine and returns the rowcount correctly. I've tried it just with the simple table name as well as the fully qualified one that management studio tends to like.
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = sqlConnectionString;
cn.Open();
SqlCommand commandRowCount = new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn);
countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count: " + countStart.ToString());
}
Any suggestions on what could be causing it?
Here's how I'd write it:
using (SqlConnection cn = new SqlConnection(sqlConnectionString))
{
cn.Open();
using (SqlCommand commandRowCount
= new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn))
{
commandRowCount.CommandType = CommandType.Text;
var countStart = (Int32)commandRowCount.ExecuteScalar();
Console.WriteLine("Starting row count: " + countStart.ToString());
}
}
Set your CommandType to Text
command.CommandType = CommandType.Text
More Details from Damien_The_Unbeliever comment, regarding whether or not .NET defaults SqlCommandTypes to type Text.
If you pull apart the getter for CommandType on SqlCommand, you'll find that there's weird special casing going on, whereby if the value is currently 0, it lies and says that it's Text/1 instead (similarly, from a component/design perspective, the default value is listed as 1). But the actual internal value is left as 0.
You can use this better query:
SELECT OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE index_id < 2 AND OBJECT_NAME(OBJECT_ID)=N'YOUR_TABLE_NAME'

SQL Server database query

I have used the standard user tables that ASP.net setup and I'm looking to be able to delete users. To do this first off I need to delete the user id from a table called memberships and then delete the user. To do this I have 2 text boxes setup one for user id and other for user name.
Any ideas of a T-SQL statement that will delete the membership user id first and then move onto the delete username this is my statement so far
else
{
try
{
connection.Open();
cmd = new SqlCommand("DELETE from Membershio
WHERE UserId ='" + deleteuserIDbox.Text + "'", connection);
cmd = new SqlCommand("DELETE from Users WHERE UserName ='" + deleteuserbox.Text + "'", connection);
cmd.ExecuteNonQuery();
update.Text = "Your data has been removed";
}
catch
{
update.Text = "Your data has not been deleted";
}
}
The two tables are related hence I need to delete the user id first and then the username
any help greatly appricated
If understand it right, your input method has serious issues.
For example,
UserID UserName
1 testUser
2 testUser2
With the logic in your application; I can enter "1" into deleteuserIDbox and "testUser2" into deleteuserbox which in turn would remove userID 1 but not username "testUser".
If you didn't do it already, you need to associate those two tables using Foreign Key on UserID. So the linkage is persisted with UserID field.
Another issue is, you are directly executing the query with the input from user thus enabling the possiblity of sql injection.
About your query, you can put " cmd.ExecuteNonQuery();" between your two cmd statements.
To use your current code, you will need to execute the first query, then set the CommandText for the second query and execute that.
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "DELETE FROM Membership WHERE UserID = #UserID";
cmd.Parameters.AddWithValue("#UserID", deleteuserIDbox.Text);
connection.Open();
cmd.ExecuteNonQuery();
cmd.Paramters.Clear();
cmd.CommandText = "DELETE from Users WHERE UserName = #UserName";
cmd.Parameters.AddWithValue("#UserName", deleteuserbox.Text);
cmd.ExecuteNonQuery();
}
Another option is to use a stored procedure that would allow you to run the two queries together.
Another option is to do cascading deletes. Here is a link on how to accomplish that.
Lastly, you are opening yourself up to SQL Injection. You should NEVER take input from a user and concatenate that data into a SQL statement. You should either use a Stored Procedure or a parameterized query(like I used above).
You're not executing the first command:
connection.Open();
cmd = new SqlCommand("DELETE from Membershio
WHERE UserId ='" +
deleteuserIDbox.Text + "'", connection);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("DELETE from Users WHERE
UserName ='" + deleteuserbox.Text +
"'", connection);
cmd.ExecuteNonQuery();
Also, these commands should be executed in a transaction.
A bit late but I only noticed your question today.
By doing this on the database you are bypassing all the good stuff! You should do this in C# by calling the Membership::DeleteUser Method
http://msdn.microsoft.com/en-us/library/5xxz7y3a.aspx
You should not mess with the internals of the Membership system at all.

Deleting records from a table, is this correct?

I want to delete some record from table ,by running this Query in C# is it Correct or not,
Please help me
SqlCommand cmdRe = new SqlCommand("insert into msisdn_master SELECT * from tblDeactive
where msisdn in (" + str_MSISDN + ")", cn);
SqlCommand cmdRed = new SqlCommand("delete from tblDeactive where msisdn in ("+str_MSISDN+")", cn);
cmdRe.CommandType = CommandType.Text;
cmdRed.CommandType = CommandType.Text;
note : str_MSISDN is the StringBuilder which stores the Number which is inserted in TextField.
You should be using proper SQL parameters. NEVER use string building since that leaves you open for injection attacks.
Read this tutorial to learn how to add parameters to SqlCommands.

Categories