I am working on my simple task in c# with service based database. I have a service-based database where I have table staff with columns id, name and password. I am trying to insert new record into that table, with C# code, but it's not inserting, just telling me "No Record ADDED" even there is no error.
My code is:
private void button5_Click(object sender, EventArgs e)
{
try
{
connetionString = Properties.Settings.Default.testdbConnectionString;
cnn = new SqlConnection(connetionString);
cnn.Open();
SqlCommand command6;
string sql6 = null;
sql6 = "insert into staff (name,pwd,id) values(#n,#p,#fid)";
command6 = new SqlCommand(sql6, cnn);
command6.Parameters.AddWithValue("#n", "jhon");
command6.Parameters.AddWithValue("#p", "test");
command6.Parameters.AddWithValue("#fid", 1);
int result = command6.ExecuteNonQuery();
if (result == 0)
{
MessageBox.Show("Record ADDED");
}
else
{
MessageBox.Show("No Record ADDED");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
If you need more detail you my ask but please correct my mistake. Thanks
The result of ExecuteNonQuery is the number of records affected. Your if statement is the wrong way round... if the result doesn't equal zero then something was inserted.
Related
When I enter a number in the ChbBeds_numericUpDown and click on the "Update" button, it says "Data Updated", but nothing changes in the database
private void ChbUp_button_Click(object sender, EventArgs e)
{
try
{
string statement = "UPDATE ChamberXPavilions SET Beds count = #beds_count WHERE Pav_name = #pav_name AND Chamber_number = #chamber_number";
cmd = new OleDbCommand(statement, conn);
cmd.Parameters.AddWithValue("#pav_name", Chbpav_comboBox.Text);
cmd.Parameters.AddWithValue("#chamber_number", Chb_numericUpDown.Value);
cmd.Parameters.AddWithValue("#beds_count", ChbBeds_numericUpDown.Value);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Data updated");
showdata();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Is the SQL statement wrong ?
Contrary to SQL Server, the OleDB provider for MS Access does NOT work with named parameters - instead, it uses positional parameters.
In your case, you have a SQL statement
UPDATE ChamberXPavilions
SET Beds count = #beds_count
WHERE Pav_name = #pav_name AND Chamber_number = #chamber_number
so you need to also provide the parameters in the same order - first #beds_count, then #pav_name and finally #chamber_number.
So try this for providing the parameter values:
cmd = new OleDbCommand(statement, conn);
cmd.Parameters.AddWithValue("#beds_count", ChbBeds_numericUpDown.Value);
cmd.Parameters.AddWithValue("#pav_name", Chbpav_comboBox.Text);
cmd.Parameters.AddWithValue("#chamber_number", Chb_numericUpDown.Value);
Now, your UPDATE statement should get the proper values and should now work
I have a datatable with 5 columns, (Song, Artist, Album, Genre, Time) the table allows for me to enter as many rows as i want to create a playlist of music, when the user sees fit they can click the button export the data to access. My access database has a table named "Playlist" with the same 5 columns as the data table. When trying to transfer the data, i keep getting the exception error for the Insert INTO statement and I have no idea why because i am using a commandBuilder. I have attached my class and method thats performing this action.
Please advise!
public void ExportPlaylistToAccess(DataTable playlist)
{
// open connection to the database pathed to
String connection = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= D:\CIS 465\Final Project\VirtualiPod\iTunesPlaylistDatabase.accdb";
using (OleDbConnection con = new OleDbConnection(connection))
{
var adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand("SELECT * from [Playlist]", con);
var cbr = new OleDbCommandBuilder(adapter);
cbr.GetDeleteCommand();
cbr.GetInsertCommand();
cbr.GetUpdateCommand();
try
{
con.Open();
adapter.Update(playlist);
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message, "Database Error");
}
catch (Exception x)
{
MessageBox.Show(x.Message, "Exception Error");
}
}
dataTable creation
private void createPlaylist_Click(object sender, EventArgs e)
{
if (playlist.Rows.Count == 0)
{
playlist.Columns.Add("Song");
playlist.Columns.Add("Artist");
playlist.Columns.Add("Album");
playlist.Columns.Add("Genre");
playlist.Columns.Add("Time");
dataGridView1.DataSource = playlist;
}
else if (playlist.Rows.Count > 0)
{
MessageBox.Show("Please clear your current playlist to create a new one.");
}
}
// adds song to playlist for user upon click
private void addToPlaylist_Click(object sender, EventArgs e)
{
IITTrackCollection tracks = app.LibraryPlaylist.Tracks;
IITTrack currentTrack = app.CurrentTrack;
DataRow newRow;
newRow = playlist.NewRow();
newRow["Song"] = currentTrack.Name;
newRow["Artist"] = currentTrack.Artist;
newRow["Album"] = currentTrack.Album;
newRow["Genre"] = currentTrack.Genre;
newRow["Time"] = currentTrack.Time;
playlist.Rows.Add(newRow);
dataGridView1.DataSource = playlist;
}
Time is a reserved word. For some reason the command builder does not surround fields that are database reserved words (time, date, long etc.) with brackets [time] which would allow the insert query to work correctly. Without the brackets the insert will fail as the SQL compiler does not know if the string time is a sql command or a field name. The only solution I've found is to rename your database fields so that they are not in conflict with the database reserved names. Hopefully MS will eventually fix this mistake.
Sorry guys to my english..
when i insert a record the same description with the existing record in datagridview but different quantity.. it creates a new row for the last record i inserted...
what i want is to ADD the quantity i inserted to the old record with the same description..
1. HERE'S THE IMAGE FOR YOU TO UNDERSTAND THE PROBLEM
2. THIS IS WHAT HAPPEN
The result should be QUANTITY = 25.. and also the totalcbm.. totalcbm = quantity * cbm
private void btnSave_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO Inventory(Quantity,Unit,ItemCode,ItemName,Cbm,TotalCbm)VALUES(#Quantity,#Unit,#ItemCode,#ItemName,#Cbm,#TotalCbm)";
cmd.Parameters.AddWithValue("#Quantity", tbQuantity.Text.ToString());
cmd.Parameters.AddWithValue("#Unit", tbUnit.Text.ToString());
cmd.Parameters.AddWithValue("#ItemCode", tbItemCode.Text.ToString());
cmd.Parameters.AddWithValue("#ItemName", tbItemName.Text.ToString());
cmd.Parameters.AddWithValue("#Cbm", tbCbm.Text.ToString());
cmd.Parameters.AddWithValue("#TotalCbm", tbTotalCbm.Text.ToString());
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
frmUserAE form1 = new frmUserAE();
AccountForm.LoadGrid();
this.Hide();
}
}
}
You are doing an INSERT statement, which will create a new row.
You should do an UPDATE statement, depending on what you think is your primary key (the description?).
So I have this code that is designed to delete a row in mySQL server database judging by what is selected in my list box. Here is the code I have to remove the rows:
private void remove_btn_Click(object sender, EventArgs e)
{
try
{
if (Calls_lsb.SelectedItem == null)
MessageBox.Show("Please select an item for deletion.");
}
else
{
int i = Calls_lsb.SelectedIndex;
if (i > 0)
{
SqlConnection connection = new SqlConnection(//My Connection String);
string sqlStatement1 = "DELETE FROM Records WHERE CallID = #Id";
string sqlStatement2 = "DELETE FROM Calls WHERE CallID = #Id";
connection.Open();
SqlCommand cmd1 = new SqlCommand(sqlStatement1, connection);
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
cmd1.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand(sqlStatement2, connection);
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
cmd2.ExecuteNonQuery();
connection.Close();
Calls_lsb.Items.Remove(Calls_lsb.Items[i]);
}
else
{
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I get no exceptions and I have similar code that adds records that works fine. I tried stepping into the code but it all seemed fine. It simply just does not delete the row from the database. It removes the correct item from the list, just not the database.
If anyone could shine some light on this situation that would be great, thanks!
Edit : Ok, I seem to have fixed the problem. I just removed the whole i = selected index stuff and replace the 'Calls_lsb.Items[i]' with '(Calls_lsb.SelectedIndex + 1)'. I don't really understand why I was getting an exception when I tried to add 1 to i as this is basically doing the same thing.
Replace your below line code.
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
//with
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i].Value);
and
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
// with
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i].Value);
I am Nubie in C#, I Try to learn CRUD. Select data Succes but I cant Save data to mysql.
my table
mahasiswa
ID| namae | jurusan | email
_____________________________
1 | Bill | IT | bill#gmail.com
2 | Tony | IT | Tony#gmail.com
ID is set to auto increment in Mysql
and this my script for btn save
void btnsave_Click(object sender, EventArgs e)
{
try
{
if (txtid.Text != "" && txtnama.Text != "" && txtjurusan.Text != "" && txtemail.Text != "")
{
query = string.Format("INSERT INTO mahasiswa values ('{1}','{2}','{3}');", txtnama.Text, txtjurusan.Text, txtemail.Text);
koneksi.Open();
perintah = new MySqlCommand(query, koneksi);
adapter = new MySqlDataAdapter(perintah);
int res = perintah.ExecuteNonQuery();
koneksi.Close();
if (res == 1)
{
MessageBox.Show("Input Data Sukses...");
}
else
{
MessageBox.Show("Input Data Gagal... ");
}
}
else
{
MessageBox.Show("Data tidak lengkap");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
That Script can run, but after input data and click save buttonm the program stop.
Can anybody help me.
Im very Appreciated your answer
Thanks
form load
void Form1_Load(object sender, EventArgs e)
{
try
{
koneksi.Open();
query = string.Format("SELECT * FROM mahasiswa");
perintah = new MySqlCommand(query, koneksi);
adapter = new MySqlDataAdapter(perintah);
perintah.ExecuteNonQuery();
ds.Clear();
adapter.Fill(ds);
koneksi.Close();
dgv1.DataSource = ds.Tables[0];
dgv1.Columns[0].Width = 50;
dgv1.Columns[0].HeaderText = "ID";
dgv1.Columns[1].Width = 120;
dgv1.Columns[1].HeaderText = "Nama Mahasiswa";
dgv1.Columns[2].Width = 120;
dgv1.Columns[2].HeaderText = "Jurusan";
dgv1.Columns[3].Width = 120;
dgv1.Columns[3].HeaderText = "Email";
//txtid.clear();
txtnama.Clear();
txtjurusan.Clear();
txtemail.Clear();
btnedit.Enabled = false;
btndelete.Enabled = false;
btnsave.Enabled = true;
btnsearch.Enabled = true;
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
Also if your learning CRUD it would be helpful if you made the necessary stored procedures within SQL aswell as attempting it this way.
Just create a CREATE, INSERT, UPDATE, DELETE procedure. Then in your code for an insert example you have this:
public bool Add(string example)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("[Proc name]", con);
cmd.CommandType = CommandType.StoredProcedure;
if (con.State == ConnectionState.Closed)
con.Open();
cmd.Parameters.AddWithValue("#Example", example);
cmd.ExecuteNonQuery();
return true;
}
}
This allows you to view what happens and to ensure your procedures are working correctly. This way allows you to catch exceptions easier, and also validate your inputs easier.
try this
"INSERT INTO mahasiswa (name,jurusan,mail) values ('{1}','{2}','{3}')", txtnama.Text, txtjurusan.Text, txtemail.Text)";
as your query will instruct mysql to look for 4 values whereas you are passing only 3 values.
Do not use string concatenation to build sql command text, use always a parameterized query
query = "INSERT INTO mahasiswa VALUES (#p1,#p2,#p3);";
using(MySqlConnection koneksi = new MySqlConnection(connectionString))
using(MySqlCommand perintah = new MySqlCommand(query, koneksi))
{
koneksi.Open();
perintah.Parameters.AddWithValue("#p1", txtnama.Text);
perintah.Parameters.AddWithValue("#p2", txtjurusan.Text);
perintah.Parameters.AddWithValue("#p3", txtemail.Text);
int res = perintah.ExecuteNonQuery();
if (res == 1)
MessageBox.Show("Input Data Sukses...");
else
MessageBox.Show("Input Data Gagal... ");
}
If you use string concatenation your code will be open to sql injection where a malicious user could wreak havoc with your database (Look at this funny example)
Also your format statement is totally wrong, I doubt that your code reaches the point where the database command is executed because you list the arguments for string.Format from the index 1 to index 3 and you supply 3 arguments, but the index should start from zero and end at two. So you should get an exception on that line.
Another point to keep note is the using statement. As you can see, in my code the using statement will ensure the proper closing and disposing of the connection and command objects. The connection is particularly important to dispose properly because a failure here could break your program later.