I am pretty new in C# and I'm making a program where the user can add a Network provider and reload. I already did the Add, Edit, Delete Network but I don't know on how to to the Reload Part where I need to get the current value of the load from the DB and add (addition) it to the new amount.
Example: Current balance = 12 and Reload = 35 --> Current Balance = 47
By the way, I am using MS Access.
Feel like I'm taking risk to answer your question but anyway..
Since we have no idea what is your desing and code looks like but I suggest to use UPDATE statement.
Here it's syntax;
UPDATE table_alias
SET expression
WHERE <search_condition>
For your case, it can be like;
UPDATE YourTableName
SET Current_balance = Current_balance + 35
WHERE <search_condition>
This query adds 35 to your Current_balance column where you specified search condition in your table.
Of course, we could be more helpful if we see your desing and code..
The user inputs the amount in the textbox. I'm doing it on Windows
Forms Application.
Let's try to write an example like this;
string s = TextBox1.Text;
int i;
if(Int32.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out i))
{
using(SqlConnection con = new SqlConnection("YourConnectionString"))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "Update TableName SET Current_balance = Current_balance + #p";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#p", i);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
else
{
//TextBox string is not a valid integer.
}
Related
I'm creating a reservation system and this is my forms, I'm having a hard time trying to send the quantity of the products because I'm using multiple textboxes unlike the reservation id I can easily get the value because I'm only using one textbox
SqlConnection con = new SqlConnection(#"Data Source = MAAAYYK; Initial Catalog = dbFoodReservation; Integrated Security = True");
SqlCommand cm = new SqlCommand();
con.Open();
cm = new SqlCommand("Insert into tbl_Reservation(ReservationID,ReceiptID,Price,Qty)Values(#ReservationID, #ReceiptID, #Price, #Qty)", con);
cm.Parameters.AddWithValue("#ReservationID", txtBoxreserveID.Text);
cm.Parameters.AddWithValue("#ReceiptID", txtboxReceiptID.Text);
cm.Parameters.AddWithValue("#Price", txtboxTotal.Text);
cm.Parameters.AddWithValue("#Qty", txtfried.Text + txtbbq.Text);
cm.ExecuteNonQuery();
con.Close();
the blank one is there I don't know what to put because as you can see I'm in my form there are many textbox for the quantity
Is there a way for me to get those values like if loop or something?
I changed my code and found a way to send the value of qty but when I enter 1 and 1 it shows 11 in the database instead of 2
Here is the database
You must convert text to Integer for Prevent concatenate strings.
// clean code
var intTxtfried = Convert.ToInt32(txtfried.Text);
var intTxtbbq = Convert.ToInt32(txtbbq.Text);
var totalQty = intTxtfried + intTxtbbq;
// other code ...
cm.Parameters.AddWithValue("#Qty", totalQty);
I am having an issue with the increment for the ID. The ID would increase by one every time I click insert, but the problem occurs when the ID 2, it would insert the values twice, if ID 3, it would insert the values three times, and so on.
There are couple of options that I have been trying. One is Max and the other one is finding the last inserted value and add one to the ID just.
I would appreciate if anyone can help me out with this. Thanks
public partial class LoginInfo : System.Web.UI.Page
{
static string myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
private void GenerateID()
{
SqlConnection myConnection = new SqlConnection(myConnectionString);
string myQuery1 = "Select Count(S_ID) from Student_Name";
SqlCommand cmd = new SqlCommand(myQuery1, myConnection);
myConnection.Open();
int addOneS_ID_Table1 = Convert.ToInt32(cmd.ExecuteScalar());
myConnection.Close();
addOneS_ID_Table1++;
lblstdID.Text = addOneS_ID_Table1.ToString();
myConnection.Open();
cmd.CommandText = "Select Count(P_ID) from Student_Pass";
int addOneP_ID_Table2 = Convert.ToInt32(cmd.ExecuteScalar());
myConnection.Close();
addOneP_ID_Table2++;
lblstdPass.Text = addOneP_ID_Table2.ToString();
/*-----------------------------------------------------------------*/
//SqlConnection myConnection = new SqlConnection(myConnectionString);
//SqlCommand cmd = new SqlCommand("SELECT MAX(S_ID) as max_S_ID from Student_Name",myConnection);
//cmd.CommandType = CommandType.Text;
//myConnection.Open();
//lblstdID.Text = Convert.ToString(cmd.ExecuteScalar());
//cmd.CommandText = "SELECT MAX(P_ID) as max_P_ID FROM Student_Pass";
//lblstdPass.Text = Convert.ToString(cmd.ExecuteScalar());
//myConnection.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
GenerateID();
}
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(myConnectionString);
string myQuery = "Insert into Student_Name(S_ID,STUDENT_NAME) VALUES" + "(#S_ID,#STUDENT_NAME)";
SqlCommand cmd = new SqlCommand(myQuery,myConnection);
cmd.Parameters.Add("#S_ID", SqlDbType.Int).Value = lblstdID.Text;
cmd.Parameters.Add("#STUDENT_NAME", SqlDbType.VarChar).Value = txtstdName.Text;
if(myConnection.State == ConnectionState.Closed)
{
myConnection.Open();
}
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
//Second Table
cmd.CommandText = "Insert into Student_Pass(P_ID,PASSWORD) VALUES" + "(#P_ID,#PASSWORD)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#P_ID", SqlDbType.Int).Value = lblstdPass.Text;
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = txtStdPass.Text;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
myConnection.Close();
GenerateID();
lblResult.Text = "Successfully Saved";
GridView1.DataBind();
}
}
Problem is with your query since you are getting COUNT(S_ID) which is going to get you count of records doesn't necessarily will give exact ID number. You should rather try MAX(S_ID) or ORDER BY clause saying
Select MAX(S_ID) from Student_Name
(OR)
Select TOP 1 S_ID from Student_Name ORDER BY S_ID DESC;
But recommended, You should actually go with SQL Server ##IDENTITY or SCOPE_IDENTITY() to get the last inserted record ID (assuming that S_ID is an IDENTITY column)
It's highly recommended to not use max or top in order to determine the "next" identifier to use, simply because of the cost associated with it.
However, there are some other pitfalls to using max and top especially if there is a chance that nolock is used (which is a whole other conversation). I've seen a lot of web applications use max and has proven to be a performance killer.
Rahul is right, ##identity or scope_identity are good alternatives. However, I think this calls for using a native SQL Server sequence, which was introduced in SQL Server 2012. It was something that application developers have been waiting for and Microsoft finally delivered.
The issue with using ##identity or scope_identity is that you actually have to write rows to some table before you can even contemplate doing something.
This makes it a bit more costly and messier than what it may need to be. In the case of using a sequence, you can issue a new sequence number and then decide what to do and once you decide what to do you're still guaranteed that you're the only one with that sequence number.
You would create a sequence like this. You should check out the documentation as well.
create sequence dbo.StudentIdSeq
as int -- this can be any integer type
start with 1 -- you can start with any valid number in the int, even negative
increment by 1;
go
Then you issue new sequence numbers by doing this ...
select next value for StudentIdSeq;
It may still be good to create a stored procedure with an output parameter that you can call from C# (which is what I would do). In fact you may want to take it a step further, in the case that you have a bunch of sequences, and create a slick stored procedure that will get a new sequence based on the type that is being requested from the caller.
This code is supposed to save some values in textboxes to a specific row. The code runs just fine with no hiccups, but refuses to actually update the database no matter what I do.
try
{
using (var con = new OleDbConnection())
{
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Desktop\esoft\gym\gym\bin\Debug\Clients.accdb;";
con.Open();
using (var com = new OleDbCommand())
{
com.Connection = con;
com.CommandText = "UPDATE gym SET BMI = #bmi and Health = #health and weight_change_to_healthy_bmi = #weight WHERE ID = #id";
com.Parameters.AddWithValue("#bmi", bmi.Text);
com.Parameters.AddWithValue("#health", health.Text);
com.Parameters.AddWithValue("#weight", change.Text);
com.Parameters.AddWithValue("#id", id.Text);
com.ExecuteNonQuery();
}
}
MessageBox.Show("Saved");
}
catch (Exception ex)
{
MessageBox.Show("Not saved: " + ex.Message);
}
Any help would be much appreciated.
As Alex mentioned, SET part needs , instead of AND for multiple columns.
Check UPDATE syntax1;
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
But I wanna say a few things more;
Don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.
Open your connection just before you execute your command. That means, you should open your connection just before your ExecuteNonQuery line.
Based on it's name, ID column should be some numeric value instead of character. Consider to change it's type or consider to change it's column name that refers some character typed column name.
1: I know I know.. a w3school link
I am working on Asp .Net project. So I have a page where I am generating random coupon keys. So user enters quantity and generate.
So what I did, I put a for loop according to quantity and inside the for loop I created a random key and search for the key in DB (key is unique) and then insert the data in DB.
Code:
for (int i = 0; i < quantity; i++)
{
do
{
couponKey = generateKey();
} while (!SearchEpinKey(couponKey));
conn = new SqlConnection(connString);
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
string query = "INSERT INTO CouponStock (coupon_key, status, created_on)";
query += "VALUES('" + couponKey + "','Unused', GETDATE())";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
}
conn.Close();
}
Inside the loop, Flow is like:
-Genrate random key
-Search if random key exists or not in db
-If found similar then again generate random key
-Insert the data in DB
So when I run this page for smaller quantities like 10 or 15, its working fine. But when I go for 50 or 100 its inserting random number of rows like sometime 24, sometime 48. And application get hangs after this. I am thinking that Sql server is hitting numerous time in short interval. Any guidance on how to handle this will be helpful.
The only reason I could find is because of this
do
{
couponKey = generateKey();
} while (!SearchEpinKey(epinKey));
If you are using couponKey in your INSERT query, why do you use SearchEpinKey(epinKey)? where are you searching for couponKey in DB?
You are assigned generateKey() to couponKey variable, and your are checking against epinKey, I believe that when epinKey is already stored in DB it hangs (an infinite loop), because epinKey is always the same even if you assing a new value to couponKey
just change this line
} while (!SearchEpinKey(epinKey));
to this
} while (!SearchEpinKey(couponKey));
First thing first I think we should avoid opening a new connection on every insert, also we should always use ASP.Net build in function for parameter (e.g. AddWithValue), as they help avoid SQL Injection
var couponList = new System.Collections.Generic.List<String>();
var query = "INSERT INTO CouponStock(coupon_key, status, created_on) VALUES(#coupon_key, #status, GETUTCDATE());";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
do{
var couponKey = generateKey();
//return early for readability
if(!SearchEpinKey(couponKey)) continue;
if(couponList.Contains(couponKey)) continue;
//add to coupon list to ensure newly generated key does not duplicate
couponList.Add(couponKey);
SqlCommand cmd = conn.CreateCommand(query);
cmd.Parameters.AddWithValue("#coupon_key", couponKey);
cmd.Parameters.AddWithValue("#status", "Unused");
cmd.ExecuteNonQuery();
}
while (couponList.Count < quantity);
}
catch (Exception e)
{
// handle exceptions or re-throw them...
}
finally
{
conn.Close();
}
}
I have a website where users can log in. The client wants there to be a way to record the number of times any particular user logs in. I have a "Counter" row in the table. How do I program the app (built in C# ASP.NET) to update the counter when people log in? Is this code correct:
cmd.ExecuteNonQuery = "UPDATE Counter FROM brokercenter"
I just recently graduated (as in the 10th of this month) so I am new to this, plus I know nothing about databases, I am just learning on the job. Please let me know if I need any other parameter or connection string or aything else? This is in the button click event and there is already a connection string there to check the username and password so I don't think I need another connection string, but I don;t know for sure. Thanks in advance!
For that matter, here is the whole event (the login stuff works fine, just the update is my question):
string connectionString =
ConfigurationManager.ConnectionStrings["moverschoiceConnectionString"].ConnectionString;
OdbcConnection conn = new OdbcConnection(connectionString);
conn.Open(); OdbcCommand cmd = new OdbcCommand();
cmd.Connection = conn;
cmd.CommandText = "select Email, Password from brokercenter where Email = '" + txtLoginEmail.Text + "'";
OdbcDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
if (reader["Password"].ToString() == txtLoginPassword.Text)
{
reader.Close();
if (cbRememberMe.Checked == true)
{
Response.Cookies["username"].Value = txtLoginEmail.Text;
Response.Cookies["username"].Expires = DateTime.Now.AddMonths(1);
Response.Cookies["password"].Value = txtLoginPassword.Text;
Response.Cookies["password"].Expires = DateTime.Now.AddMonths(1);
}
else
{
Response.Cookies["username"].Expires = DateTime.Now.AddMonths(-1);
Response.Cookies["password"].Expires = DateTime.Now.AddMonths(-1);
}
Response.Redirect("BrokerResources.aspx");
}
else
{
lblLoginError.Text = "Invalid Password";
}
}
lblLoginError.Text = "Invalid Email or Password";
reader.Close();
cmd.ExecuteNonQuery = "UPDATE counter FROM brokercenter";
}
For a start, you should read about using UPDATE in MySQL's Reference Manual.
There is even an example for exactly what you want to do.
Quote from the link:
If you access a column from the table to be updated in an expression,
UPDATE uses the current value of the column. For example, the
following statement sets col1 to one more than its current value:
UPDATE t1 SET col1 = col1 + 1;
This is basically all you need, you just need to add a WHERE clause and filter for the username or for the email.
Plus, you should read about SQL Injection because of this:
where Email = '" + txtLoginEmail.Text + "'";
Concatenating strings like this to pass parameters can cause problems as described in the link.
Here's an example how to do it better.
cmd.ExecuteNonQuery = String.Format("UPDATE brokercenter SET counter = {0} WHERE Email = {1}", myCounter++, txtLoginEmail.Text);
where "myCounter" is a local counter variable (which should also be read from the database). Does this make sense now?