SqlException was unhandled by user code for cmd.ExecuteNonQuery() - c#

I am new to .Net. I just started learning it. I came across as error, where it displays that "SqlException was unhandled by user code."
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert tbemp (#eno, #ename, #es, #eadd)";
cmd.Connection = con;
cmd.Parameters.Add("#eno",SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text);
cmd.Parameters.Add("#ename", SqlDbType.VarChar,50).Value = TextBox2.Text;
cmd.Parameters.Add("#es", SqlDbType.VarChar, 50).Value = TextBox3.Text;
cmd.Parameters.Add("#eadd", SqlDbType.VarChar, 50).Value = TextBox4.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
TextBox1.Text = String.Empty;
TextBox2.Text = String.Empty;
TextBox3.Text = String.Empty;
TextBox4.Text = String.Empty;
TextBox1.Focus();
}

Your insert DML is not correct. It should be: insert into tbemp values(#eno, #ename, #es, #eadd).
I would also be very careful with your size limitations of 50 characters and a direct assignment of the TextBox-Values. It might be another exception source.

The SQL query you are setting to cmd.CommandText is not valid SQL. Assuming tbemp is your table name, your query should look like:
insert into tbemp values (#eno, #ename, #es, #eadd)

I would do something like this:
using (SqlCommand cmd = new SqlCommand())
{
try
{
cmd.CommandText =
"INSERT tbemp VALUES (#eno, #ename, #es, #eadd)";
cmd.Connection = con;
cmd.Parameters.Add("#eno", SqlDbType.Int).Value =
Convert.ToInt32(TextBox1.Text);
cmd.Parameters.Add("#ename", SqlDbType.VarChar, 50)
.Value = TextBox2.Text;
cmd.Parameters.Add("#es", SqlDbType.VarChar, 50).Value =
TextBox3.Text;
cmd.Parameters.Add("#eadd", SqlDbType.VarChar, 50).Value =
TextBox4.Text;
cmd.ExecuteNonQuery();
TextBox1.Text = String.Empty;
TextBox2.Text = String.Empty;
TextBox3.Text = String.Empty;
TextBox4.Text = String.Empty;
TextBox1.Focus();
}
catch (SqlException exception)
{
System.Diagnostics.Debug.WriteLine(exception.Message);
throw;
}
catch (Exception exception)
{
System.Diagnostics.Debug.WriteLine
("General Exception caught: " + exception.Message);
throw;
}
In the event of an exception, your SqlCommand will be disposed by putting it in a using statement. Now you will also get diagnostic print out of the errors you are receiving too. Also since you aren't doing anything with the Exception (like trying to fix the issue by a retry or something), you want to throw the exception, so that the code calling the method will know that something is wrong. When rethrowing an exception, you don't want to do this throw exception, because that will reset the stack trace. Just use throw.

Related

C#: Execute a query from Windows Forms using TextBoxes and a Button

How I can change my code, so I can search for specific columns of my table?
I want to write the request's column values in TextBoxes, and then execute the request when I press a Button.
private async void button26_Click(object sender, EventArgs e)
{
if (label77.Visible) label77.Visible = false;
if (!string.IsNullOrEmpty(textBox62.Text) && !string.IsNullOrEmpty(textBox62.Text))
{
SqlCommand command = new SqlCommand("INSERT INTO [Policlinic] ('id_Policlinic', 'Name', 'Address', 'Phone') VALUES (" + textBox62 + ", '" + textBox62 + "', '" + textBox62 + "','" + textBox62 + "')", sqlConnection);
command.Parameters.Add("#id_Policlinic", SqlDbType.Int); command.Parameters["#id_Policlinic"].Value = Convert.ToInt32(textBox62.Text, 4);
command.Parameters.AddWithValue("Name", textBox62.Text);
command.Parameters.AddWithValue("Address", textBox62.Text);
command.Parameters.AddWithValue("Phone", textBox62.Text);
await command.ExecuteNonQueryAsync();
}
else
{
label77.Visible = true;
label77.Text = "Поля должны быть заполнены!";
}
}
Any thoughts?
Try this:
private async void button26_Click(object sender, EventArgs e)
{
//why check the SAME textbox twice?
// You should give MEANINGFUL NAMES to your controls, rather than leaving them at the default
if (string.IsNullOrEmpty(textBox62.Text) || string.IsNullOrEmpty(textBox62.Text))
{
label77.Visible = true;
label77.Text = "Поля должны быть заполнены!";
return;
}
label77.Visible = false;
string sql = "INSERT INTO [Policlinic] (Name, Address, Phone) VALUES ( #Name, #Address, #Phone);";
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
{
//Use exact database column types and lengths here
// DON'T trust ADO.Net to guess these types correctly.
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 20).Value = textBox62.Text;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 80).Value = textBox62.Text;
cmd.Parameters.Add("#Phone", SqlDbType.NVarChar, 14).Value = textBox62.Text;
con.Open()
await cmd.ExecuteNonQueryAsync();
}
}
There are a number of important changes here:
Do NOT try to re-use the same SqlConnection object throughout your application. This interferes with the built-in connection pooling.
Do NOT trust ADO.Net to guess your parameter types and lengths.
DO rely on using blocks to the make sure your connection object is disposed, even if an exception is thrown.
If you're still learning how to do this stuff, I also recommend removing async/await for the time being, and just calling ExecuteNonQuery(). Add that stuff back after you have it working in the "normal" way.
I tried to summarize what you should do in the code below to run this query.
Just remember to replace that textBox62 by something else more suitable.
Make sure you have the right sever address and the right credentials before creating the connection.
After executing the query, you should not keep the connection open for a long time (read this).
private void button26_Click(object sender, EventArgs e)
{
if (label77.Visible) label77.Visible = false;
if (string.IsNullOrEmpty(textBox62.Text))
{
label77.Visible = true;
label77.Text = "Поля должны быть заполнены!";
return;
}
SqlConnection connection = null;
SqlCommand command = null;
try
{
// First create a SQL Connection:
string connectionString = $"Data Source=127.0.0.1;Initial Catalog=MyDatabaseName";
Credential credential = new SqlCredential("myusername", "mypassword");
connection = new SqlConnection(connectionString, credential);
connection.Open();
// Then create the SQL command:
command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO dbo.[Policlinic] (Name, Address, Phone) VALUES (#Name, #Address, #Phone)";
// Add '#' in front of all column names:
command.Parameters.Add(new SqlParameter("#Name", textBox62.Text, 60)
{
SqlDbType = SqlDbType.NVarChar,
Direction = ParameterDirection.Input
});
command.Parameters.Add(new SqlParameter("#Address", textBox62.Text, 120)
{
SqlDbType = SqlDbType.NVarChar,
Direction = ParameterDirection.Input
});
command.Parameters.Add(new SqlParameter("#Phone", textBox62.Text, 20)
{
SqlDbType = SqlDbType.NVarChar,
Direction = ParameterDirection.Input
});
// Execute command:
Task.Run(() => command.ExecuteNonQuery()).Wait();
// Parse any results here...
}
catch (Exception ex)
{
if (ex.InnerException != null) ex = ex.InnerException;
MessageBox.Show(this, ex.ToString(), "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
// Now cleanup this mess:
command?.Dispose();
connection?.Close();
connection?.Dispose();
}
}
Let me know the error message in case you're still in trouble executing that.

Microsoft Access Engine

I'm trying to add data from Visual Studio to Access in C#. Every time I click the button to save the data an error message pops up saying "Microsoft Database Engine". I have no clue where the problem is. I pasted the code below:
private void btnsave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\My Monroe\Semester 5\Advanced Programming\Final Project\WindowsFormsApplication1\WindowsFormsApplication1\Final exam .accdb";
string fname = first_NameTextBox.Text;
string lname = last_NameTextBox.Text;
string snum = sSNTextBox.Text;
string city = cityTextBox.Text;
string state = stateTextBox.Text;
string telnum = telephone__TextBox.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Customers(First Name, Last Name, SSN,City,State,Telephone# )" + " values(#fname,#lname,#snum,#city,#state,#telnum)", connect);
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#fname", OleDbType.Char, 20).Value = fname;
cmd.Parameters.Add("#lname", OleDbType.Char, 20).Value = lname;
cmd.Parameters.Add("#snum", OleDbType.Numeric, 20).Value = snum;
cmd.Parameters.Add("#city", OleDbType.Char, 20).Value = city;
cmd.Parameters.Add("#state", OleDbType.Char, 20).Value = state;
cmd.Parameters.Add("#telnum", OleDbType.Numeric, 20).Value = telnum;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
A few things to check. Firstly change the catch to
MessageBox.Show(ex.Message);
This will be much more informative!
Secondly on which line does the error get thrown? Thirdly, please check your connection string. When I attach to access my string is always of the form:
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DBFullPath\DBName.accdb;Jet OLEDB:Engine Type=5;Persist Security Info=False;"
if there is no password or
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DBFullPath\DBName.accdb;Jet OLEDB:Engine Type=5;Jet OLEDB:Database Password = password;"
if there is one.
Finally, do you really have a telephone field as numeric? What happens with numbers that start with 0 or international ones with +?
EDIT
Sorry I think you misunderstood me. What I wanted you to do, was to amend the catch so that it reads (in full):
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}

fatal error encountered during command execution in c#.net mysql

I have tried the code below when I am going to click Save button I got the error of "fatal error encountered during command execution" I rechecked more than two times but unfortunately error not go away. please, anyone kindly fix this error.
private void button1_Click(object sender, EventArgs e)
{
string cid, lname, fname,street,city,state,phone,date,email,aco,actype,des,bal;
cid = label14.Text;
lname = textBox1.Text;
fname = textBox2.Text;
street = textBox3.Text;
city = textBox4.Text;
state = textBox5.Text;
phone = textBox6.Text;
date = dateTimePicker1.Text;
email = textBox8.Text;
aco = textBox7.Text;
actype = comboBox1.Text;
des = textBox10.Text;
bal = textBox11.Text;
con.Open();
MySqlCommand cmd = con.CreateCommand();
MySqlTransaction transaction;
transaction = con.BeginTransaction();
StringBuilder cmdText = new StringBuilder();
cmdText.AppendLine("INSERT into customer (custid,lastname,firstname,street,city,state,phone,date,email) VALUES (#custid,#lastname,#firstname,#street,#city,#state,#phone,#date,#email)");
cmdText.AppendLine("INSERT into account(accid,custid,acctype,description,balance) VALUES (#accid,#custoid,#acctype,#description,#balance)");
cmd.CommandText = cmdText.ToString();
cmd.Connection = con;
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("#custid", cid);
cmd.Parameters.AddWithValue("#lastname", lname);
cmd.Parameters.AddWithValue("#firstname", fname);
cmd.Parameters.AddWithValue("#street", street);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#accid", aco);
cmd.Parameters.AddWithValue("#cusotid", cid);
cmd.Parameters.AddWithValue("#acctype", actype);
cmd.Parameters.AddWithValue("#description", des);
cmd.Parameters.AddWithValue("#balance", bal);
try
{
cmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Transaction Suceess");
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I have seen many developers encountering errors with their SQL because they are using AddWithValue on their SqlCommand. The issue with this is that the command doesn't know the data type of your sql command parameter.
You should use SqlParameterCollection.Add Method (String, SqlDbType, Int32) to specify the data type of the parameter. Refer to SqlDbType Enumeration for the SqlDbType enumeration.
Usage:
cmd.Parameters.Add("#custid", SqlDbType.Int).Value = cid;
cmd.Parameters.Add("#lastname", SqlDbType.Text).Value = lname;
P.S. I am assuming that there are no issues with your SQL connection string.

SqlException error when I insert into database

This is basically a method to insert a record into a table. It was working fine before I decided to add in a way to check if the Customer ID already exists in the database. I get a
'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Procedure or function InsertCustomer has too many arguments specified.
on the line
command.ExecuteNonQuery();
I don't understand what's wrong.
public void add()
{
lblMessage.Text = "";
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CheckDetails";
command.Parameters.AddWithValue("#CustID", txtCID.Text);
conn.Open();
int check = (int)command.ExecuteScalar();
if (check == 0)
{
command.CommandText = "InsertCustomer";
command.Parameters.Add("#CustID", SqlDbType.Int).Value = txtCID.Text;
command.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFName.Text;
command.Parameters.Add("#Surname", SqlDbType.VarChar).Value = txtLName.Text;
command.Parameters.Add("#Gender", SqlDbType.VarChar).Value = rdoGender.Text;
command.Parameters.Add("#Age", SqlDbType.Int).Value = txtAge.Text;
command.Parameters.Add("#Address1", SqlDbType.VarChar).Value = txtAdd1.Text;
command.Parameters.Add("#Address2", SqlDbType.VarChar).Value = txtAdd2.Text;
command.Parameters.Add("#City", SqlDbType.VarChar).Value = txtCity.Text;
command.Parameters.Add("#Phone", SqlDbType.VarChar).Value = txtPhone.Text;
command.Parameters.Add("#Mobile", SqlDbType.VarChar).Value = txtMobile.Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = txtEmail.Text;
command.ExecuteNonQuery();
lblMessage.Text = "Customer Details Added.";
}
else
{
lblMessage.Text = "Customer ID already exists.";
}
conn.Close();
}
You are adding the same parameter twice:
command.Parameters.AddWithValue("#CustID", txtCID.Text);
// ....
command.Parameters.Add("#CustID", SqlDbType.Int).Value = txtCID.Text;
You can use command.Parameters.Clear();. But i'd prefer to use two different SqlCommands for the two procedures CheckDetails and InsertCustomer to avoid such issues.
Side-note: don't let the database try-cast the value for you. Use int.TryParse.
Remove below parameter from your statement, you already add parameter in command:
command.Parameters.Add("#CustID", SqlDbType.Int).Value = txtCID.Text;

The name '"' does not exist in the current context

I am facing several errors in my code. These errors are:
Error 17 The name 'CommandType' does not exist in the current context
Error 18 The name 'SqlDbType' does not exist in the current context
Error 35 The name 'txtCity' does not exist in the current context
I would like if you can help me to understand the error and tell me how I can fix it.
protected void btnSave_Click(object sender, EventArgs e)
{
// create connectionstring and insert statment
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string insertSql = " INSERT INTO UserInfo (UID, FN, LN, Password, RePass, Email, Country,State, City)" +
" values (#UsrNme, #fnbox, #lnamebox, #passtxtbx1, #passtxtbx2, #emailbox, #DrDncoundrlst, #DropDownListSwestate, #citytxtbox)";
// create SQL Connection
SqlConnection con = new SqlConnection(connectionString);
// create sql command and parameters
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.text;
cmd.CommandText = insertSql;
SqlParameter UID = new SqlParameter("#UsrNme", SqlDbType.nvarchar, 50);
UID.Value = txtUID.text.tostring();
cmd.Parameters.Add(UID);
SqlParameter FN = new SqlParameter("#fnbox", SqlDbType.varchar,25);
cmd.Connection = con;
FN.Value = txtfn.text.ToString();
cmd.Parameters.Add(FN);
SqlParameter LN = new SqlParameter("#lnamebox", SqlDbType.varchar, 25);
cmd.Connection = con;
LN.Value = txtLN.text.ToString();
cmd.Parameters.Add(LN);
SqlParameter Password = new SqlParameter("#passtxtbx1", SqlDbType.varchar, 25);
cmd.Connection = con;
Password.Value = txtPassword.text.ToString();
cmd.Parameters.Add(Password);
SqlParameter RePass = new SqlParameter("#passtxtbx2", SqlDbType.varchar, 25);
cmd.Connection = con;
RePass.Value = txtRePass.text.ToString();
cmd.Parameters.Add(RePass);
SqlParameter Email = new SqlParameter("#emailbox", SqlDbType.varchar, 25);
cmd.Connection = con;
Email.Value = txtEmail.text.ToString();
cmd.Parameters.Add(Email);
SqlParameter Country = new SqlParameter("#DrDncoundrlst", SqlDbType.varchar, 25);
cmd.Connection = con;
Country.Value = txtCountry.text.ToString();
cmd.Parameters.Add(Country);
SqlParameter State = new SqlParameter("#DropDownListSwestate", SqlDbType.varchar, 25);
cmd.Connection = con;
State.Value = txtState.text.ToString();
cmd.Parameters.Add(State);
SqlParameter City = new SqlParameter("#citytxtbox", SqlDbType.varchar, 25);
cmd.Connection = con;
City.Value = txtCity.text.ToString();
cmd.Parameters.Add(City);
try
{
con.Open();
cmd.ExecuteNonQuery();
lblmsg.Text = "You already complete your registration process";
}
catch (SqlException ex)
{
string errorMessage = "error in registration user";
errorMessage += ex.Message;
throw new Exception(errorMessage);
}
finally
{
con.Close();
}
}
You may be way over-complicating things. Try the following code...
var connection = new SqlConnection(connectionString);
var cmd = new SqlCommand(insertSql, connection);
cmd.Parameters.AddWithValue("#UsrNme", txtUID.Text.ToString());
cmd.Parameters.AddWithValue("#fnbox", txtfn.Text.ToString());
cmd.Parameters.AddWithValue("#lnamebox", txtLN.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx1", txtPassword.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx1", txtPassword.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx2", txtRePass.Text.ToString());
cmd.Parameters.AddWithValue("#emailbox", txtEmail.Text.ToString());
cmd.Parameters.AddWithValue("#DrDncoundrlst", txtCountry.Text.ToString());
cmd.Parameters.AddWithValue("#DropDownListSwestate", txtState.Text.ToString());
cmd.Parameters.AddWithValue("#citytxtbox", txtCity.Text.ToString());
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
lblmsg.Text = "You already completed your registration process";
}
catch (SqlException ex)
{
var errorMessage = "error in registration user";
errorMessage += ex.Message;
throw new Exception(errorMessage);
}
finally
{
con.Close();
}
You also want to make sure the you have the following using clauses declared...
using System.Data;
using System.Data.SqlClient;
... and that txtCity is what you actually called your text box and that it's not hidden from this method by a private identifier or actually appears on a different form because the error you're getting means that the variable is outside the method's scope or has its lifetime expire before you reach this method.
Here's what all that code does. Instead of setting up tons of metadata that you should not need to declare your parameters, it lets SqlCommand do all the hard work for you and figure out what type is what based on the database column, the type of the object you passed in, and the name of the parameter. If you end up allowing the passing of invalid data, none of the elaborate metadata markup is going to save you from an error.
Likewise, you really want to look into wrapping your insertSql into a stored procedure like so in Sql Server...
create procedure adduserinfo #UsrNme nvarchar (50),
#fnbox varchar (25),
#lnamebox varchar (25),
#passtxtbx1 varchar (25),
#passtxtbx2 varchar (25),
#emailbox varchar (25),
#DrDncoundrlst varchar (25),
#DropDownListSwestate varchar (25),
#citytxtbox varchar (25)
as begin
INSERT INTO UserInfo
( UID,
FN,
LN,
Password,
RePass,
Email,
Country,
State,
City )
VALUES
( #UsrNme,
#fnbox,
#lnamebox,
#passtxtbx1,
#passtxtbx2,
#emailbox,
#DrDncoundrlst,
#DropDownListSwestate,
#citytxtbox )
end
go
Then your SqlCommand declaration would look like so...
var command = new SqlCommand("adduserinfo", connection)
{
CommandType = CommandType.StoredProcedure;
}
... and for the rest you'd follow the rest of the code I provided above. This would be the more or less proper way to do it. And at the risk of sounding nitpicky, consider more informative and consistently formatted variable and parameter names. Those who might have to modify your code in the future will thank you for it.

Categories

Resources