How to UPDATE multiple times off one connection OleDb - c#

I am trying to update an Access database with information I have passed to a [WebMethod] from multiple txtbox's on a website.
[WebMethod]
public string changePersonalInfo(string email, string name, string id, string address, string contactDetails, string password, string question, string answer, string loggedInEmail)
I am passing all information to it weather it has a value or not.
if (email != "") //Wont execute if there is no value
{
cmd.CommandText = #"UPDATE BuyerInfo SET [emailAddress] = '" + email + "' WHERE (emailAddress = '" + loggedInEmail + "')";
}
if (name != "")
{
cmd.CommandText = #"UPDATE BuyerInfo SET [name] = '" + name + "' WHERE (emailAddress = '" + loggedInEmail + "')";
}
if (id != "")
{
cmd.CommandText = #"UPDATE BuyerInfo SET [id] = '" + id + "' WHERE (emailAddress = '" + loggedInEmail + "')";
}
//etc. It goes on for a few more.
cmd.ExecuteNonQuery();
conn.Close();
The problem is when I run the website it only updates the data from the last txtbox on the website (so in other words the last variable that has a value). How do I fix this, or if there is maybe a better way to do it.
P.S Keep in mind I am new to Web Services.
Thanx

Related

Null Reference when connecting to SQL Server database C# ASP.NET [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
I keep on receiving a null reference when trying to connect to the SQL Server database via Visual Studio 2017. Below is where the reference is and how it is trying to connect to gather the data. Please help! Thank you!.
Profile.aspx
protected void updateProfile(object sender, EventArgs e)
{
// Database entry
string message = "Your information has been updated accoridngly!<br><br>";
double number;
if (txtName.Text.Equals("") || ddlDegree.SelectedValue.Equals("") || txtExperience.Text.Equals("") || !Double.TryParse(txtExperience.Text, out number) || txtSalary.Text.Equals("") || txtStreet.Text.Equals("") || txtCity.Text.Equals("") || txtState.Text.Equals("") || txtZipcode.Text.Equals(""))
{
message += "However:<br>There was an error found in your entry fields, resulting in a failure to store field information. Make sure that all fields are filled and that the Experience field is a double value.";
}
else
{
**myDataLayer.updateStaff(Session["userid"].ToString(), txtName.Text, ddlDegree.SelectedValue, txtExperience.Text, txtSalary.Text, txtStreet.Text, txtCity.Text, txtState.Text, txtZipcode.Text);** - **Null Reference**
}
Here is the data layer class it needs to reference to:
string _ConString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con;
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
SqlDataReader data;
// Handles updating staff info
public bool updateStaff(string userid, string full_name, string degree, string experience, string salary, string street, string city, string state, string zipcode)
{
try
{
con = new SqlConnection(_ConString);
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE staff SET [full_name] = '" + full_name + "', [degree] = '" + degree + "', [experience] = '" + experience + "', [salary] = '" + salary + "', [street] = '" + street + "', [city] = '" + city + "', [state] = '" + state + "', [zipcode] = '" + zipcode + "' WHERE userid = '" + userid + "'";
cmd.ExecuteNonQuery();
con.Close();
return true;
}
catch (OleDbException e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
}
finally
{
con.Close();
}
return false;
}
Your validations are weak and never go with building sql commands for insert, update, delete without parameterizing them. You are prone for SQL-INJECTION.
First, basic validation. By using IsNullOrWhiteSpace, you are preventing nulls to begin with (hence your error), but also a start for your SQL-Injection.
if( string.IsNulllOrWhiteSpace( txtName.Text )
|| string.IsNullOrWhiteSpace( ddlDegree.SelectedValue )
… )
message back about failed values
Now the SQL. User Parameters. What happens if you have a name O'Connor. The first quote would kill your string single-quote balancing.
cmd.Connection = con;
cmd.CommandText =
#"UPDATE staff SET
full_name = #parmFullName,
degree = #parmDegree,
experience = #parmExperience,
salary = #parmSalary,
street = #parmStreet,
city = #parmCity,
state = #parmState,
zipcode = #parmZIP,
where
userid = #parmUserID";
// pulling the parameters from the parameters you pass to your UpdateStaff() call
cmd.Parameters.AddWithValue( "parmFullName", full_name );
cmd.Parameters.AddWithValue( "parmDegree", degree );
cmd.Parameters.AddWithValue( "parmExperience", experience );
cmd.Parameters.AddWithValue( "parmSalary", salary );
cmd.Parameters.AddWithValue( "parmStreet", street);
cmd.Parameters.AddWithValue( "parmCity", city );
cmd.Parameters.AddWithValue( "parmState", state );
cmd.Parameters.AddWithValue( "parmZIP", zipcode );
cmd.Parameters.AddWithValue( "parmUserID", userid );
So, for the most-part, you should be good. No Null values, no mismatched single-quoted strings. This is not the ultimate in validation, you should definitely read more on SQL-Injection and data cleansing though.
In my example, I explicitly add a prefix "parm" to the parameters to differentiate between the actual VALUES you are trying to work with.
Also, if the data columns are of date, integer, double, string, let them remain the type they are intended. The parameters will pass to through correctly.

How to save combobox items in database using the insert into query?

I want to save account in login database using combobox.
When I try to save, I'm presented with the error: "Syntax error in INSERT INTO statement". I tried to find the error in my INSERT INTO statement but i was unable to figure out whats wrong. This is the code I used to add items in combobox:
cmbAccountType2.DropDownStyle = ComboBoxStyle.DropDownList;
string str = null;
str = "User";
cmbAccountType2.Items.Add(str);
str = "Administrator";
cmbAccountType2.Items.Add(str);
And this is the query I used to saved the account in my login database:
private void btnSaveAccount_Click_1(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Do you want to save item?", "Confirmation", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
string q = "INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "', , '" + cmbAccountType2.Text.ToString() + "')";
doSomething(q);
}
else if (result == DialogResult.No)
{
MessageBox.Show("Transaction cancelled.", "Information");
textClear();
}
loadData();
}
You have one extra comma here
"INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "'**, ,** '" + cmbAccountType2.Text.ToString() + "')";
that is the reason of error,but there are some other things you can make better in your code,
using (var cmd = new SqlCommand("INSERT INTO LoginDB (userName, password, accountType) VALUES(#name,#pw,#accType)",yourConnection))
{
cmd.Parameters.AddWithValue("name", txtUserName1.Text);
cmd.Parameters.AddWithValue("pw", txtPassword1.Text);
cmd.Parameters.AddWithValue("accType", cmbAccountType2.Text);
cmd.ExecuteNonQuery();
}
Use parametirized query
Don't use redundant ToString() methods
cmd = new SqlCommand("INSERT INTO LoginDB (userName, password, accountType) VALUES(#name,#pw,#accType)",yourConnection)
cmd.Parameters.AddWithValue("#name", txtUserName1.Text);
cmd.Parameters.AddWithValue("#pw", txtPassword1.Text);
cmd.Parameters.AddWithValue("#accType", cmbAccountType2.SelectedItem);
cmd.ExecuteNonQuery();
txtPassword1.Text.ToString() + "', , '" + cmbAccountType2.Text.ToString() +
I'm not absolutely sure, but since it's a syntax error, I'm assuming this is your error.
It's part of the line where you make the query string.
string q = "INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "', , '" + cmbAccountType2.Text.ToString() + "')";

