I need to perform an update in a table(Homework). But it is not just replacing an old value with a new one; to the already existing value in the column i have to add(SUM) the new value(the column is of type int).
This is what i did so far but i am stuck:
protected void subscribeButton_Click(object sender, EventArgs e)
{
string txtStudent = (selectedStudentLabel.Text.Split(' '))[0];
int studentIndex = 0;
studentIndex = Convert.ToInt32(txtStudent.Trim());
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Trusted_Connection=True;User Instance=yes");
conn.Open();
string sql2 = "UPDATE student SET moneyspent = " + ?????? + " WHERE id=" + studentIndex + ";";
SqlCommand myCommand2 = new SqlCommand(sql2, conn);
try
{
conn.Open();
myCommand2.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
finally
{
conn.Close();
}
}
What should i add intead of ??? to achieve my goal?
Is it possible to do it this way? I want to avoid using to many queries.
If i understand you correctly (i'm not sure i do) you want something like this:
string sql2 = "UPDATE student SET moneyspent = moneyspent + #spent WHERE id=#id";
SqlCommand myCommand2 = new SqlCommand(sql2, conn);
myCommand2.Parameters.AddWithValue("#spent", 50 )
myCommand2.Parameters.AddWithValue("#id", 1 )
Notice how i've used parameters and not string concatenation, very important!!
Related
I am creating a basic app for adding and displaying customer information using windows forms in visual studio. i have set it up so i am able to display the contents of the database in a gridview and also add to the database which you can see the code for below. what i am stuck on at the moment is updating the customers information. I want to search the database by customerID which will be entered by the user in a textbox, and display that specific customers details into their relevent textboxes which i can then edit and save.
using (SQLiteCommand cmd = conn.CreateCommand())
{
// adds customers details to the database
cmd.CommandText = #"INSERT INTO customer (title, " + "firstname, " + "lastname, " + "dob, " + "nicode, " + "email, " + "password, " + "allowance) VALUES (#setTitle, #setFirstname, #setLastname, #setDOB, #setNICode, #setEmail, #setPassword, #setAllowance)";
cmd.Parameters.AddWithValue("setTitle", cb_title.Text);
cmd.Parameters.AddWithValue("setFirstname", txtFirst_Name.Text);
cmd.Parameters.AddWithValue("setLastname", txtSurname.Text);
cmd.Parameters.AddWithValue("setDOB", dtp_DOB.Text);
cmd.Parameters.AddWithValue("setNICode", txtNI_Code.Text);
cmd.Parameters.AddWithValue("setEmail", txtEmail.Text);
cmd.Parameters.AddWithValue("setPassword", txtPassword.Text);
cmd.Parameters.AddWithValue("setAllowance", txtAllowance.Text);
int recordsChanged = cmd.ExecuteNonQuery();
MessageBox.Show("Customer Added");
conn.Close();
Customers customers = new Customers();
customers.Show();
this.Hide();
}
That's what I have for adding a new customer which works fine
using (SQLiteCommand cmd = conn.CreateCommand())
{
// adds customers details to the database
cmd.CommandText = #"UPDATE customer SET (title, " + "firstname, " + "lastname, " + "dob, " + "nicode, " + "email, " + "password, " + "allowance) VALUES (#setTitle, #setFirstname, #setLastname, #setDOB, #setNICode, #setEmail, #setPassword, #setAllowance) WHERE custid = #recd";
cmd.Parameters.AddWithValue("title", cb_title_update.Text);
cmd.Parameters.AddWithValue("firstname", txtFirst_Name_update.Text);
cmd.Parameters.AddWithValue("lastname", txtSurname_update.Text);
cmd.Parameters.AddWithValue("dob", dtp_DOB_update.Text);
cmd.Parameters.AddWithValue("nicode", txtNI_Code_update.Text);
cmd.Parameters.AddWithValue("email", txtEmail_update.Text);
cmd.Parameters.AddWithValue("password", txtPassword_update.Text);
cmd.Parameters.AddWithValue("allowance", txtAllowance_update.Text);
cmd.Parameters.AddWithValue("recd", Convert.ToInt32(txtSearch.Text));
int recordsChanged = cmd.ExecuteNonQuery();
MessageBox.Show("Customer Updated");
conn.Close();
Customers customers = new Customers();
customers.Show();
this.Hide();
}
And that's the code I have so far for updating the database, but I can not figure out how to retrieve the customer data and display it into the textboxes, any help or guidance would be appreciated
Your Update statement is not correct. Try the following.
cmd.CommandText =#"UPDATE customer
SET title = #setTitle,
firstname = #setFirstname,
lastname = #setLastname
dob = #setDOB,
nicode = #setNICode,
email = #setEmail,
password = #setPassword,
allowance = #setAllowance
WHERE custid = #recd";
It is a bit different from an Insert. Each field is set to a new value. You don't need all that concatenation. This is a literal string.
Of course, in a real application you would NEVER store passwords as plain text.
To get the value of a certain column from a certain row, you can try to call method SqlCommand.ExecuteReader.
Here assume you want to get the the customer password.
string connectionstring = #"connectin string";
private void btnSearch_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from customer where customerID = #cusID";
cmd.Parameters.AddWithValue("#cusID", textBoxID.Text);
conn.Open();
try
{
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (reader.HasRows)
{
if (reader.Read())
{
// get password column value
textBoxPWD.Text = reader["password"].ToString();
}
}
else
{
Console.WriteLine("no such record");
}
}
catch (Exception ex)
{
Console.WriteLine("\nError:\n{0}", ex.Message);
}
}
}
As to update the record,
private void btnUpdate_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE customer SET password = #cusPWD WHERE customerID = #cusID";
cmd.Parameters.AddWithValue("#cusID", textBoxID.Text);
cmd.Parameters.AddWithValue("#cusPWD", textBoxPWD.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
I'm writing a script to add a bug report in the bug tracking system.
While after clicking the submit button, the SQL syntax error dialog have been pop-up.
Here is my coding
public partial class AddBugForm : Form
{
public AddBugForm()
{
InitializeComponent();
Fillcombo();
Fillcombo1();
Fillcombo2();
}
void Fillcombo()
{
string constring = "datasource = localhost; username = root; password = ";
string Query = "select * from bug.type";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string type = myReader.GetString("Type_of_bug");
comboBox1.Items.Add(type);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Fillcombo1()
{
string constring1 = "datasource = localhost; username = root; password = ";
string Query1 = "select * from bug.severity";
MySqlConnection conDataBase1 = new MySqlConnection(constring1);
MySqlCommand cmdDataBase1 = new MySqlCommand(Query1, conDataBase1);
MySqlDataReader myReader;
try
{
conDataBase1.Open();
myReader = cmdDataBase1.ExecuteReader();
while (myReader.Read())
{
string severity = myReader.GetString("severity");
severity_combo.Items.Add(severity);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Fillcombo2()
{
string constring2 = "datasource = localhost; username = root; password = ";
string Query2 = "select * from bug.priority";
MySqlConnection conDataBase2 = new MySqlConnection(constring2);
MySqlCommand cmdDataBase2 = new MySqlCommand(Query2, conDataBase2);
MySqlDataReader myReader;
try
{
conDataBase2.Open();
myReader = cmdDataBase2.ExecuteReader();
while (myReader.Read())
{
string priority = myReader.GetString("priority");
priority_combo.Items.Add(priority);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void submit_button_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;username=root;password=";
string Query = "INSERT INTO 'bug.bug' (Bug_ID, title, Type_of_bug, software, software_version, description, step_to_reproduction, severity, priority, symptom) values('" + this.bugid_txt.Text+"', '" + this.title_txt.Text + "','" + this.comboBox1.Text + "','" + this.software_txt.Text + "','" + this.software_version_txt.Text + "','" + this.description_txt.Text + "','" + this.step_to_reproduction_txt.Text + "','" + this.severity_combo.Text + "','" + this.priority_combo.Text + "','" + this.symptom_txt.Text + "');";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Saved");
while(myReader.Read())
{
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Please help me :((((
I see two issues with context of syntax error in your INSERT query
first, INSERT INTO 'bug.bug'; remove those single quotes else it's a literal value and not table name. It should be INSERT INTO bug.bug
Second, remove the semicolon from last of your query statement
.... + this.symptom_txt.Text + "');";
^.... this semicolon
replace this INSERT INTO 'bug.bug' by
INSERT INTO `bug.bug`
your table name is tarted as string and mysql engine doesn't see the table.
What is the syntax error you are getting?
Couple of points regarding the Insert statement.
You should not build the SQL command string by combining the value strings, this can create SQL injection problems and easily cause syntax errors. Instead you should use Parameters. Parameters also make the syntax a lot simpler.
You should use the ExecuteNonQuery command instead of a Reader, as the Insert statement is not reading any data
Updated statement (only two values used to make it smaller):
string Query = "INSERT INTO bug.bug (Bug_ID, title) values (#id, #title)"
MySqlConnection conDataBase = new MySqlConnection (constring);
MySqlCommand cmdDataBase = new MySqlCommand (Query, conDataBase);
cmdDataBase.Parameters.AddWithValue ("#id", bugid_txt.Text)
cmdDataBase.Parameters.AddWithValue ("#title", title_txt.Text)
conDataBase.Open();
cmdDataBase.ExecuteNonQuerty ();
MessageBox.Show("Saved");
Using Parameters will probably solve your syntax error.
I'm trying to finish a college project that requires a program to interact with a database.
Some of my naming is a little odd, but don't worry!
I'm trying to use a single submit button to either update or insert to the database.
Main issue is that I can't get an update to work though when I changed my code to try and fix it, I made it worse. Here is what I currently have.
private void btn_submit_Click(object sender, EventArgs e)
{
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT TaskCode FROM TaskCode;";
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
SqlCeDataReader reader;
reader = c1.ExecuteReader();
if (reader.Read())
{
try
{
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, TaskDescription = #TaskDescription = WHERE TaskCode = #TaskCode;";
SqlCeCommand c = new SqlCeCommand(taskUpdate, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been updated");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
else
{
try
{
string taskInsert = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
SqlCeCommand c = new SqlCeCommand(taskInsert, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
}
}
Has anyone got any ideas why I am getting an error on the c.ExecuteQuery line?
If I remove said line, it will not throw an exception, but it will not update the database.
Thanks
You have a simple syntax error in your update query just before the where statement.
There is an invalid equal sign
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
Your query also could be simplified with
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT COUNT(*) FROM TaskCode";
string cmdText;
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
int count = (int)c1.ExecuteScalar();
if (count > 0)
{
// Here there is no point to update the TaskCode. You already know the value
// Unless you have a different value, but then you need another parameter
// the 'old' TaskCode.....
cmdText = "UPDATE TaskCode SET " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
}
else
{
cmdText = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
}
try
{
SqlCeCommand c = new SqlCeCommand(cmdText, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
MessageBox.Show(count > 0 ? "Record has been updated" : "Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
Not sure if it is the only problem, but you have an equal (=) sign before the WHERE keyword.
I'm trying to simply delete a full row from my SQL Server database table using a button event. So far none of my attempts have succeeded. This is what I'm trying to do:
public static void deleteRow(string table, string columnName, string IDNumber)
{
try
{
using (SqlConnection con = new SqlConnection(Global.connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + IDNumber, con))
{
command.ExecuteNonQuery();
}
con.Close();
}
}
catch (SystemException ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
}
}
}
I keep receiving the error:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
An error occurred: Operand type clash: text is incompatible with int
All of the columns in the table are of TEXT type. Why cannot I compare the function argument of type string to the columns to find the match? (And then delete the row?)
As you have stated that all column names are of TEXT type, So, there is need to use IDNumber as Text by using single quote around IDNumber.....
public static void deleteRow(string table, string columnName, string IDNumber)
{
try
{
using (SqlConnection con = new SqlConnection(Global.connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber+"'", con))
{
command.ExecuteNonQuery();
}
con.Close();
}
}
catch (SystemException ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
}
}
}
Either IDNumber should be an int instead of a string, or if it's really a string, add quotes.
Better yet, use parameters.
Try with paramter
.....................
.....................
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + #IDNumber, con))
{
command.Paramter.Add("#IDNumber",IDNumber)
command.ExecuteNonQuery();
}
.....................
.....................
No need to close connection in using statement
Looks like IDNumber is a string. It needs single quote wrapped around it.
"DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber + "'"
You may change the "columnName" type from TEXT to VARCHAR(MAX). TEXT column can't be used with "=".
see this topic
private void button4_Click(object sender, EventArgs e)
{
String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("delete successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
String st = "SELECT * FROM suppliers";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
SqlDataReader reader = sqlcom.ExecuteReader();
DataTable datatable = new DataTable();
datatable.Load(reader);
dataGridView1.DataSource = datatable;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
If you are using MySql Wamp. This code work.
string con="SERVER=localhost; user id=root; password=; database=dbname";
public void delete()
{
try
{
MySqlConnection connect = new MySqlConnection(con);
MySqlDataAdapter da = new MySqlDataAdapter();
connect.Open();
da.DeleteCommand = new MySqlCommand("DELETE FROM table WHERE ID='" + ID.Text + "'", connect);
da.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("Successfully Deleted");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
private void DeleteProductButton_Click(object sender, EventArgs e)
{
string ProductID = deleteProductButton.Text;
if (string.IsNullOrEmpty(ProductID))
{
MessageBox.Show("Please enter valid ProductID");
deleteProductButton.Focus();
}
try
{
string SelectDelete = "Delete from Products where ProductID=" + deleteProductButton.Text;
SqlCommand command = new SqlCommand(SelectDelete, Conn);
command.CommandType = CommandType.Text;
command.CommandTimeout = 15;
DialogResult comfirmDelete = MessageBox.Show("Are you sure you want to delete this record?");
if (comfirmDelete == DialogResult.No)
{
return;
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
Iam fairly new to SQLClient and all, and iam having a problem with my SQL tables..when ever i run my code, the data, rather than getting updated, attaches itself to the already existing records in the tables..here's my code
SqlConnection conneciones = new SqlConnection(connectionString);
SqlCommand cmd;
conneciones.Open();
//put values into SQL DATABASE Table 1
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
cmd = new SqlCommand("insert into URL_Entries values('" + CleanedURLlist[ok] + "' , '" + DateTime.Now + "' , '" + leak + "' )", conneciones);
cmd.ExecuteNonQuery();
}
conneciones.Dispose();
Take a look at these functions, i hope you understand better on update , insert and delete functions..
Code snippets for reading, inserting, updating and deleting a records using asp.net and c# and sql server database
static void Read()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM EmployeeDetails", conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("Id = ", reader["Id"]);
Console.WriteLine("Name = ", reader["Name"]);
Console.WriteLine("Address = ", reader["Address"]);
}
}
reader.Close();
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
"#Id, #Name, #Address)", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Amal Hashim");
cmd.Parameters.AddWithValue("#Address", "Bangalore");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Update()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE EmployeeDetails SET Name=#NewName, Address=#NewAddress WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Munna Hussain");
cmd.Parameters.AddWithValue("#Address", "Kerala");
int rows = cmd.ExecuteNonQuery();
//rows number of record got updated
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Delete()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("DELETE FROM EmployeeDetails " +
"WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
int rows = cmd.ExecuteNonQuery();
//rows number of record got deleted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
Your code should be inserting new records, but I'm not clear on whether it is not doing that, or you mean to update existing records.
Aside from that, understanding that you are new to working with SQL Server, there are a couple of things you should be aware of.
You should use using to automatically dispose resources. This will also close your connection for you so you don't have open connections hanging around.
You should use parameters to protect against sql injection attacks. Another benefit of using parameters in your case is that you don't need to create new commands for every statement.
For example:
using (var connection = new SqlConnection(connectionString)
using (var command = connection.CreateCommand())
{
command.CommandText = "insert into URL_Entries values(#url, #now, #leak)";
command.Parameters.AddWithValue("#now", DateTime.Now);
command.Parameters.AddWithValue("#lead", leak);
// update to correspond to your definition of the table column
var urlParameter = command.Parameters.Add(new SqlParameter("#url", SqlDbType.VarChar, 100));
connection.Open();
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
urlParameter.Value = CleanedURLlist[ok];
command.ExecuteNonQuery();
}
}
Per your comment, if you want to do an update, you'll need to include the parameter(s) that identify the rows to update. If this is a single row, use the primary key value:
command.CommandText = "update URL_Entries set UrlColumn = #url, ModifiedDate = #now where ID = #id";
You're using an INSERT function, that is 'ADD NEW RECORDS'
If you want an update, you'll want an UPDATE function
UPDATE tablename
SET column1 = 'x', column2 = 'y'
WHERE id = z