Works perfectly except changes are not saved to the SQL database - c#

Changes are not saved to the SQL database
Why would I want to use '#' in the sql statement instead of the way that I have the statement?
Code:
private void button_Save_Customer_Click(object sender, EventArgs e)
{
sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
string customer_Ship_ID = customer_Ship_IDTextBox.ToString();
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = customer_Ship_Address WHERE Customer_Ship_ID = customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}

Here you can check the MSDN reference for the update command.
Use parameters, Why?
Also check that you need to open and close the connection object, not the command.
In case you want to update the rows with the Customer_ID = "something" you could do like this:
The code (updated after your changes):
private void button_Save_Customer_Click(object sender, EventArgs e)
{
string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
int customer_Ship_ID;
if(int.TryParse(customer_Ship_IDTextBox.Text, out customer_Ship_ID))
{
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
// Customer_Ship: Database's table
// Customer_Ship_Address, Customer_Ship_ID: fields of your table in database
// #Customer_Ship_Address, #Customer_Ship_ID: parameters of the sqlcommand
// customer_Ship_ID, customer_Ship_Address: values of the parameters
string SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = #Customer_Ship_Address WHERE Customer_Ship_ID = #Customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
else
{
// The id of the textbox is not an integer...
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}

Seems like your syntax isn't correct. Here's the syntax for the Update:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
So, Update, what to set, and WHERE to set (which you seem to be missing).
For more, have a look here.

Check your update query
Change it like
string SQL = string.format("UPDATE Customer_Ship SET Customer_Ship_Address='{0}'",putUrVaue);

Related

How to insert datagridview record into mysql database using foreach

This code runs fine Values from the dataGridview are also saved succesfully but after saving the entered values in database a null row is also added in the tabl
private void save_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)// picks data from dataGridview
{
try // MySql connection
{
string MyConnectionString = "Server=localhost; Database=markcreations; Uid=root; Pwd=admin";
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd = connection.CreateCommand();
cmd.Parameters.AddWithValue("#invoice", row.Cells["Invoice"].Value);
cmd.Parameters.AddWithValue("#jobOrder", row.Cells["jobOrder"].Value);
cmd.Parameters.AddWithValue("#dateTime", row.Cells["Date"].Value);
cmd.Parameters.AddWithValue("#clientCode", row.Cells["Client Code"].Value);
cmd.Parameters.AddWithValue("#clientName", row.Cells["Client Name"].Value);
cmd.CommandText = "INSERT INTO record(invoice, jobOrder, dateTime, clientCode, clientName)VALUES(#invoice, #jobOrder, #dateTime, #clientCode, #clientName)";
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("Records inserted.");
}
It looks like you have an empty row in the DataGridView, probably the last one, which is used for a new row. That row has null values for each column and if you dont check for it, it would insert the NULL's.
You can use row.IsNewRow, to check for the new row.
Thanks buddy it worked.
Here is the Correct code along with row.IsNewRow
private void button5_Click(object sender, EventArgs e)
{
string MyConnectionString = "Server=localhost; Database=markcreations; Uid=root; Pwd=admin";
MySqlConnection connection = new MySqlConnection(MyConnectionString);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
try
{
MySqlCommand cmd = new MySqlCommand();
cmd = connection.CreateCommand();
if (row.IsNewRow) continue;
cmd.Parameters.AddWithValue("#invoice", row.Cells["Invoice"].Value);
cmd.Parameters.AddWithValue("#jobOrder", row.Cells["jobOrder"].Value);
cmd.Parameters.AddWithValue("#dateTime", row.Cells["Date"].Value);
cmd.Parameters.AddWithValue("#clientCode", row.Cells["Client Code"].Value);
cmd.Parameters.AddWithValue("#clientName", row.Cells["Client Name"].Value);
cmd.Parameters.AddWithValue("#jobName", row.Cells["Job Name"].Value);
cmd.Parameters.AddWithValue("#flexQuality", row.Cells["Flex Quality"].Value);
cmd.Parameters.AddWithValue("#sizeLength", row.Cells["Size Length"].Value);
cmd.Parameters.AddWithValue("#sizeWidth", row.Cells["Size Width"].Value);
cmd.Parameters.AddWithValue("#rate", row.Cells["Rate"].Value);
cmd.CommandText = "INSERT INTO record(invoice, jobOrder, dateTime, clientCode, clientName, jobName, flexQuality, sizeLength, sizeWidth, rate)VALUES(#invoice, #jobOrder, #dateTime, #clientCode, #clientName, #jobName, #flexQuality, #sizeLength, #sizeWidth, #rate)";
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("Records inserted.");
}

why my password isn't changed?

I want to change password that saved in db,but my code dose not work. what is wrong? I always see the last message:
unable to connect database
public partial class pws : System.Web.UI.Page
{
static string strcon = (System.Web.Configuration.WebConfigurationManager.ConnectionStrings["strcon"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
private void ShowPopUpMsg(string msg)
{
StringBuilder sb = new StringBuilder();
sb.Append("alert('");
sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
sb.Append("');");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
}
protected void btnInsert_Click(object sender, EventArgs e)
{
try {
SqlConnection db = new SqlConnection(strcon);
db.Open();
string strId = string.Empty;
string strusername = string.Empty;
string OLdpassword = string.Empty;
SqlCommand cmd;
cmd = new SqlCommand("SELECT * FROM login WHERE login_username =#login_username ", db);
cmd.Parameters.AddWithValue("login_username", txtOldUsername.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
cmd = null;
db.Close();
db.Open();
SqlDataReader DR;
DR = cmd.ExecuteReader();
if (DR.Read())
{
strId = DR["login_id"].ToString();
strusername = DR["login_username"].ToString();
OLdpassword = DR["login_Password"].ToString();
}
db.Close();
if (OLdpassword == txtOldPass.Text)
{
db.Open();
string Command = "Update login Set login_Password= #login_Password WHERE login_username=#login_username";
SqlCommand cmdIns = new SqlCommand(Command, db);
cmdIns.Parameters.AddWithValue("#login_Password ", txtNewPass.Text);
cmdIns.Parameters.AddWithValue("#login_username ", txtOldUsername.Text);
cmdIns.ExecuteNonQuery();
cmdIns.Parameters.Clear();
cmdIns.Dispose();
cmdIns = null;
db.Close();
ShowPopUpMsg("successful");
}
else
{
ShowPopUpMsg(" old pass is not correct");
}
}
catch
{
ShowPopUpMsg("unable to connect database");
}
}
}
this part:
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
cmd = null;
db.Close();
db.Open();
SqlDataReader DR;
DR = cmd.ExecuteReader();
why do you execute a non query, which is a query (select * from ...)?
why do you dispose the SqlCommand object cmd and why do you reuse it after disposing?
why do you close and open the line below?
I would rewrite those lines it like this:
SqlDataReader DR = cmd.ExecuteReader();
I would recomment a using statement or closing the connection in a finally block:
SqlConnection db = new SqlConnection(strcon);
try{
db.Open();
//.... the rest
}
catch(Exception ex)
{
ShowPopUpMsg("unable to connect database: " + ex.Message);
}
finally
{
db.Close();
}
and another thing: I would use the primary key in the update statement. where id = login_id instead of the username. unless the username is set to "unique"
Check if you can connect to the database using your credentials and database management tool (I assume you you use MS SQL Server so use MS SQL Server Management Studio)
Check if the format of your connection string is correct. You can use this website http://www.connectionstrings.com/ to do it.
I hope this will help you.
Try to step through the code and find where the exception occures, and look at the details of the exception.
My guess is that there are something wrong with you connection string (strcon).

Deleting from a .mdb with input from textbox

My delete has the same issue where it says
no value given for one or more parameters
I actually don't know the code to fix this.
This is what I have atm:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
string FirstName = txtFirstName.Text;
sql = " DELETE FROM Club_Member WHERE FirstName = #FirstName; ";
dbCmd = new OleDbCommand(sql, dbConn);
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
string FirstName = txtFirstName.Text;
sql = " DELETE FROM Club_Member WHERE FirstName = #FirstName; ";
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd .Parameters.Add(new OleDbParameter("#FirstName",FirstName ));
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
Isn't that obvious?
You declared #FirstName parameter in your SqlCommand but you never add a value as a parameter.
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd.Parameters.AddWithValue("#FirstName", FirstName);
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection dbConn = new OleDbConnection(ConnString))
using(OleDbCommand dbCmd = dbConn.CreateCommand())
{
dbCmd.CommandText = "DELETE FROM Club_Member WHERE FirstName = #FirstName";
dbCmd.Parameters.AddWithValue("#FirstName", FirstName);
dbConn.Open();
dbCmd.ExecuteNonQuery();
}
I always prefer to use Add method instead of AddWithValue because AddWithValue method sends nvarchar type since it is a string variable. But in some cases, you don't want this. You want to declare your SqlDbType as well.
For example, if you have a varchar column and you used AddWithValue method, ADO.NET send it as an nvarchar value and that might cause potential information lost. (for non-Latin characters for example)
This happens mainly because of the Miss spelled values or if you leave any values blank while entering or adding. So database confuses it with a parameter. Debug or just check for spelling.
BTW I wanted to know what is primary key you are using for Club_Member?

Can't Update with sqlcommand and Parameters

I have some trouble to update my sql server 2005 database when i use parameters.Here you can see the code that normally has to work.I precise that i already make others treatments such as insert into and it worked perfectly.
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
//Execute la commande
myCommand.ExecuteNonQuery();
EDIT:When i use hard code such as:
myCommand.CommandText = "Update Action set titre='title' where pk=#Pk";
it works...
I don't know where you went wrong this is the working code for me
string strCon = #"Data Source=SYSTEM19\SQLEXPRESS;Initial Catalog=TransactionDB;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("select * from tblTransaction1", cn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
txtName.Text = ds.Tables[0].Rows[i]["FirstName"].ToString();
txtName1.Text = ds.Tables[0].Rows[i]["LastName"].ToString();
}
}
}
Button click code
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(strCon);
obj1.FirstName = txtName.Text;
obj1.LastName = txtName1.Text;
if (obj1.upDate(cn))
{
}
}
Sample class code file
private bool m_flag = false;
private string strFirstName;
private string strLastName;
public string FirstName
{
get { return strFirstName; }
set { strFirstName = value; }
}
public string LastName
{
get { return strLastName; }
set { strLastName = value; }
}
public bool upDate(SqlConnection con)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
cmd.Parameters.AddWithValue("#Fname", FirstName);
cmd.Parameters.AddWithValue("#Lname", LastName);
cmd.CommandText = "Update tblTransaction1 set LastName=#Lname where FirstName=#Fname";
if (cmd.ExecuteNonQuery() > 0)
{
m_flag = true;
}
}
catch
{
}
return m_flag;
}
Sample Images
I've seen weird results when you forget to include the "CommandType" parameter. Since you using inline SQL, it should be set to "CommandType.Text".
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
// Added CommandType //
myCommand.CommandType = CommandType.Text;
//Execute la commande
myCommand.ExecuteNonQuery();
I have noticed that copying the entire code into a new project helps. I have ran into many times my code would work and then the next day would not, or would only work for someone else and not me. Usually this is due to the designer side of the project when adding and removing code from your project. Just because you delete specific code does not mean the program can update the entire class/project.
If you do :
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
What does it say ?
Try also to prefix your Action table, with the schema name, for example :
myCommand.CommandText = "Update MySchema.Action set titre=#Titre where pk=#Pk";
Because sometimes it can depend on the schema and the user's rights to update this schema.
You could try this: instead of adding the parameters like that
myCommand.Parameters.AddWithValue("#Titre", this.titre);
you should add them with data type.
myCommand.Parameters.Add(new SqlParameter("#Titre", SqlDbType.VarChar, 50));
myCommand.Parameters["#Titre"].Value = this.titre;
That way, the final SQL will be Update Action set titre='titre' instead of Update Action set titre=title. Look that in the second statement titre is not inside quotes ''.
Try adding the parameters after declaring the command.
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
//Execute la commande
myCommand.ExecuteNonQuery();
I found something similar (not identical) here: http://forums.asp.net/t/1249831.aspx/1

