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
Related
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();
}
I have a local MS SQL Database, and I want to update one of it's bit field.
I have the following code:
static void UpgradeVevo(string nev)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("UPDATE Vevok SET Torzsvendeg=True Where Nev=" + nev, connection);
command.ExecuteNonQuery();
}
Console.WriteLine(nev+" mostmár törzsvendég");
}
Torzsvendeg is a bit datatype(I have tried to set its value to 1 too), and Nev is varchar.
The connectionstring should be fine, since I have tried Select in another method and it works fine. The above code throws no exceptions, but the table does not get updated.
I have tried to find an answer for quite some time, with no success :/. Thank you for your help in advance!
True should be in a single quote since it's a string literal like
UPDATE Vevok SET Torzsvendeg='True'
Well brother, you are messed up with quotes. Your query should look like
"UPDATE Vevok SET Torzsvendeg = 1 Where Nev = '" + nev + "'"
Again, use parametarized query and not this concatenated one to avoid SQL Injection
If the column is a boolean (bit in sql server) then you will have to write
Torzsvendeg=1
instead of
Torzsvendeg='True'
or
Torzsvendeg=True
Edit:
Please try this:
static void UpgradeVevo(string nev)
{
var connection = new SqlConnection(connectionString))
connection.Open(); // try doing this without a using
SqlCommand command = new SqlCommand("UPDATE Vevok SET Torzsvendeg=#enabled Where Nev=#nev", connection);
command.Parameters.AddWithValue(#"enabled", 1);
command.Parameters.AddWithValue(#"nev", "vevo123");
command.ExecuteNonQuery();
command.Parameters.Clear(); // always clear after executed
// close connection when you shut down your application
connection.Close();
connection.Dispose();
Console.WriteLine(nev+" mostmár törzsvendég");
}
Check the bold oledb command, idont know what kind of error it is , or what im doing wrong
please help :(
private void button1_Click(object sender, EventArgs e)
{
try
{
string constring = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\ShahMuhammad\Desktop\testLogin.accdb; Persist Security Info=True;";
OleDbConnection conDataBase = new OleDbConnection(constring);
***OleDbCommand cmdDatabase = new OleDbCommand("Select * from login where uname="this.textBox1.Text" and pword = "this.textBox2.Text", connDatabase);***/// HERE I HAVE PROBLEM
OleDbDataReader myReader;
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
int count=0;
while(myReader.Read())
{count=count+1}
if(count==1)
{MessageBox.Show("Successfull Login");}
else if (count >1)
{MessageBox.Show("Duplicate Uname or Password");}
else
MessageBox.Show("Ghalat input ustaad, wari account password");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
kindly tell me whats is the error , i am a total newbie in C# programming, specially connecting with db
You have a problem because uname and pword are text fields.
When you query text fields you need to put the values between single quotes.
However there is a better solution and it is called Parameterized query
OleDbCommand cmdDatabase = new OleDbCommand(#"Select * from login
where uname=#name and pword = #pword",
connDatabase);
cmdDatabase.Parameters.AddWithValue("#name", textBox1.Text);
cmdDatabase.Parameters.AddWithValue("#pword",textBox2.Text);
....
No more problems with quoting string, replacing single quotes inside strings and Sql Injection attacks, and your command text is now a lot more readable.
When you have fixed this problem I also suggest to read about the weakness of storing passwords in clear text inside a database. In your case a malicious user can simply copy the database and he/she can easily read all your users passwords.
EDIT
Revisiting this question after an hour and I see that there are multiple correct answers (Soner Gönül and Paul Zahra) to your question (albeit incomplete including mine).
In a summary:
Concatenating strings in C# is done using the + operator
There is a typographical error in your naming the connection
Passing string values to a database should be done enclosing strings
in quotes
Use the using statement around disposable objects
Finally use a parameterized query when dealing with command texts
"Select * from login where uname="this.textBox1.Text" and pword = "this.textBox2.Text"
I think this should be;
"Select * from login where uname=" + this.textBox1.Text + "and pword =" + "this.textBox2.Text
If your columns are not character typed, othwerwise you need to use single quotes with them.
But as a better way, always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
var cmdDatabase = new OleDbCommand("Select * from login where uname= ? and pword = ?", connDatabase);
cmdDatabase.Parameters.Add("p1", OleDbType...).Value = this.textBox1.Text;
cmdDatabase.Parameters.Add("p2", OleDbType...).Value = this.textBox2.Text;
And use using statement to dispose your OleDbCommand, OleDbConnection and OleDbDataReader. Like;
using(OleDbConnection conDataBase = new OleDbConnection(constring))
using(OleDbCommand cmdDatabase = conDataBase.CreateCommand())
{
...
...
using(OleDbDataReader myReader = comm.ExecuteReader())
{
//
}
}
Finally, looks like you store your passwords as a plain text. Don't do that! Read: Best way to store password in database
You have two issues with your code... as others have pointed out you need to concatenate the strings... the other is your db connection object, it is called conDataBase but you reference connDataBase and your sql string is a bit squiffy ... your code should look like...
OleDbConnection conDatabase = new OleDbConnection(constring);
string sql = "Select * from login where uname='" + this.textBox1.Text + "' and pword = '" + this.textBox2.Text + "'"
OleDbCommand cmdDatabase = new OleDbCommand(sql, conDatabase);
but as others have said using a parameterised query is safer.
you should write 'this.textbox1.text' (+this.textbox1.text+)
ur query should be like this
"select * from TblLogin where UserName='"+this.txtUserName.text+"' and Password='"+this.txtPassword.text+"' ";
For the longest time, my code has been running, but lately I encounter this error,Object reference not set to an instance of an object. I don't know if it is related to the creation and usage of a new database.
Here is my code:
con2.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT QtyInHand FROM Inventory WHERE ProductID=#ProductID";
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = productID;
int existingQty = (int)cmd.ExecuteScalar();
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE Inventory SET QtyInHand=#QtyInHand WHERE ProductID=#ProductID";
cmd.Parameters.Add("#QtyInHand", SqlDbType.Int).Value = existingQty - int.Parse(quantity);
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = productID;
cmd.ExecuteNonQuery();
con2.Close();
Error on this part: int existingQty = (int)cmd.ExecuteScalar();
When I tried using my other SqlConnection: con
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT QtyInHand FROM Inventory WHERE ProductID=#ProductID";
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = productID;
int existingQty = (int)cmd.ExecuteScalar();
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE Inventory SET QtyInHand=#QtyInHand WHERE ProductID=#ProductID";
cmd.Parameters.Add("#QtyInHand", SqlDbType.Int).Value = existingQty - int.Parse(quantity);
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = productID;
cmd.ExecuteNonQuery();
con.Close();
I encounter another error, The connection was not closed. The connection's current state is open. Error on con.Open(); part. How should I solve this problem?
For the first error, your executeScalar() call is returning a null value. Either refine your query - you can check your query by running it directly in your database - or change your logic to deal with null values.
For the second error, if calling Open() is throwing that error, it's because the connection object was in use before and was not closed properly. It's usually considered bad practice to reuse connections like that, so consider creating a new connection instance when you go opening one.
Edit: I tried to imply something in the second paragraph there, but now I feel I must make it explicit: don't forget to deal with the connection you left open there, as it may be a major performance hog for your application. Specially since it's an ASP.NET one. Dispose of connections as soon as you don't need them. When you call Dispose() for a connection, it gets closed - with the added bonus of other finer memory management procedures as well. Read about the using statement and its usage with connections as soon as you have some time.
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'