enter image description hereI am writing the update query but it doesn't work. When I run this code, nothing is updated in my database table.
My connection string is
public partial class cutomers : Form
{
public static string connection =
#"Data Source=HOME-PC\SQLEXPRESS;Initial Catalog=WATER-Supply;Integrated Security=True";
SqlConnection con = new SqlConnection(connection);
private void update_Click(object sender, EventArgs e)
{
con.Open();
string UPDATE = "UPDATE Customer_db SET Cust_Phone = #cusphone, Cust_Email = #cusemail, Cust_Address = #cusaddress WHERE Cust_Name = #cusname";
SqlCommand cmd = new SqlCommand(UPDATE, con);
cmd.Parameters.AddWithValue("#cusname", cusname.Text);
cmd.Parameters.AddWithValue("#cusphone", cusphone.Text);
cmd.Parameters.AddWithValue("#cusemail", cusemail.Text);
cmd.Parameters.AddWithValue("#cusaddress", cusaddress.Text);
int i = cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Customer Update...");
}
}
I created a console application and I was able to update with the following code. What is the value returned by: command.ExecuteNonQuery()?
class Program
{
static void Main(string[] args)
{
UpdateCustomerCommand(Guid.Parse("77ceef70-ab98-4392-835d-66c9face5f16"), "John Doe", "johndoe#acme.com");
}
public static string connectionString = #"Data Source=localhost\SQLEXPRESS;Initial Catalog=labdb;Integrated Security=True;Pooling=False";
private static void UpdateCustomerCommand(Guid Id, string name, string email)
{
var updateCommand = "UPDATE [Customer] SET [Name] = #NAME, [EMAIL] = #EMAIL WHERE [Id] = #ID";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(updateCommand, connection);
command.Parameters.Add("#ID", SqlDbType.UniqueIdentifier);
command.Parameters["#ID"].Value = Id;
command.Parameters.Add("#NAME", SqlDbType.NVarChar, 150);
command.Parameters["#NAME"].Value = name;
command.Parameters.Add("#EMAIL", SqlDbType.NVarChar, 100);
command.Parameters["#EMAIL"].Value = email;
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Related
I'm using freesqldatabase.com to get a database for a college project, so having a remotely accessible database is needed. Unfortunately it does not connect to the database. It connects to their myphpadmin just fine but any other connection fails.
private void Submit_registration(object sender, RoutedEventArgs e)
{
SqlConnection sqlCon = new SqlConnection(#"Data Source= sql2.freesqldatabase.com; Initial Catalog=dbname; User ID=id;Password=no, Integrated Security= True;");
sqlCon.Open();
String query = "INSERT INTO tbluser (ID, username, password) VALUES (#ID, #username, #password)";
String query2 = "SELECT MAX(ID) FROM tbluser";
SqlCommand cmd2 = new SqlCommand(query2, sqlCon);
SqlCommand cmd = new SqlCommand(query, sqlCon);
int maxId = Convert.ToInt32(cmd2.ExecuteScalar());
int newmaxid = maxId + 1;
if (String.Equals(text_password.Password,text_password_confirm.Password))
{
cmd.Parameters.AddWithValue("#ID", newmaxid.ToString());
cmd.Parameters.AddWithValue("#username", textbox_username.Text);
cmd.Parameters.AddWithValue("#password", text_password.Password);
cmd.ExecuteNonQuery();
sqlCon.Close();
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
Close();
}
else
{
MessageBox messageBox = new MessageBox();
messageBox.Show();
sqlCon.Close();
}
}
There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?
protected void Page_Load(object sender, EventArgs e) {
rno.Text = Request.QueryString["rno"];//rno is a textbox
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "select fname from table1 where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if (reader.Read()) {
fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
}
reader.Close();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
protected void modify_Click(object sender, EventArgs e) {
fName.ReadOnly = false;
}
protected void savechanges_Click(object sender, EventArgs e) {
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update table1 set fname=#fname where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", sfname);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
I have tried your code which executed fine and updated database table as well.
I have tried like below :
string connectionString = #"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update TestTable set fname=#fname where rno =rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", "Test");
command.Parameters.AddWithValue("#rno", "rno");
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
Another way I have tried.
using (SqlConnection connection = new SqlConnection(connectionString ))
{
connection.Open();
var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";
using (SqlCommand cmd = new SqlCommand(queryText, connection))
{
responseResults = await cmd.ExecuteNonQueryAsync();
}
connection.Close();
}
Hope it would help
After searching for a while, I found out that this code was executing perfectly. The only problem was that everything was inside the page_Load() method and thus the page was reloading everytime I updated the database and thus removing the small window to edit the textboxes. The appropriate solution was to associate this code with some button event rather than with the page_Load() event.
This is my code used for updating a customer in c#, can someone help me correcting the code, so that it will work smoothly?
This is my repository code:
public static void KlantWijzigen(Klant klan)
{
string commandString = string.Format("UPDATE tblKlanten (Adres, Postcode, Gemeente, Email, Telefoonnummer) SET('{0}','{1}','{2}','{3}','{4}')", klan.Adres, klan.Postcode, klan.Gemeente, klan.Email, klan.Telefoonnummer);
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand command = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
conn.Open();
//commandstring toevoegen aan adapter
command.Connection = conn;
command.CommandText = commandString;
adapter.UpdateCommand = command;
//command uitvoeren
adapter.UpdateCommand.ExecuteNonQuery();
//databank connect
conn.Close();
}
My new window code:
public partial class WindowKlantWijzig : Window
{
public WindowKlantWijzig()
{
InitializeComponent();
}
private void buttonSlaOp_Click(object sender, RoutedEventArgs e)
{
Klant upda = new Klant();
upda.Naam = textBoxNieuweNaam.Text;
upda.Adres = textBoxAdresNieuw.Text;
upda.Postcode = Convert.ToInt32(textBoxPostcodeNieuw.Text);
upda.Gemeente = textBoxGemeenteNieuw.Text;
upda.Email = textBoxEmailNieuw.Text;
upda.Telefoonnummer = textBoxTelefoonnummerNieuw.Text;
KlantRepository.KlantWijzigen(upda);
MessageBox.Show("De klant werd succesvol gewijzigd");
}
}
And this is my main window code
private void buttonWijzigKlant_Click(object sender, RoutedEventArgs e)
{
if (comboBoxKlanten.SelectedIndex == -1)
{
MessageBox.Show("Selecteer de klant die je wil wijzigen");
}
else
{
// TODO: gebruiker eerst om bevestiging vragen
Klant klan = (Klant)comboBoxKlanten.SelectedItem;
KlantRepository.KlantWijzigen(klan);
MessageBox.Show("De klant werd succesvol gewijzigd");
//combobox wordt vernieuwd
comboBoxKlanten.ItemsSource = null;
comboBoxKlanten.ItemsSource = KlantRepository.AlleKlanten();
}
}
As response on the question from the comments, I would do it like this: (untested/pseudo) So this is NOT the answer, but a response to prevent SQL-injections.
public static void KlantWijzigen(Klant klan)
{
string commandString = "UPDATE tblKlanten (Adres, Postcode, Gemeente, Email, Telefoonnummer) SET(#Adres, #Postcode, #Gemeente, #Email, #Telefoonnummer)";
using(OleDbConnection conn = new OleDbConnection(connectionString))
using(OleDbCommand command = new OleDbCommand())
{
conn.Open();
//commandstring toevoegen aan adapter
command.Connection = conn;
command.CommandText = commandString;
// de velden zetten via de parameters, zodat SQL-injection niet werkt.
command.Parameters.Add("Adres", OleDbType.VarChar).Value = klan.Adres;
command.Parameters.Add("Postcode", OleDbType.VarChar).Value = klan.Postcode;
command.Parameters.Add("Gemeente", OleDbType.VarChar).Value = klan.Gemeente;
command.Parameters.Add("Email", OleDbType.VarChar).Value = klan.Email;
command.Parameters.Add("Telefoonnummer", OleDbType.VarChar).Value = klan.Telefoonnummer;
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.UpdateCommand = command;
//command uitvoeren
adapter.UpdateCommand.ExecuteNonQuery();
}
}
Don't forget... you're missing a Where clause.. so you are updating ALL records.
You might change (something like):
string commandString = #"
UPDATE tblKlanten (Adres, Postcode, Gemeente, Email, Telefoonnummer)
SET(#Adres, #Postcode, #Gemeente, #Email, #Telefoonnummer)
WHERE id = #Id"; // <<--------------
command.Parameters.Add("Id", OleDbType.Integer).Value = klan.Id;
Is that possible to insert into SQL with DataSet input ?
I have created my DataSet like this :
SqlCommand comm_SelectAll = new SqlCommand(sql_SelectAll, connectionWrapper.conn);
comm_SelectAll.Parameters.AddWithValue("#NO_CLIENT", IdClient);
if (Anne != "")
comm_SelectAll.Parameters.AddWithValue("#DATE_PERIMER", Anne);
SqlDataAdapter adapt_SelectAll = new SqlDataAdapter();
adapt_SelectAll.SelectCommand = comm_SelectAll;
DataSet dSet_SelectAll = new DataSet();
adapt_SelectAll.Fill(dSet_SelectAll);
dSet_SelectAll.Dispose();
adapt_SelectAll.Dispose();
Now I want to insert data into SQL table xx, how can I do that ?
Thanks you in advance
You can try like this ...with out using dataset
public static string BuildSqlNativeConnStr(string server, string database)
{
return string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True;", server, database);
}
private void simpleButton1_Click(object sender, EventArgs e)
{
const string query = "Insert Into Employees (RepNumber, HireDate) Values (#RepNumber, #HireDate)";
string connStr = BuildSqlNativeConnStr("apex2006sql", "Leather");
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add(new SqlParameter("#RepNumber", 50));
cmd.Parameters.Add(new SqlParameter("#HireDate", DateTime.Today));
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException)
{
System.Diagnostics.Debugger.Break();
}
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True"))
{
string sqlQuery = #"UPDATE cottonpurchase SET #slipNo, #basicprice, #weight, #totalamountbasic, #premium, #totalamountpremium, #totalamountpaid, #yeildestimates WHERE farmercode = #farmercode";
{
SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn);
cmd.Parameters.Add("#slipNo", SqlDbType.Int).Value = TxtSlipNo.Text;
cmd.Parameters.Add("#basicprice", SqlDbType.Int).Value = TxtBasicPrice.Text;
cmd.Parameters.Add("#weight", SqlDbType.Int).Value = TxtWeight.Text;
cmd.Parameters.Add("#totalamountbasic", SqlDbType.Int).Value = TxtTotalAmountBasic.Text;
cmd.Parameters.Add("#premium", SqlDbType.Int).Value = TxtPremium.Text;
cmd.Parameters.Add("#totalamountpremium", SqlDbType.Int).Value = TxtTotalAmountPremium.Text;
cmd.Parameters.Add("#totalamountpaid", SqlDbType.Int).Value = TxtTotalAmountPaid.Text;
cmd.Parameters.Add("#yeildestimates", SqlDbType.Int).Value = TxtYeildEstimates.Text;
sqlConn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
It's giving me an error even though everything seems fine with my code:
error : incorrect syntax near ','
You need to specify column names that you are trying to set.
string sqlQuery = #"
UPDATE cottonpurchase
SET
slipNo = #slipNo,
basicprice= #basicprice,
weight = #weight,
totalamountbasic = #totalamountbasic,
premium = #premium,
totalamountpremium = #totalamountpremium,
totalamountpaid = #totalamountpaid,
yeildestimates = #yeildestimates
WHERE farmercode = #farmercode";
Also, you didn't provide #farmercode parameter:
cmd.Parameters.AddWithValue("#farmercode", <someValue>);
You forgot to mention the column names in the set.
string sqlQuery = #"UPDATE cottonpurchase SET slipNo=#slipNo, basicprice=#basicprice, ... WHERE farmercode = #farmercode";