check existing record before inserting sql database

I created a simple asp.net form which allow users to view a list of dates for a training and register for that date , they enter their name and employeeid manually ( i dont want to allow dulpicate employe ids), so I need to figure out how to check this on c#..
code:
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
private void checkContraint()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select "; //NEED HELP HERE
}
private void InsertInfo()
{
var dateSelected = dpDate.SelectedItem.Value;
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT #Val1b+','+#Val1,#Val2,#Val3,#Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id =#training_id ";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Val1", txtName.Text);
cmd.Parameters.AddWithValue("#Val1b", txtLname.Text);
cmd.Parameters.AddWithValue("#Val2", txtDept.Text);
cmd.Parameters.AddWithValue("#Val3", txtTitle.Text);
cmd.Parameters.AddWithValue("#Val4", txtEmployeeID.Text);
//Parameter to pass for the select statement
cmd.Parameters.AddWithValue("#training_id", dateSelected);
cmd.CommandType = CommandType.Text;
//cmd.ExecuteNonQuery();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 1)
{
//Success notification // Sends user to redirect page
Response.Redirect(Button1.CommandArgument.ToString());
ClearForm();
}
else
{
//Error notification
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
checkContraint();
InsertInfo();
this way , your query will insert data only if not exists already
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT #Val1b+','+#Val1,#Val2,#Val3,#Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id =#training_id and not exists (select 1 from personTraining pp where pp .employeeid=#Val4) ";

Categories