I've created a website that is connected to the database, I can get data and display it on the page with no prob at all. But when I try to insert (or update) it does nothing.
I have tested the SQL query and it works just fine.
I've looked here for similar situations and questions here for the past 24 hours with no luck.
I want the website to tell if the user want a one way or two way tickets and make a request. The table has the request id which is automatically incremented
then I add the id of the student who is requesting, the the id of the departure ticket then the id of return ticket (if it is 2 ways, this value can be null) there is also status which will be pending until a supervisor either accept or decline the request, once accepted, issue date will be added and status will change to approved. If declined reason will be added and status change to declined.
Main issue, when I make the request, the row is not created and added to the database for the supervisor to view later.
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int parsedValue;
int.TryParse(DropDownList1.SelectedValue, out parsedValue);
SqlConnection myConnection = new SqlConnection(""); // I removed the connection string.
string sqlcommand = "";
string idString = TextBox1.Text;
string idTwoString ="";
bool canContune = false;
if (parsedValue == 1)
{
System.Diagnostics.Debug.WriteLine("p");
Panel3.Visible = true;
idTwoString = TextBox2.Text;
if (AllNumber(idString, TextBox1) && AllNumber(idTwoString, TextBox2))
{
canContune = true;
}
}
else if (AllNumber(idString, TextBox1))
{
canContune = true;
}
if (canContune)
{
int dId;
int dId2;
int.TryParse(idString, out dId);
int.TryParse(idTwoString, out dId2);
sqlcommand = "INSERT INTO TicketRequest.dbo.TicketRequest (student_id, departure_id, return_id, statues, issue_date, notes) "
+ "VALUES (#student_id, #departure_id , #return_id , #statues, #issue_date, #notes)";
try
{
SqlCommand cmd = new SqlCommand(sqlcommand);
cmd.CommandType = CommandType.Text;
cmd.Connection = myConnection;
myConnection.Open();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("departure_id", SqlDbType.Int).Value = dId; //I used AddWithValue(#para, value) it didn't work.
if (parsedValue == 0)
{
cmd.Parameters.AddWithValue("#return_id", DBNull.Value);
}
else
{
cmd.Parameters.Add("#return_id", SqlDbType.Int).Value = dId2;
}
cmd.Parameters.Add("#statues", SqlDbType.Text).Value = "Pending";
cmd.Parameters.AddWithValue("#issue_date", DBNull.Value);
cmd.Parameters.AddWithValue("#notes", DBNull.Value);
cmd.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}`
It doesn't throw any exception, I really don't know what is wrong.
I would be very thankful to anyone who will point me out my mistake in Insert query. Thanks in advance.
==================================================
I apologized all, it worked just fine. it seemed that the code wasn't excuted to being with. Thanks Falanor, you helped me discover the problem. =)
Try to check the return value.
int modified =(int)cmd.ExecuteScalar();
This is also missing the # symbol for the parameter
cmd.Parameters.Add("departure_id", SqlDbType.Int).Value = dId; //I used AddWithValue(#para, value) it didn't work.
Related
private void button4_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='liblib';Data Source=localhost;username=root;password=admin");
String query = "UPDATE loans SET dataRet=#data1 WHERE loans.idloans = #idloan";
MySqlCommand cmd = new MySqlCommand(query, connection);
int id = Int32.Parse(textBox9.Text);
cmd.Parameters.Add("#data1", MySqlDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#idloan", MySqlDbType.Int32).Value = id;
connection.Open();
if (cmd.ExecuteNonQuery() == 1)
{
MessageBox.Show("Succesful!");
connection.Close();
FIllCard();
}
else
{
MessageBox.Show("Error");
connection.Close();
}
When I execute this UPDATE query in phpmyadmin it works and updates the entry:
UPDATE loans SET dataRet='2017-5-6' WHERE loans.idloans = 23.
But the problem is when I try it in my Form whith parameters. It always returns me "Error" message(ExecuteNonQuery is different from 1), and when I check the database there is no update. The type of the variables in my database are:
idloans - int; dataRet = date;
Check out this post: update a mySQL table using C#, It does not have an answer marked as solution, but the OP of that question has authentication problems after using the code of the first answer, perhaps it works for you
I want to shift some variables by one. I searched for the command for it but I couldn't find. If anybody knows it please help me.
Here is the code:
private int shiftNumbers(int number)
{
int newNumber = 0;
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
try
{
con.Open();
cmd = new MySqlCommand(stm, con);
cmd.Parameters.AddWithValue("#number", number);
}
catch (Exception e)
{
ErrorMessage = e.Message;
con.Close();
return null;
}
try
{
rdr = cmd.ExecuteReader();
while(rdr.Read()) {
newNumber = rdr.GetInt32(1);
cmd.Parameters.AddWithValue("#newNumber ", (newNumber-1));
}
}
catch (Exception e)
{
ErrorMessage = e.Message;
con.Close();
return null;
}
con.Close();
return 1;
}
I know this code useless but I show it for you to get the logic that I want to do.
I think your approach is wrong.
First, you read from the database, using a select statement;
Then you go over that result, your rdr.Read();
Then you create a new command, updating the original record;
Move forward in your reader (rdr) and repeat from 2 until you are done.
What you are doing now is impossible. You can't get a result set from an update, just a count affected.
Or, if you can, let your update statement do the calculation (it seems it is only subtracting one from the original number, so why not do that in SQL?):
string stm = "UPDATE devices SET number = number - 1 WHERE number>#number";
Yes, your code is really useless. In your update statement you are passing a parameter #newNumber bu not providing it. Closing the connection in catch block.
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
First decide from where you are going to get the #newNumber value and then add that as parameter and use ExecuteNonQuery() method.
If you want pass the other parameter as well in your method and use it like
private int shiftNumbers(int number, int newNumber)
{
//int newNumber = 0;
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
using(SqlConnection con = new SqlConnection(connectionString))
{
cmd = new MySqlCommand(stm, con);
SqlParameter paramNumber = new SqlParameter("#number", SqlDbType.Int);
paramNumber.Value = number;
SqlParameter paramNewNumber = new SqlParameter("#newNumber", SqlDbType.Int);
paramNewNumber.Value = newNumber;
cmd.Parameters.Add(paramNumber);
cmd.Parameters.Add(paramNewNumber);
con.Open();
cmd.ExecuteNonQuery();
}
//Rest of your code logic if any
}
I am getting error in this line
account = int.Parse(cmd.ExecuteScalar().ToString());// ERROR
every time i am trying to run this program . Its gives me same error.The Account number is an integer and the value is coming from text box1.and the account holder name comes from text box2. this is an SQL transaction method . when i clicked the button the out put i am expecting to increase the balance or reduce the balance. this is the thing i am trying to do. I am not very expert i am trying to learn .Please replay me so i can correct this error.Thnaks
Here is my C# code . But when i run this application its shows following errors.Input stream not in correct format
namespace BANKINHNTIRE1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int account = System.Convert.ToInt32(textBox1.Text);
string sql = "select statementamount from ACCOUNT WHERE Account_Number ='" + textBox1.Text + "'";
SqlConnection cn = new SqlConnection(#"Data Source=KHUNDOKARNIRJOR\KHUNDOKERNIRJOR;Initial Catalog=Login;Integrated Security=True");
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
account = int.Parse(cmd.ExecuteScalar().ToString());
if (account > 0)
{
int j;
SqlTransaction trans;
SqlCommand cmd1 = new SqlCommand();
trans = cn.BeginTransaction();
cmd1.Connection = cn;
cmd1.Transaction = trans;
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "update ACCOUNT set statementamount=statementamount+'" + textBox3.Text + "' where Account_Number ='" + textBox1.Text + "' and First_Name='" + textBox2.Text + "'";
j = cmd1.ExecuteNonQuery();
if (j == 1)
{
trans.Commit();
MessageBox.Show("credited...");
}
else
trans.Rollback();
}
else
{
MessageBox.Show("u can't make credit...");
}
}
}
}
The first thing I'd check is why you trying to convert a statementamount (almost certainly a floating point value) with int.parse().
You're also placing it into the variable account despite the fact it's not an account number, so it may be that you've mistakenly conflated account and amount, in which case it's probably better as:
double amount = Double.Parse(cmd.ExecuteScalar().ToString());
if (amount > 0) ...
In any case, you really should catch exceptions if you can recover from them, and this is certainly a case where you can do so (by, for example, putting up an error dialog then not trying to process the transaction further).
Beyond that, you can break down the statement into components so you can identify where the problem occurs more specifically:
object obj = cmd.ExecuteScalar();
string str = obj.ToString();
account = int.Parse(str);
Single-stepping through that and examining the variables should hopefully make it clear what the actual problem is.
int.Parse will throw an exception if the input cannot be parsed into an integer. You should only use this method if you are sure that the input looks like a number. I would guess that your select statement is returning nothing which causes the error.
You should use int.TryParse() instead which will return true if the parse worked. Some sample code would be
string input = cmd.ExecuteScalar().ToString();
int value;
bool success = int.TryParse(input, out value);
if (success)
{
//use the value
}
Have you tried int.tryparse? Or have you check whether cmd.ExecuteScalar Return a null value. You haven't provide the exact error so I'm just guessing. Try this:
int num1 = 0;
//Check whether cm.ExecuteScalar was null, if yes then use empty string
var sqlResult = cmd.ExecuteScalar() ?? "";
//Next Try parse it to int, if it failed then return 0, you may also return null to determine that you have no records at all.
account = int.TryParse(sqlResult .ToString(), out num1) ? num1 : 0;
You should use int.Parse() or you can put it under try{} catch{} to validate the values passed.
int account = 0;
try
{
account = int.Parse(textBox1.Text.Trim());
}
catch(Exemption emp)
{
account=0; // or any default value
MessageBox.Show(emp.Message);
}
And also, you can check it line by line by adding breakpoint on account. And debug it by pressing F11.
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.