Implementing database search

I use mysql as database where I store my data.
I have a windows form with textboxes radiobuttons, comboboxes and more; where people give personal information about themselves like (first name, last name, sex, date birthday, phone, father name and more like this). (40 fields total)
I want to do a search button. With this button I want to fill some fields and after I push the search button a new window be opened containing all people with same personal information. I achieved to do a search button for one field (for example searching only by name).
But I have a problem when I select to search with more than one fields. For example I select to search all people who have name:Chris, Nickname:Dung, sex:Male, Birth_Country:UK and other but when I push search it gives back a window with irrelevant with the search data. Can someone help me with that?
The code I made for the search button after changes is:
public MySqlDataAdapter da;
public DataSet ds;
public string sTable = "data";
private void anazitisi_button_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
try
{
conn = openconnectio.GetConn();
string radiob = null;
if (radioButton1.Checked == true)
{
radiob = radioButton1.Text;
}
else if(radioButton2.Checked == true)
{
radiob = radioButton2.Text;
}
StringBuilder Query = new StringBuilder("SELECT * FROM data d INNER JOIN country c ON d.id_data = c.id_country WHERE 1=1 ");
if (!String.IsNullOrEmpty(textBox1.Text))
Query.Append(" AND name like '" + textBox1.Text + "'");
if (!String.IsNullOrEmpty(textBox2.Text))
Query.Append(" AND lastname like '" + textBox2.Text + "'");
if (!String.IsNullOrEmpty(radiob))
Query.Append(" AND sex like '" + radiob + "'");
if (!String.IsNullOrEmpty(maskedTextBox1.Text))
Query.Append(" AND birthdate like '" + maskedTextBox1.Text + "'");
if (!String.IsNullOrEmpty(maskedTextBox2.Text))
Query.Append(" AND phone_number like '" + maskedTextBox2.Text + "'");
MySqlDataAdapter da = new MySqlDataAdapter(Query.ToString(), conn);
ds = new DataSet();
da.Fill(ds, sTable);
conn.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DataGridView dg1 = new DataGridView();
form2.Controls.Add(dg1);
dg1.Dock = DockStyle.Fill;
dg1.Refresh();
dg1.DataSource = ds;
dg1.DataMember = sTable;
form2.Show();
if (conn != null)
{
conn.Close();
}
}
}
My results after search is fine when i comment that code:
(birthdate code) and i dont used as search of course.
//if (!String.IsNullOrEmpty(maskedTextBox1.Text))
// Query.Append(" AND birthdate like '" + maskedTextBox1.Text + "'");
But when i use the (birthdate code) i get us result only a blank row.
I think because the birthdate maskedTextbox have a mask: 00/00/0000
Any suggestion?
Thanks.
I think you should consider three things
1- You may replace OR with And in your query
I mean instead of using
da = new MySqlDataAdapter(
"SELECT * FROM data INNER JOIN country ON id_data = id_country
WHERE name like '" + textBox1.Text +
"'OR lastname like '" + textBox2.Text +
"'OR sex like '" + radiob +
"'OR birthdate like '" + maskedTextBox1.Text +
"'OR phone
_number like '" + maskedTextBox2.Text + "' ;", conn);
You may use
da = new MySqlDataAdapter(
"SELECT * FROM data INNER JOIN country ON id_data = id_country
WHERE name like '" + textBox1.Text +
"'AND lastname like '" + textBox2.Text +
"'AND sex like '" + radiob +
"'AND birthdate like '" + maskedTextBox1.Text +
"'AND phone_number like '" + maskedTextBox2.Text + "' ;", conn);
2- You have to build your query string based on your text boxes and else seeing if they have any value, something like this:
StringBuilder Query = "SELECT * FROM data INNER JOIN country ON id_data = id_country
WHERE 1=1 ";
if(!String.IsNullOrEmpty(textBox1.Text))
Query.Append(" AND name like '" + textBox1.Text);
....
3- Sql Injection vulnerabilities
oh my God !!! Some programming !!!
where clause must created by and/or ,... other clauses ,
so ,
two solutions exist :
On server Side by Store Procedure by below definition :
you must care by position of AND/OR in below :
CREATE PROCEDURE [dbo].[dbo_Bank_SELByFields]
(
#ID nvarchar(50) = NULL ,
#BankName nvarchar(50) = NULL ,
#BankCode nvarchar(50) = NULL ,
#Address nvarchar(50) = NULL ,
#BranchCode nvarchar(50) = NULL
)
AS
SELECT * FROM dbo.Bank WHERE
(
(#ID IS NULL OR ID = #ID) AND
(#BankName IS NULL OR BankName =#BankName) AND
(#BankCode IS NULL OR BankCode =#BankCode) AND
(#Address IS NULL OR Address =#Address) AND
(#BranchCode IS NULL OR BranchCode =#BranchCode)
) ORDER BY BankCode
//---you know call the Sp . OK?
and other solution in your business layer code :
if you use ORM such as Entity Framework , very easy By IQueryable object, you can use below :
var selectByEnyCondition=(from c in ctx.customer ...);
//---- you must add by below way :
if(!(String.IsNullOrEmpty(txtName.Text)))
{
selectByEnyCondition.Where(.....);
}
if(!String.IsNullOrEmpty(sex))
{
selectByEnyCondition= opportunites.Where(.....);
}
//------
/* **** beacuse you use by ADO.NET technique you should use StringBuilder -->*/
StringBuilder query;
query.add("SELECT * FROM BankTbl WHERE ");
if(!(String.IsNullOrEmpty(txtName.Text))){
query.Add("Name Like {0}",txtName.Text);
//-----now continue for build your criteria
king reguard
bye.....

Updating data in database using datagridview

i have a code like this:
public int updateFriend(long id, string Firstname, string Lastname, string Nickname, DateTime Birthdate, int Age, string Gender)
{
OleDbConnection con = new OleDbConnection(conString());
string query = "UPDATE FriendList SET Firstname ='" + Firstname + "', Lastname ='" + Lastname + "',Nickname ='" + Nickname + "',Birthday ='" + Birthdate + "',Age ='" + Age + "', Gender ='" + Gender + "' WHERE ID = " + id;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
return (rowsAffected);
}
now the problem is when i click the update button it calls the method updateFriend, then an error appears on the Line "int rowsAffected = cmd.ExecuteNonQuery();" saying
"No value given for one or more required parameters."
Can somebody help me with this?
string query = "UPDATE FriendList SET Firstname ='" + Firstname + "', Lastname ='" + Lastname + "',Nickname ='" + Nickname + "',Birthday ='" + Birthdate + "',Age ='" + Age + "', Gender ='" + Gender + "' WHERE ID = " + id;
You are passing all parameters as string where some of them are int and one is DateTime. As suggested you should use Parameters.AddWithValue()
string query = "UPDATE FriendList SET Firstname = #Firstname, Lastname = #Lastname , Nickname = #Nickname, Birthday = #Birthdate, Age = #Age, Gender = #Gender WHERE ID = #id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Firstname", FirstName);
//add rest parameters the same way as above
cmd.Parameters.AddWithValue("#id", id);
Talking about on your error message;
"No value given for one or more required parameters."
This message will appears probably one of your parameters is null or zero-length string. Or the reason can be misspelling of your parameters.
Check your query in your database first and look which column gives you an error.
And please, never add your parameters in your sql command. That may cause SQL Injection attack. Always use parameterized query on your queries.
Check out SqlParameterCollection.AddWithValue() method from MSDN.

Update Statement will not update table

I'm trying to update a vendor record in a MS Access table and this is the code if have in the DA layer:
method to update the vendor
public static void updateVendor(Vendor aVendor)
{
try
{
String sSQLCommand = "UPDATE Vendor SET VendorID = '" + aVendor.VendorId + "', VendorName = '" + aVendor.Name
+ "', AddressNo = '" + aVendor.AddressNo + "', Address = '" + aVendor.Address + "', City = '"
+ aVendor.City + "', State = '" + aVendor.State + "', ZipCode = '" + aVendor.Zipcode + "', PhoneNumber = '"
+ aVendor.PhoneNumber + "' WHERE VendorID = '" + aVendor.VendorId + "'";
// Create the command object
if (aConnection.State == ConnectionState.Closed)
aConnection.Open();
OleDbCommand cmd = aConnection.CreateCommand();
cmd.CommandText = sSQLCommand;
// Execute the SQL command
cmd.ExecuteNonQuery();
aConnection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
I'm not getting any kind of error, but it will not update the table, so I'm not sure what is wrong about it, do you see anything that is wrong?
Daniel, if the query is executing without any error and the issue is that no record is updated then check following in data:
VendorID field is text field, so if it's having white space preceding the value in the column then your query will not update any thing but execute successfully.
It's possible because access does n't remove the preceding white space in text.

Categories