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.
Related
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();
}
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.
I am having problem with my code Always having the error which i am not understanding. Please help with my code
i want to retrieve the user details from the db for login page
string uname = TextBox1.Text.Trim();
string pass = TextBox2.Text.Trim();
try
{
con.Open();
string query = "SELECT user_name, user_password FROM [user] where user_name=#username and user_password=#password";
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = uname;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = pass;
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
rd = cmd.ExecuteReader();
if (rd.HasRows)
{
Response.Write("Login successful");
}
else
{
Response.Write("login Unsucessful");
}
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}
You need to create your cmd prior to adding the paramaters. Your code should look like:
con.Open();
string query = "SELECT user_name, user_password FROM [user] where user_name=#username and user_password=#password";
cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = uname;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = pass;
EDIT: and as #ekad said, you do not need cmd.ExecuteNonQuery();
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.
Hello I have a Stored Proc for the Registration Page, but I need ADO.NET to take values from various textboxes.
However, I'm recieving error like this:
"System.ArgumentException: No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type. "
public void InsertInfo()
{
String empdb = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True";
SqlConnection conn = new SqlConnection(empdb);
SqlCommand cmd = new SqlCommand("bridge_Type", conn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
conn.Open();
cmd.Parameters.Add(new SqlParameter("#EmpID", TextBox1.Text));
cmd.Parameters.Add(new SqlParameter("#Name", TextBox2.Text));
cmd.Parameters.Add(new SqlParameter("#Mob2", TextBox3.Text));
cmd.Parameters.Add(new SqlParameter("#Email", TextBox14.Text));
cmd.Parameters.Add(new SqlParameter("#Emptype", dropdown1.SelectedValue));
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
InsertInfo();
}
Then I used this format to add values from controls:
cmd.Parameters.Add(new SqlParameter("#EmpID", SqlDbType.Int));
cmd.Parameters("#EmpID").Value = TextBox1.Text;
I'm getting errors on:
Its showing errors for these kind of codes by appearing red line under 'Parameters'.
Non-invocable member 'System.Data.SqlClient.SqlCommand.Parameters' cannot be used like a method.
Try TextBox1.Text, TextBox is the Control. The Text property holds the String value.
cmd.Parameters.Add(new SqlParameter("#EmpID", TextBox1.Text));
Try this code.
try
{
string empdb = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True";
using (var conn = new SqlConnection(connString))
{
using (var cmd = new SqlCommand("bridge_Type",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpID",TextBox1.Text);
cmd.Parameters.AddWithValue("#Name", TextBox2.Text);
cmd.Parameters.AddWithValue("#Mob2", TextBox3.Text);
cmd.Parameters.AddWithValue("#Email", TextBox14.Text);
cmd.Parameters.AddWithValue("#EmpType",dropdown1.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
string msg = "Insert Error:"+ ex.Message;
throw new Exception(msg);
}
Make sure you are converting to the types same as the Parameter types in your stored proc ( Ex: If the parameter type of EmpID is int, you may need to convert the TextBox1.Text value to int. Check for null values also.
why dont u use this format?
cmd.Parameters.Add("#parameter", SqlDBType , size).value = TextBox1.Text