I was following this tutorial
http://www.c-sharpcorner.com/UploadFile/1d42da/a-xml-web-service-that-update-data-into-a-default-table-of-t/
And now that I finished it, when I press send the data does not go into the DB, however the code does run in the web service page, just not the forms.
My web service code:
public class SampleService : System.Web.Services.WebService
{
SqlConnection con;
SqlCommand cmd;
[WebMethod]
public int insertPerson(string firstName, string lastName, string DOB, int phoneNumber, string address, int postCode)
{
con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=collegedatabase;Integrated Security=True;Pooling=False");
con.Open();
cmd = new SqlCommand("INSERT INTO person (firstName, lastName, DOB, phoneNumber, address, postCode) VALUES (#firstName, #lastName, #DOB, #phoneNumber, #address, #postCode)", con);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#phoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#postCode", postCode);
int roweffected = cmd.ExecuteNonQuery();
return roweffected;
}
and my .aspx.cs code:
protected void Button1_Click(object sender, EventArgs e)
{
string firstName = TextBox34.Text;
string lastName = TextBox35.Text;
string DOB = TextBox36.Text;
int phoneNumber = Convert.ToInt32(TextBox38.Text);
string address = TextBox37.Text;
int postCode = Convert.ToInt32(TextBox39.Text);
SampleService myservice = new SampleService();
int temp = myservice.insertPerson(firstName, lastName, DOB, phoneNumber, address, postCode);
if (temp == 1)
{
messageLabel.Text = "record is update";
}
else
{
messageLabel.Text = "record is not update";
}
}
EDIT:
So at some point I changed the button name and that's why it wasn't running, however upon changing the button name and clicking the button, I get a crash and the program points to the conn string in the web service, and says that Keyword not supported: 'initialcatalog'.
Place your connection in a using block so that it closes and commits the transaction.
public int insertPerson(string firstName, string lastName, string DOB, int phoneNumber, string address, int postCode)
{
using(SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;InitialCatalog=collegedatabase;Integrated Security=True;Pooling=False"))
{
con.Open();
cmd = new SqlCommand("INSERT INTO person (firstName, lastName, DOB, phoneNumber, address, postCode) VALUES (#firstName, #lastName, #DOB, #phoneNumber, #address, #postCode)", con);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#phoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#postCode", postCode);
int roweffected = cmd.ExecuteNonQuery();
return roweffected;
}
}
OR
call
con.Close();
I had to change the button name to match and also had to remove theusing block
You need to specify the ProviderName as second parameter while supplying connection string.
i suggest you to add both connectionstring and providername in web.config file and access them from code behind.
Add the following statements into the web.config file
web.config
<connectionStrings>
<add name="ConnectionString1" providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=collegedatabase;Integrated Security=True;Pooling=False" />
</connectionStrings>
to access the connectionctring from web.config file try this:
Code behind:
String connectionstring=System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
Complete Code:
public class SampleService : System.Web.Services.WebService
{
SqlConnection con;
SqlCommand cmd;
[WebMethod]
public int insertPerson(string firstName, string lastName, string DOB, int phoneNumber, string address, int postCode)
{
String connectionstring=System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
con = new SqlConnection(connectionstring);
con.Open();
cmd = new SqlCommand("INSERT INTO person (firstName, lastName, DOB, phoneNumber, address, postCode) VALUES (#firstName, #lastName, #DOB, #phoneNumber, #address, #postCode)", con);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#phoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#postCode", postCode);
int roweffected = cmd.ExecuteNonQuery();
return roweffected;
}
Related
I have to insert into two tables (contact and patient) using one transaction. The insert into the contact table works fine, although it is incrementing the contactID by 2. For example, if the most recently added row has a contactID of 25, this method will insert a new row with a contactID of 27. However, the insert into the patient table does nothing at all. The patient table is comprised of only two columns:
patientID INT PRIMARY KEY
contactID INT FOREIGN KEY
The contactID column in the patient table references the contactID column in the contact table. Since the insert is done into the contact table first, I'm not sure why there would be any problems.
public static bool CreatePatient(string lName, string fName, DateTime dob, string streetAddress, string city, string state, string zip, string phone, string gender, string ssn)
{
bool isCreated = false;
int newContactID = 0;
string insertStmt1 = "INSERT INTO contact (lName, fName, dob, mailingAddressStreet, mailingAddressCity, mailingAddressState, mailingAddressZip, phoneNumber, gender, SSN, userType) " +
"VALUES (#last, #first, #dob, #street, #city, #state, #zip, #phone, #gender, #ssn, 4)";
string selStmt = "SELECT MAX(contactID) AS MaxContactID FROM contact";
string insertStmt2 = "INSERT INTO patient (contactID) VALUES (#contact);";
using (SqlConnection connect = DBConnection.GetConnection())
{
connect.Open();
SqlTransaction tran = connect.BeginTransaction();
try
{
using (SqlCommand cmd = new SqlCommand(insertStmt1, connect, tran))
{
cmd.Parameters.AddWithValue("#last", lName);
cmd.Parameters.AddWithValue("#first", fName);
cmd.Parameters.AddWithValue("#dob", dob);
cmd.Parameters.AddWithValue("#street", streetAddress);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#zip", zip);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#gender", gender);
cmd.Parameters.AddWithValue("#ssn", ssn);
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd = new SqlCommand(selStmt, connect, tran))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
newContactID = (int)reader["MaxContactID"];
}
}
}
if (newContactID > 0)
{
using (SqlCommand cmd = new SqlCommand(insertStmt2, connect, tran))
{
cmd.Parameters.AddWithValue("#contact", newContactID);
cmd.ExecuteNonQuery();
}
}
isCreated = true;
tran.Commit();
connect.Close();
}
catch
{
tran.Rollback();
return false;
}
}
return isCreated;
}
public static List<Patient> SearchPatientByFirstAndLastName(string fName, string lName)
{
List<Patient> patientList = new List<Patient>();
string selectStatement = "SELECT * FROM contact INNER JOIN patient ON contact.contactID = patient.contactID "
+ "WHERE contact.fName LIKE '%'+#fName+'%' AND contact.lName LIKE '%'+#lName+'%'";
try
{
using (SqlConnection connection = DBConnection.GetConnection())
{
connection.Open();
using (SqlCommand selectCommand = new SqlCommand(selectStatement, connection))
{
selectCommand.Parameters.AddWithValue("#fName", fName);
selectCommand.Parameters.AddWithValue("#lName", lName);
using (SqlDataReader reader = selectCommand.ExecuteReader())
{
while (reader.Read())
{
Patient patient = new Patient();
patient.PatientID = (int)reader["patientID"];
patient.ContactID = (int)reader["contactID"];
patient.LastName = reader["lName"].ToString();
patient.FirstName = reader["fName"].ToString();
patient.Dob = (DateTime)reader["dob"];
patient.Address = reader["mailingAddressStreet"].ToString();
patient.City = reader["mailingAddressCity"].ToString();
patient.State = reader["mailingAddressState"].ToString();
patient.Zip = reader["mailingAddressZip"].ToString();
patient.Phone = reader["phoneNumber"].ToString();
patient.Gender = reader["gender"].ToString();
patient.Ssn = reader["ssn"].ToString();
patientList.Add(patient);
}
reader.Close();
}
}
connection.Close();
}
}
catch (SqlException ex)
{
throw;
}
catch (Exception ex)
{
throw;
}
return patientList;
}
EDIT
I am now trying a different approach. Instead of handling this all in the program, I created a stored procedure as follows:
CREATE PROCEDURE [dbo].[uspCreatePatient] #last VARCHAR(45), #first VARCHAR(45), #dob DATE, #street VARCHAR(100), #city VARCHAR(100), #state CHAR(2), #zip CHAR(5),
#phone VARCHAR(20), #gender CHAR(1), #ssn CHAR(9), #isCreated BIT OUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #contact INT;
BEGIN TRAN
BEGIN TRY
INSERT INTO contact (lName, fName, dob, mailingAddressStreet, mailingAddressCity, mailingAddressState, mailingAddressZip, phoneNumber, gender, SSN, userType)
VALUES (#last, #first, #dob, #street, #city, #state, #zip, #phone, #gender, #ssn, 4);
SET #contact = SCOPE_IDENTITY();
INSERT INTO patient (contactID) VALUES (#contact)
COMMIT TRAN
SET #isCreated = 1;
END TRY
BEGIN CATCH
ROLLBACK TRAN
SET #isCreated = 0;
END CATCH
END
I then updated the CreatePatient method in C# as follows:
public static bool CreatePatient(string lastName, string firstName, DateTime dob, string streetAddress, string city, string state, string zip, string phone, string gender, string ssn)
{
int result = 0;
bool isCreated = false;
using (SqlConnection connect = DBConnection.GetConnection())
{
using (SqlCommand cmd = new SqlCommand("uspCreatePatient", connect))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#last", lastName);
cmd.Parameters.AddWithValue("#first", firstName);
cmd.Parameters.AddWithValue("#dob", dob);
cmd.Parameters.AddWithValue("#street", streetAddress);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#zip", zip);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#gender", gender);
cmd.Parameters.AddWithValue("#ssn", ssn);
result = cmd.ExecuteNonQuery();
}
}
if (result == 1)
{
isCreated = true;
}
return isCreated;
}
However, the same problem is happening. Only the contact table is being updated. When I run these same commands in SQL Server with hardcoded values, both tables are updated like I want.
So I'm trying to insert text from textbox and combobox controls into an SQLite database, but i am getting a syntax error
private void btnConfirm_Click(object sender, EventArgs e)
{
int indexID = 0;
string username = txtUsername.Text;
string password = txtPassword.Text;
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
int age = cmbAge.SelectedIndex + 1;
string country = cmbCountry.Text;
string city = txtCity.Text;
string address = txtAddress.Text;
string breeds = txtBreeds.Text;
string notes = "None";
SQLiteConnection registerConnection = new SQLiteConnection("Data Source=|DataDirectory|/Resources/database.sqlite;Version=3;");
registerConnection.Open();
SQLiteCommand registerCommand = new SQLiteCommand("INSERT INTO users (indexID,username,password,firstname,lastname,age,country,city,address,tigerbreeds,notes)", registerConnection);
registerCommand.Parameters.AddWithValue("indexID", indexID); //0 for now, but we're going to change this later.
registerCommand.Parameters.AddWithValue("username", username);
registerCommand.Parameters.AddWithValue("password", password);
registerCommand.Parameters.AddWithValue("firstname", firstName);
registerCommand.Parameters.AddWithValue("lastname", lastName);
registerCommand.Parameters.AddWithValue("age", age);
registerCommand.Parameters.AddWithValue("country", country);
registerCommand.Parameters.AddWithValue("city", city);
registerCommand.Parameters.AddWithValue("address", address);
registerCommand.Parameters.AddWithValue("tigerbreeds", breeds);
registerCommand.Parameters.AddWithValue("tigerbreeds", notes);
registerCommand.ExecuteNonQuery();
}
Does anybody have any idea how to fix this?
An unhandled exception of type 'System.Data.SQLite.SQLiteException' occurred in System.Data.SQLite.dll
Additional information: SQL logic error or missing database
near ")": syntax error
Try updating to this:
SQLiteCommand registerCommand = new SQLiteCommand("INSERT INTO users (indexID,username,password,firstname,lastname,age,country,city,address,tigerbreeds,notes) VALUES (#indexID, #username, #password, #firstname, #lastname, #age, #country, #city, #address, #tigerbreeds, #notes)", registerConnection);
registerCommand.Parameters.AddWithValue("#indexID", indexID); //0 for now, but we're going to change this later.
registerCommand.Parameters.AddWithValue("#username", username);
registerCommand.Parameters.AddWithValue("#password", password);
registerCommand.Parameters.AddWithValue("#firstname", firstName);
registerCommand.Parameters.AddWithValue("#lastname", lastName);
registerCommand.Parameters.AddWithValue("#age", age);
registerCommand.Parameters.AddWithValue("#country", country);
registerCommand.Parameters.AddWithValue("#city", city);
registerCommand.Parameters.AddWithValue("#address", address);
registerCommand.Parameters.AddWithValue("#tigerbreeds", breeds);
registerCommand.Parameters.AddWithValue("#notes", notes);
registerCommand.ExecuteNonQuery();
You must construct a valid SQL query . Insert (columnName) Values (#paramName)
Question: data gets duplicated when inserting into database. How do I not make duplicate entries in database?
I read about securing/ preventing SQL injection by not using the
texboxt1.text
So I tried using
parameters.add()
But the entries are duplicated for every insertion.
This is the image of the database...
This is my code
protected void Button1_Click(object sender, EventArgs e)
{
string username = txtuser.Text;
string firstname = txtfirst.Text;
string lastname = txtlast.Text;
string email = txtemail.Text;
string password = txtpass.Text;
string gender = rbgender.Text;
string nationality = ddcountry.Text;
string Connect_string = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
SqlConnection Connect = new SqlConnection(Connect_string);
Connect.Open();
string pass = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
SqlCommand Command = new SqlCommand("INSERT INTO [Users] (username, firstname, lastname, email, password, gender, nationality) VALUES (#username, #firstname, #lastname, #email, #password, #gender, #nationality)", Connect);
Command.Parameters.AddWithValue("#username", username);
Command.Parameters.AddWithValue("#firstname", firstname);
Command.Parameters.AddWithValue("#lastname", lastname);
Command.Parameters.AddWithValue("#email", email);
Command.Parameters.AddWithValue("#password", pass);
Command.Parameters.AddWithValue("#gender", gender);
Command.Parameters.AddWithValue("#nationality", nationality);
Command.ExecuteNonQuery();
int success = Command.ExecuteNonQuery();
if (success > 0)
{
Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#12223");
Label1.Visible = true;
Label1.Text = "You have successfully registered";
Connect.Close();
}
else
{
Label1.Text = "Your information has not been entered to database";
Connect.Close();
}
When I use
INSERT INTO Table () VALUE '"+textbox1.text +"'
it doesn't get duplicated but yeah, SQL injection-thingy.
You have two calls to the ExecuteNonQuery which actually fires the command:
Command.Parameters.AddWithValue("#nationality", nationality);
Command.ExecuteNonQuery(); //CALLED HERE First Time
int success = Command.ExecuteNonQuery(); //CALLED HERE Second Time (This is the one you want)
if (success > 0)
{
Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#12223");
Label1.Visible = true;
Label1.Text = "You have successfully registered";
Connect.Close();
}
You are executing the query twice, by these lines:
Command.ExecuteNonQuery();
int success = Command.ExecuteNonQuery();
Remove the first Command.ExecuteNonQuery() and leave the second one with the int success.
I am working on a database management system. I have a simple task of updating user profile. I created an asp.net page with textboxes and a save button. After adding the text I click on the save button. The code for the button is
protected void Button1_Click(object sender, EventArgs e)
{
string firstName = TextBox2.Text;
string lastName = TextBox1.Text;
string sCourse = TextBox3.Text;
string sTelephone = TextBox4.Text;
string sAddress = TextBox5.Text;
string sEmail = TextBox6.Text;
string Gender = TextBox7.Text;
string user = User.Identity.Name;
OleDbConnection oleDBConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\ASPNetDB.accdb");
string sqlQuerry = "UPDATE aspnet_Users SET firstName=#firstName, lastName=#lastName, Gender=#Gender, Address=#Address, Telephone=#Telephone, Course=#Course, Email=#email WHERE UserName=#UserName";
OleDbCommand cmd = new OleDbCommand(sqlQuerry, oleDBConn);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Email", sEmail);
oleDBConn.Open();
cmd.ExecuteNonQuery();
}
But nothing happens. The database is not updated. Is the code correct?
Add the parameter values in the same order as the parameter names appear in the UPDATE statement.
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Email", sEmail);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);
OleDb with Access does not pay attention to the parameter names, only their order.
add the parameters according to the order in the query
string sqlQuerry = "UPDATE aspnet_Users SET firstName=#firstName, lastName=#lastName, Gender=#Gender, Address=#Address, Telephone=#Telephone, Course=#Course, Email=#email WHERE UserName=#UserName";
OleDbCommand cmd = new OleDbCommand(sqlQuerry, oleDBConn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Email", sEmail);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);
I get this error in ASP.NET Wizard when I try to use values of TextBox control of previous step.
Error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Contact_Emp".
The conflict occurred in database "KKSTech", table "dbo.Emp", column 'EmpID'.
Is it a problem to access control's values of different steps?
This is the First class that inserts into dbo.Emp table
public void InsertInfo()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String insertstring = #"insert into Emp (EmpID, FirstName, LastName, MiddleName, Mob1, Mob2, Phone, Email1, Email2, EmpDesc)
values (#EmpID, #FirstName, #LastName, #MiddleName, #Mob1, #Mob2)";
SqlCommand cmd = new SqlCommand(insertstring, conn);
cmd.CommandText = insertstring;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.Parameters.AddWithValue("#FirstName", TextBox2.Text);
cmd.Parameters.AddWithValue("#LastName", TextBox3.Text);
cmd.Parameters.AddWithValue("#MiddleName", TextBox4.Text);
cmd.Parameters.AddWithValue("#Mob1", TextBox5.Text);
cmd.Parameters.AddWithValue("#Mob2", TextBox6.Text);
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
And this is the one where I 'm inserting into the table where EmpID is a FK
public void Insertaddress()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String str = #"insert into Contact (Addressline1, Addressline2, CityID, EmpID)
values(#Addressline1, #Addressline2, #CityID, #EmpID)";
SqlCommand cmd = new SqlCommand(str, conn);
cmd.CommandText = str;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#Addressline1", TextBox15.Text);
cmd.Parameters.AddWithValue("#Addressline2", TextBox17.Text);
cmd.Parameters.AddWithValue("#CityID", DropDownList2.SelectedValue);
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
That was my problem.
A foreign key ensures that it cannot have a value in that column that is not also in the primary key column of the referenced table.
In your case , you are inserting EmpID into contact table which is not present in the referenced table of EmpID i.e Emp table.