C# can't insert into Data Source - c#

Here is my code:
try
{
SqlCommand cmd2 = new SqlCommand(#"INSERT INTO Clienti (parola,nume,prenume,adresa,email,kcal_zilnice) VALUES (#Parola,#Nume,#Prenume,#Adresa,#Email,2000)", conn);
cmd2.Prepare();
cmd2.Parameters.AddWithValue("#Parola", passBox.Text);
cmd2.Parameters.Add("#Nume", SqlDbType.VarChar, 50).Value = nameBox.Text;
cmd2.Parameters.Add("#Prenume", SqlDbType.VarChar, 50).Value = pnameBox.Text;
cmd2.Parameters.Add("#Adresa", SqlDbType.VarChar, 100).Value = adressBox.Text;
cmd2.Parameters.Add("#Email", SqlDbType.VarChar, 100).Value = emailBox.Text;
cmd2.ExecuteNonQuery();
}
catch (SqlException exception)
{
MessageBox.Show("Failed! " + exception.Message);
}
MessageBox.Show("User Created!");
I don't know what am I doing wrong here. I even tried to replace #Parola with 'abc' but it does not work. I don't get any error message. Every time I get "User Created", but when I look into the DB I get all the fields NULL(no records where created).

So, for anyone that has the same problem Prepare() solved it.
Use Add() for params and specify The SqlDbType. Prepare() will not work with AddWithValue().
At the end do Prepare() and then ExecuteNonQuery().

Related

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

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.

'System.Data.SqlClient.SqlException' thrown

protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Companyregister";
cmd.Parameters.AddWithValue("#Company_name", txtname.Text);
cmd.Parameters.AddWithValue("#Register_no", txtreg_no.Text);
cmd.Parameters.AddWithValue("#Type", DropDownList1.Text);
cmd.Parameters.AddWithValue("#Address", txtadrs.Text);
cmd.Parameters.AddWithValue("#Email", txtemail.Text);
cmd.Parameters.AddWithValue("#Contact_no", txtphone.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Register succesful");
}
Stored procedure:
CREATE PROCEDURE [dbo].Companyregister
#Company_name varchar(50),
#Register_no varchar(50),
#Type varchar(50),
#Address varchar(50),
#Email varchar(50),
#Contact_no varchar(50)
AS
insert into company_reg (Company_name, Register_no, Type, Address, Email, Contact_no)
values (#Company_name, #Register_no, #Type, #Address, #Email, #Contact_no)
RETURN 0
Error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: String or binary data would be truncated.
The following error indicates that one or more of your data field is NOT able to fit in the DB field. For eg, may be your address is of 60 characters but your DB size for it is only 50 characters.
String or binary data would be truncated.
To solve this, first check if the data you are inserting complies to the sizes defined in you DB. To catch this more easily, define your parameters to stored procedure as follows:
cmd.Parameters.Add("#Company_name", SqlDbType.VarChar, 50).Value = txtname.Text;
cmd.Parameters.Add("#Register_no", SqlDbType.VarChar, 50).Value = txtreg_no.Text;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 50).Value = DropDownList1.Text;
cmd.Parameters.Add("#Address", SqlDbType.VarChar, 50).Value = txtadrs.Text;
cmd.Parameters.Add("#Email", SqlDbType.VarChar, 50).Value = txtemail.Text;
cmd.Parameters.Add("#Contact_no", SqlDbType.VarChar, 50).Value = txtphone.Text;
A good way to start investigating exceptions is to wrap your code in try/catch blocks. This will allow you to dig down in the Exception and hopefully get a more meaningful description of the error. Submitting the Exception as part of your question will help the community in finding the cause.
Use a try/catch block as follows
try{
// code goes here
}
catch (Exception e) // this block is only entered when an exception is thrown in the try block
{
Console.WriteLine(e.ToString()); // print the exception description to the Console (if console application)
}
As suggested in the comments, try executing the Stored Procedure using the same parameters and see if it's successful.
Try like this,
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.Int).Direction = ParameterDirection.Output; /// this is optional if you declare #ID in your store procedure
cmd.Parameters.Add("#Company_name", SqlDbType.VarChar).Value = txtname.Text;
cmd.Parameters.Add("#Register_no", SqlDbType.VarChar).Value= txtreg_no.Text;
cmd.Parameters.Add("#Type", SqlDbType.VarChar).Value = DropDownList1.Text;
cmd.Parameters.Add("#Address", SqlDbType.VarChar).Value = txtadrs.Text;
cmd.Parameters.Add("#Email", SqlDbType.VarChar).Value = txtemail.Text;
cmd.Parameters.Add("#Contact_no", SqlDbType.VarChar).Value = txtphone.Text;
And check your variable size and name

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.

Am I protected against SQL injections?

