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)
Related
I'm trying to add values into my database using text boxes.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
string MemberID = txtMember.Text;
string FirstName = txtFirstName.Text;
string LastName = txtLastName.Text;
string Phone = txtTelephone.Text;
string Email = txtEmail.Text;
sql = " INSERT INTO A_Member ( MemberID, LastName, FirstName, Phone, Email) VALUES ( #Member, #LastName, #FirstName, #Phone, #Email);";
dbCmd = new OleDbCommand(sql, dbConn);
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
When i try to use the add button it says "no value given for one or more parameters.
is this something within my .cs or .mdb file? or can i change something in this part of the code?
You have correctly used parameters in your SQL code but you haven't then added those parameters to your command, e.g.
dbCmd.Parameters.AddWithValue("#LastName", lastNameTextBox.Text);
You must add a parameter to the command for each place-holder that appears in your SQL code.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
string memberID = txtMember.Text.Trim();
string firstName = txtFirstName.Text.Trim();
string lastName = txtLastName.Text.Trim();
string phone = txtTelephone.Text.Trim();
string email = txtEmail.Text.Trim();
sql = "INSERT INTO A_Member ( MemberID, LastName, FirstName, Phone, Email) VALUES ( #Member, #LastName, #FirstName, #Phone, #Email);";
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd.Parameters.Add("#MemberID",SqlDbType.Int32).Value = Convert.ToInt32(memberID);
dbCmd.Parameters.Add("#LastName",SqlDbType.Varchar,30).Value = lastName;
dbCmd.Parameters.Add("#FirstName",SqlDbType.Varchar,30).Value = firstName;
dbCmd.Parameters.Add("#Phone",SqlDbType.Int32).Value = Convert.ToInt32(phone);
dbCmd.Parameters.Add("#LastName",SqlDbType.Varchar,30).Value = email;
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
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;
}
Hi guys i came stuck again. I am wanting to edit a selected row from my datagridview and replace the data from dgv with the new information in the text fields. I have managed to get it to change all the data in the dataset. So what i am asking is for guidance on how to code it so it only edits the selected row.
private void btnEdit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = new SqlCommand(String cmdUpdate = #"update Customer set firstName = #firstName, surname = #surname, email = #email, phonenumber = #phone, mobileNumber = #mobile";
, con);
da.UpdateCommand.Parameters.Add("#firstName", SqlDbType.VarChar).Value = textFirstName.Text;
da.UpdateCommand.Parameters.Add("#surname", SqlDbType.VarChar).Value = textSurname.Text;
da.UpdateCommand.Parameters.Add("#email", SqlDbType.VarChar).Value = textEmail.Text;
da.UpdateCommand.Parameters.Add("#phone", SqlDbType.VarChar).Value = textPhone.Text;
da.UpdateCommand.Parameters.Add("#mobile", SqlDbType.VarChar).Value = textMobile.Text;
da.UpdateCommand.Parameters.Add("#ID", SqlDbType.Int).Value = customerDataSet.Customer[0].ID;
con.Open();
da.UpdateCommand.ExecuteNonQuery();
MessageBox.Show("Customer Edited");
con.Close();
}
You UPDATE query updates whole table you should use WHERE statement in this query to update the row
with current ID
update Customer
set firstName = #firstName,
surname = #surname,
email = #email,
phonenumber = #phone,
mobileNumber = #mobile
WHERE ID=#ID
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 have registration as my database table. I want to update my information that has key in by the user into my SQL Server database. But it won't work, it don't occur any errors but the data key in wouldn't update into my database. Someone please help me if anything wrong with my code? Thanks.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE registration SET username = #username, password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno", con);
con.Open();
cmd.Parameters.AddWithValue("#username", TextBoxUsername.Text);
cmd.Parameters.AddWithValue("#password", TextBoxPassword.Text);
cmd.Parameters.AddWithValue("#retypepassword", TextBoxRPassword.Text);
cmd.Parameters.AddWithValue("#gender", DropDownListGender.Text);
cmd.Parameters.AddWithValue("#birth", DropDownListDay.Text);
cmd.Parameters.AddWithValue("#address", TextBoxAddress.Text);
cmd.Parameters.AddWithValue("#city", TextBoxCity.Text);
cmd.Parameters.AddWithValue("#country", DropDownListCountry.Text);
cmd.Parameters.AddWithValue("#postcode", TextBoxPostcode.Text);
cmd.Parameters.AddWithValue("#email", TextBoxEmail.Text);
cmd.Parameters.AddWithValue("#carno", TextBoxCarno.Text);
cmd.ExecuteNonQuery();
con.Close();
if (IsPostBack)
{
Response.Redirect("UpdateSuccess.aspx");
}
After I click confirm it somehow only update my column gender which from male to female, others column of data it won't update.
It might be because the #username is used both in UPDATE and WHERE. If it changes, the WHERE will be wrong and if it does not change it can be left out of the query.
sql update
SqlCommand cmd = new SqlCommand("update[Testing].[dbo].[student] set name= '" + tb1.Text + "',age='" + tb2.Text + "',mobile='" + tb3.Text+ "' where id = '" + tb4.Text + "'", con);
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM registration WHERE username = " + TextBoxUsername.Text + "UPDATE registration SET username = #username, password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno", con);
con.Open();
cmd.Parameters.AddWithValue("#username", TextBoxUsername.Text);
cmd.Parameters.AddWithValue("#password", TextBoxPassword.Text);
cmd.Parameters.AddWithValue("#retypepassword", TextBoxRPassword.Text);
cmd.Parameters.AddWithValue("#gender", DropDownListGender.Text);
cmd.Parameters.AddWithValue("#birth", DropDownListDay.Text);
cmd.Parameters.AddWithValue("#address", TextBoxAddress.Text);
cmd.Parameters.AddWithValue("#city", TextBoxCity.Text);
cmd.Parameters.AddWithValue("#country", DropDownListCountry.Text);
cmd.Parameters.AddWithValue("#postcode", TextBoxPostcode.Text);
cmd.Parameters.AddWithValue("#email", TextBoxEmail.Text);
cmd.Parameters.AddWithValue("#carno", TextBoxCarno.Text);
cmd.ExecuteNonQuery();
con.Close();
if (IsPostBack)
{
Response.Redirect("UpdateSuccess.aspx");
}
I think in page load you are load again all data and Button1_Click run after page load and you lost are all data
you can try your code in page_load method
private void Page_Load()
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE registration SET username = #username, password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno " + "WHERE username = #username", con);
con.Open();
.
.
.
}
}
I have never seen that type of syntax. Usually if one is using parameters, one is using a stored proc (the best practice). If one is using inline SQL, one builds the SQL statement as a single text line and executes it. I would recommend recoding for one of those.
If you want to try what you've started, in your SQL, you probably need to declare all the variables first. For example
SqlCommand cmd = new SqlCommand("declare #username varchar(100), #password varchar(100),
#retypepassword varchar(100) #gender varchar(10), #birth date, #address varchar(100),
#city varchar(100) #country varchar(100), #postcode varchar(10), #email varchar(100),
#carno varchar(100) UPDATE registration SET username = #username, password = #password,
retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address,
city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno",
con);