adding value into sql using textboxes - c#

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;
}
}

Related

Second insert statement not working

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.

C# SQLite command line syntax error

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)

Syntax error in INSERT statement - C#, Access 2013, VS Express 2013

I have been trying to figure out why my program keeps giving me error. system.data.oledb.oledbexception(0x80040E14): Syntax error in INSERT INTO statement.
Table name: User
Columns:
Username
AccountNumber
FirstName
LastName
Code:
namespace Library_System
{
public partial class CreateAccountWindow : Form
{
OleDbConnection connect = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jc\Documents\Visual Studio 2013\Projects\Library System\Library System\LibrarySystemDatabase.accdb;Persist Security Info=False;");
OleDbCommand command = new OleDbCommand();
//OleDbDataReader reader;
public CreateAccountWindow()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string Username = "", AccountNumber = "", FirstName = "", LastName = "";
//int Borrowed = 0;
bool hasValue1 = false, hasValue2 = false, hasValue3 = false, hasValue4 = false;
if (textBox1.Text != "")
{
label1.Hide();
Username = textBox1.Text;
hasValue1 = true;
}
else
{
label1.Show();
label1.Text = "Required";
}
if (textBox10.Text != "")
{
label21.Hide();
AccountNumber = textBox8.Text;
hasValue2 = true;
}
else
{
label21.Show();
label21.Text = "Required";
}
if (textBox8.Text != "")
{
label13.Hide();
FirstName = textBox10.Text;
hasValue3 = true;
}
else
{
label13.Show();
label13.Text = "Required";
}
if (textBox7.Text != "")
{
label12.Hide();
label12.Text = "Required";
LastName = textBox7.Text;
hasValue4 = true;
}
else
{
label12.Show();
label12.Text = "Required";
}
if (hasValue1 || hasValue2 || hasValue3 || hasValue4)
{
try
{
connect.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "insert into User (Username,AccountNumber,FirstName,LastName) values ('" + Username + "','" + AccountNumber + "','" + FirstName + "','" + LastName + "')";
command.ExecuteNonQuery();
MessageBox.Show("REGISTRATION COMPLETE !!", "DONE");
connect.Close();
}
catch (Exception ex)
{
connect.Close();
MessageBox.Show("Error:"+ex.ToString());
}
}
}
}
You are getting the error because USER is a reserved word in Access SQL so you need to enclose the table name in square brackets. Also, as marc_s mentioned in a comment to the question, you should be using a parameterized query like this:
// test data
string Username = "gord";
string AccountNumber = "gt001";
string FirstName = "Gord";
string LastName = "Thompson";
command.CommandText =
"INSERT INTO [User] (Username, AccountNumber, FirstName, LastName) VALUES (?,?,?,?)";
command.Parameters.AddWithValue("?", Username);
command.Parameters.AddWithValue("?", AccountNumber);
command.Parameters.AddWithValue("?", FirstName);
command.Parameters.AddWithValue("?", LastName);
command.ExecuteNonQuery();
You will need a UNIQUE field as primary key.
Fields that generate numbers automatically in Access
SelectCommand = "select ##IDENTITY";
var id = (int)SelectCommand.ExecuteScalar();
did you try to run the insert query directly on db console? in your case its access. you might be having some spelling mistake.
you have initialized oledbcommand object twice. you might not require to initialize it just after oledbconnection object.
also regarding the approach you can use the validators; check this link How to: Validate Data
for oledbcommand parameters check below links:
OleDBParams
Update Data using OLEDB
Insert data using OLEDB

Duplicate entries in database. ASP.NET - C# - SQL Server 2012

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.

SQL update statement in C#

I have table "Student"
P_ID LastName FirstName Address City
1 Hansen Ola
2 Svendson Tove
3 Petterson Kari
4 Nilsen Johan
...and so on
How do I change edit code in C#
string firstName = "Ola";
string lastName ="Hansen";
string address = "ABC";
string city = "Salzburg";
string connectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["LocalDB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Student (LastName, FirstName, Address, City)
VALUES (#ln, #fn, #add, #cit)";
command.Parameters.AddWithValue("#ln", lastName);
command.Parameters.AddWithValue("#fn", firstName);
command.Parameters.AddWithValue("#add", address);
command.Parameters.AddWithValue("#cit", city);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
To edit entry where Lastname field has lastname value and FirstName field has firstname value.
I don't want to use like this
UPDATE Persons SET Address = 'Nissestien 67', City = 'Sandnes'
WHERE LastName = 'Tjessem' AND FirstName='Jakob'
and I edited my original statement to
command.CommandText = "UPDATE Student(LastName, FirstName, Address, City)
VALUES (#ln, #fn, #add, #cit) WHERE LastName='" + lastName +
"' AND FirstName='" + firstName+"'";
But the statement is not getting executed. Why is it throwing SQL exception? Is there any solution to it?
This is not a correct method of updating record in SQL:
command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) VALUES (#ln, #fn, #add, #cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";
You should write it like this:
command.CommandText = "UPDATE Student
SET Address = #add, City = #cit Where FirstName = #fn and LastName = #add";
Then you add the parameters same as you added them for the insert operation.
I dont want to use like this
That is the syntax for Update statement in SQL, you have to use that syntax otherwise you will get the exception.
command.Text = "UPDATE Student SET Address = #add, City = #cit Where FirstName = #fn AND LastName = #ln";
and then add your parameters accordingly.
command.Parameters.AddWithValue("#ln", lastName);
command.Parameters.AddWithValue("#fn", firstName);
command.Parameters.AddWithValue("#add", address);
command.Parameters.AddWithValue("#cit", city);
string constr = #"Data Source=(LocalDB)\v11.0;Initial Catalog=Bank;Integrated Security=True;Pooling=False";
SqlConnection con = new SqlConnection(constr);
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd = new SqlCommand(" UPDATE Account SET name = Aleesha, CID = 24 Where name =Areeba and CID =11 )";
cmd.ExecuteNonQuery();
If you don't want to use the SQL syntax (which you are forced to), then switch to a framework like Entity Framework or Linq-to-SQL where you don't write the SQL statements yourself.
There is always a proper syntax for every language. Similarly SQL(Structured Query Language) has also specific syntax for update query which we have to follow if we want to use update query. Otherwise it will not give the expected results.
Please, never use this concat form:
String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
+ "WHERE supplier_id = " + textBox1.Text;
use:
command.Parameters.AddWithValue("#attribute", value);
Always work object oriented
Edit: This is because when you parameterize your updates it helps prevent SQL injection.
command.Text = "UPDATE Student
SET Address = #add, City = #cit
Where FirstName = #fn and LastName = #add";
private void button4_Click(object sender, EventArgs e)
{
String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("刪除成功");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
String st = "SELECT * FROM suppliers";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
SqlDataReader reader = sqlcom.ExecuteReader();
DataTable datatable = new DataTable();
datatable.Load(reader);
dataGridView1.DataSource = datatable;
//MessageBox.Show("LEFT OUTER成功");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
If you are using EF Core, then you can use FromSqlRaw
Here is an example.
Using Robin's update string, just add SELECT STATEMENT at the end.
String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
+ "WHERE supplier_id = " + textBox1.Text; SELECT Id From supplier WHERE supplier_Id ="+ textBox1,Text
var updatedSupplier = context.Supplier.FromSqlRaw(st).ToList();
(Please note this is using EF Core, Data table has Id column)
String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
+ "WHERE supplier_id = " + textBox1.Text;
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("update successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}

Categories