I have been attacked on my last few questions here for writing code that is open to injections. I am looking for honest help to make sure I am finally doing this the safest and correct way. Please give me any tips to make this as secure as possible.
using (SqlConnection conn = new SqlConnection(""))
{
try
{
SqlCommand cmd = new SqlCommand(#"INSERT dbo.Table (FullName, Category, Street, City, State, Zip, PhoneDay, PhoneEven, Email, Employer, Description, UserName,
UserStreet, UserCity, UserState, UserZip, UserPhoneDay, UserPhoneEven, UserEmail, SubmitDate)
VALUES (#f1, #f2, #f3, #f4, #f5, #f6, #f7, #f8, #f9, #f10, #f11, #f12, #f13, #f14, #f15, #f16, #f17, #f18, #f19, #f20)", conn);
conn.Open();
cmd.Parameters.Add("#f1", SqlDbType.NVarChar, 100).Value = NameTxtBox.Text;
cmd.Parameters.Add("#f2", SqlDbType.NVarChar, 100).Value = HeroicList.SelectedValue;
cmd.Parameters.Add("#f3", SqlDbType.NVarChar, 100).Value = StreetTxtBox.Text;
cmd.Parameters.Add("#f4", SqlDbType.NVarChar, 100).Value = CityTxtBox.Text;
cmd.Parameters.Add("#f5", SqlDbType.NVarChar, 100).Value = StateTxtBox.Text;
cmd.Parameters.Add("#f6", SqlDbType.NVarChar, 100).Value = ZipTxtBox.Text;
cmd.Parameters.Add("#f7", SqlDbType.NVarChar, 100).Value = PhoneDayTxtBox.Text;
cmd.Parameters.Add("#f8", SqlDbType.NVarChar, 100).Value = PhoneEvenTxtBox.Text;
cmd.Parameters.Add("#f9", SqlDbType.NVarChar, 100).Value = EmailTxtBox.Text;
cmd.Parameters.Add("#f10", SqlDbType.NVarChar, 100).Value = EmpTxtBox.Text;
cmd.Parameters.Add("#f11", SqlDbType.NVarChar, 100).Value = WhyTxtBox.Text;
cmd.Parameters.Add("#f12", SqlDbType.NVarChar, 100).Value = UserNameTxtBox.Text;
cmd.Parameters.Add("#f13", SqlDbType.NVarChar, 100).Value = UserStreetTxtBox.Text;
cmd.Parameters.Add("#f14", SqlDbType.NVarChar, 100).Value = UserCityTxtBox.Text;
cmd.Parameters.Add("#f15", SqlDbType.NVarChar, 100).Value = UserStateTxtBox.Text;
cmd.Parameters.Add("#f16", SqlDbType.NVarChar, 100).Value = UserZipTxtBox.Text;
cmd.Parameters.Add("#f17", SqlDbType.NVarChar, 100).Value = UserPhoneDayTxtBox.Text;
cmd.Parameters.Add("#f18", SqlDbType.NVarChar, 100).Value = UserPhoneEvenTxtBox.Text;
cmd.Parameters.Add("#f19", SqlDbType.NVarChar, 100).Value = UserEmailTxtBox.Text;
cmd.Parameters.Add("#f20", SqlDbType.DateTime).Value = DateTime.Now.ToString();
cmd.ExecuteNonQuery();
messageLabel.Text = "Your submission has been sent!";
messageLabel.Visible = true;
}
catch (System.Data.SqlClient.SqlException ex)
{
messageLabel.Text = ex.Message;
messageLabel.Visible = true;
}
}
You're protected with respect to insertion, yes. Using your code, it doesn't matter what the user puts in any of the textboxes (or what they put in any other sort of response they can cook up) nothing will happen beyond their data being stuck into fields of a new row of the given table, exactly as the strings were given to you.
The only way (that comes to mind) that someone could maliciously inject code would depend on how you use the data once it's in the database. If you go and, for example, take a field from this table and stick it in a LiteralControl without escaping anything and show it to other users then someone could stick in nasty JavaScript code that they run on another person's machine, for example. That would be a "cross site scripting" attack. To prevent that you need to make sure that any user-inputted data is sanitized before being displayed.

SQL Transaction with Parameters

I am using a SQL Transaction statement to execute a stored procedure. Traditionally, I would use command parameters to insert different variables into the command.
When I tried to use the same method with a Transaction, the procedure would not insert into the database, although the transaction would work without an error.
Here is how I am trying to do it:
SqlConnection db = DataConn.SqlConnection();
db.Open();
SqlTransaction transaction = db.BeginTransaction();
try
{
const string strSql = "procSiteAddMember #uID, #userName, #password, #nickname, #email, #siteAddress";
var sqlComm = new SqlCommand(strSql, db, transaction) {CommandType = CommandType.Text};
sqlComm.Parameters.Add(new SqlParameter("#uID", SqlDbType.VarChar, 255)).Value = uID;
sqlComm.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar, 20)).Value =
txtRegisterUsername.Text.Trim();
sqlComm.Parameters.Add(new SqlParameter("#password", SqlDbType.VarChar, 20)).Value =
txtRegisterPassword.Text;
sqlComm.Parameters.Add(new SqlParameter("#nickname", SqlDbType.VarChar, 20)).Value =
txtRegisterNickname.Text.Trim();
sqlComm.Parameters.Add(new SqlParameter("#email", SqlDbType.VarChar, 20)).Value = txtRegisterEmail.Text.Trim();
sqlComm.Parameters.Add(new SqlParameter("#siteAddress", SqlDbType.VarChar, 20)).Value = lblNickname.Text.Trim();
//sqlComm.ExecuteNonQuery();
//DataConn.Disconnect();
transaction.Commit();
Response.Redirect("~/Member/" + txtRegisterNickname.Text);
}
catch (Exception ent)
{
Response.Write("Error: " + ent.Message);
}
I saw This post - But it seems pretty long winded with a lot of variables.
You already solved this but since no one answered I'll do it for future reference.
You still need to execute the query so uncommment your line sqlComm.ExecuteNonQuery();
Also don't forget to add transaction.Rollback(); in your catch block, which you have to put inside another try-catch block in case the Rollback throws an exception.
Example:
try
{
...
transaction.Commit();
}
catch (Exception ex)
{
try
{
...
transaction.Rollback();
}
catch (Exception ex2)
{
...
}
}
For more information visit: https://msdn.microsoft.com/en-us/library/86773566(v=vs.110).aspx

Categories

Resources