Where and how to write this SQL query? - c#

This is my SQL query and its running but I want to update a particular table column with this query so how and where I write update query?
public void Add()
{
SqlConnection sqlcon = new SqlConnection("server =(LocalDB)\\MSSQLLocalDB; Database = Online Medical Store ; integrated security = true");
sqlcon.Open();
SqlCommand cmd = new SqlCommand("select LastName, FirstName, FatherName, Address, City, Contact, EmailAddress,BookSubject,BookTitle,EditionNumber,ISBN_Number,Issue_Date from IssueBooks where StudentID =#studentID and " +
"ISBN_Number = #isbnNumber", sqlcon);
cmd.Parameters.AddWithValue("#studentID", studentId);
cmd.Parameters.AddWithValue("#ISbnNumber", ISbnNumber);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
throw new Exception(" One Student Can Take Only One Book ");
}
else
{
SqlConnection con = new SqlConnection("server =(LocalDB)\\MSSQLLocalDB; Database = Online Medical Store ; integrated security = true");
con.Open();
SqlCommand sqlcmd = new SqlCommand("insert into IssueBooks(StudentID,LastName,FirstName,FatherName,Address, City," +
" Contact, EmailAddress, BookSubject, BookTitle,EditionNumber, ISBN_Number,Issue_Date)values" +
"(#studentID,#lastName,#firstName,#fatherName,#address,#city, #contact,#emailAddress,#BookSubject, #BookTitle, #EditionNumber, #ISBN_Number,#IssueDate)", con);
sqlcmd.Parameters.AddWithValue("#studentID", studentId);
sqlcmd.Parameters.AddWithValue("#lastName", LastName);
sqlcmd.Parameters.AddWithValue("#firstName", FirstName);
sqlcmd.Parameters.AddWithValue("#fatherName", FatherName);
sqlcmd.Parameters.AddWithValue("#address", Address);
sqlcmd.Parameters.AddWithValue("#city", City);
sqlcmd.Parameters.AddWithValue("#contact", Contact);
sqlcmd.Parameters.AddWithValue("#emailAddress", EmailAddress);
sqlcmd.Parameters.AddWithValue("#BookSubject", bookSubject);
sqlcmd.Parameters.AddWithValue("#BookTitle", bookTitle);
sqlcmd.Parameters.AddWithValue("#EditionNumber", EditionNumber);
sqlcmd.Parameters.AddWithValue("#ISBN_Number", isbnNumber);
sqlcmd.Parameters.AddWithValue("#IssueDate", Issue_Date);
sqlcmd.ExecuteNonQuery();
}
sqlcon.Close();
}

Related

How to post records from my windows form to my database

Good day, thanks for the assistance previously. please am trying to POST records from my window form to database, am having challenges with it, how do i do it?
Below is the code snippet i coded it with
private void btnNext_Click(object sender, EventArgs e)
{
//Calling Window Work experience page
WorkExperience frm = new WorkExperience();
frm.ShowDialog();
string connectionString = #"Data Source=localhost;" +
"Initial Catalog=EmploymentDb;Integrated Security=true; User Instance=False";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.Connection = connection;
//command.CommandText
string sql = "INSERT INTO EmploymentDb " +
"(Id,Title, LastName, FirstName, MiddleName, Gender, Address, Email, City, State, MobileNumber, DateOfBirth, HomePhone, DistchargeCertNumber, SchoolAttended, NYSCStatus, AgeLimit) VALUES " +
"(#Id, #Title, #LastName, #FirstName, #MiddleName, #Gender, #Address, #Email, #City, #State, #MobileNumber, #DateOfBirth, #HomePhone, #DistchargeCertNumber, #SchoolAttended, #NYSCStatus, #AgeLimit)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Id", txtID.Text);
cmd.Parameters.AddWithValue("#Title", comboBoxtTitle.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#MiddleName", txtMiddleName.Text);
cmd.Parameters.AddWithValue("#Gender", comboBoxGender.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#City", comboBoxCity.Text);
cmd.Parameters.AddWithValue("#State", comboBoxState.Text);
cmd.Parameters.AddWithValue("#MobileNumber", txtMobileNo.Text);
cmd.Parameters.AddWithValue("#DateOfBirth", dateTimePickerDOB.Text);
cmd.Parameters.AddWithValue("#HomePhone", txtHomePhone.Text);
cmd.Parameters.AddWithValue("#DistchargeCertNumber", txtNYSCCertNumder.Text);
cmd.Parameters.AddWithValue("#SchoolAttended", txtSchoolAttended.Text);
cmd.Parameters.AddWithValue("#NYSCStatus", comboBoxNYSCStatus.Text);
cmd.Parameters.AddWithValue("#AgeLimit", cbxAgeLimit.Text);
int affectedRows = cmd.ExecuteNonQuery();
MessageBox.Show(affectedRows + "Row inserted!");
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds, "Employment");
FillControls();
btnNext.Enabled = true;
// btnPrevious.Enabled = true;
}
You need to provide SqlConnection for SqlDataAdapter, if you want to retrieve the data back. Otherwise, you can delete the following 4 lines of code.
var query = "SELECT Id,Title FROM EmploymentDb";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
^^^^^^
DataSet ds = new DataSet();
da.Fill(ds, "Employment");

How to Save 2 different Cell values into 2 different variables from database C#

I am stuck on collecting 2 column values from a database row.
this method is only working to retrieve one value, not for 2. I need to save values from cells to Different variables then I will use these variables to populate another database.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
SqlCommand command = new SqlCommand();
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity= Quantity - {0} WHERE id='"+tbItemid.Text+"'", Convert.ToInt32(tbQuantity.Text));
command.ExecuteNonQuery();
con2.Close();
Data();
DData();
con2.Open();
int x = int.Parse(tbQuantity.Text);
SqlCommand cmd1 = new SqlCommand("SELECT Model from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
con2.Close();
con.Open();
int y = int.Parse(tbQuantity.Text);
SqlCommand cmd2 = new SqlCommand("SELECT Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader pricerdr = null;
pricerdr = cmd2.ExecuteReader();
pricerdr.Read();
int price = int.Parse(pricerdr["Price"].ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (" + tbItemid.Text + ",'" +model.ToString()+ "',"+price.ToString()+",'"+tbQuantity.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
First thing first you should use Parameterized Queries instead of Concatenations. These kind of queries are prone to SQL Injection. You can read both the columns in one command
SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
int price = int.Parse(modelRdr["Price"].ToString());
The complete code with Parameters would look like
string model=String.Empty;
int price = 0;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
using(SqlCommand command = new SqlCommand())
{
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity = Quantity - #qty WHERE id=#id";
command.Parameters.AddWithValue("#id", tbItemid.Text);
command.Parameters.AddWithValue("#qty", Convert.ToInt32(tbQuantity.Text)));
command.ExecuteNonQuery();
Data();
DData();
int x = int.Parse(tbQuantity.Text);
using(SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id=#id"))
{
cmd1.Parameters.AddWithValue("#id", tbItemid.Text);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
model = modelRdr["model"].ToString();
price = int.Parse(modelRdr["Price"].ToString());
}
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (#id,#model,#price,#qty)";.
cmd.Parameters.AddWithValue("#id", tbItemid.Text);
cmd.Parameters.AddWithValue("#model", model);
cmd.Parameters.AddWithValue("#price", price);
cmd.Parameters.AddWithValue("#qty", tbQuantity.Text);
cmd.ExecuteNonQuery();
}
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
}

Search data in SQL

I want to search data in database and put it in datatable but it seem my sql command its not correct because it didnt return any data. please help. thanks in advance. below is my code please check.
protected DataTable SearchResident(String name, String ConnStr)
{
DataTable dt = new DataTable();
try
{
SqlCommand cmd;
using (SqlConnection con = new SqlConnection(ConnStr))
{
con.Open();
String SQL = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate, CivilStatus, " +
"Citizenship, MobileNo, Landline, PermanentAddress, Address FROM Residents " +
"WHERE FirstName LIKE '%name%' OR LastName LIKE '%name%'";
using (cmd = new SqlCommand(SQL, con))
{
using (SqlDataReader sdr = cmd.ExecuteReader())
{
dt.Load(sdr);
}
}
}
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
You wrote a request to the string SQL, but you do not use it in your code. Example SQL-query:
class SQLQuery
{
public static DataSet SQLGetData(string ConnectionString, string commandString)
{
DataSet DS = new DataSet();
DataTable DT = new DataTable("Table1");
DS.Tables.Add(DT);
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
try
{
connection.Open();
SqlCommand command = new SqlCommand(commandString, connection);
//command.CommandTimeout = 3000;
SqlDataReader read = command.ExecuteReader();
DS.Load(read, LoadOption.PreserveChanges, DS.Tables[0]);
}
catch (SqlException e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
finally
{
connection.Close();
}
}
return DS;
}
}
And get data:
private DataTable SearchData (string name)
{
DataTabel dt = new DataTable();
string connStr; // connection string
string command = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate,"+
"CivilStatus, Citizenship, MobileNo, Landline, PermanentAddress,"+
"Address FROM Residents WHERE FirstName LIKE '" + name +
"' OR LastName LIKE '" + name + "'";
dt = SQLQuery.SQLGetData(connStr, command).Tables[0];
return dt;
}
you need a sql command, and to add name as a parameter :-
using (SqlConnection con = new SqlConnection(ConnStr))
{
con.Open();
String SQL = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate, CivilStatus, " +
"Citizenship, MobileNo, Landline, PermanentAddress, Address FROM Residents " +
"WHERE FirstName LIKE '%#name%' OR LastName LIKE '%#name%'";
var cmd = new SqlCommand(SQL, connection);
cmd.Parameters.Add("#name", SqlDbType.Text);
cmd.Parameters["#name"].Value = name;
using (SqlDataReader sdr = cmd.ExecuteReader())
{
dt.Load(sdr);
}
}
You can use like this :
protected DataTable SearchResident(String name, String ConnStr)
{
try
{
String SQL = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate, CivilStatus, " +
"Citizenship, MobileNo, Landline, PermanentAddress, Address FROM Residents " +
"WHERE FirstName LIKE '%#name%' OR LastName LIKE '%#name%'";
using (SqlConnection sqlConn = new SqlConnection(ConnStr))
using (SqlCommand cmd = new SqlCommand(SQL, sqlConn))
{
cmd.Parameters.AddWithValue("#name", name);
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
catch (Exception ex)
{
throw ex;
}
}
One more suggestion, you are inviting SQL injection. Please use a parameterized stored procedure.

How do I go about adding records into TWO tables into Access Database?

I am a new member. Also, I am trying to add a record into 2 different tables (customerinfo & studentinfo). My code is below but it only records the textbox fields into the StudentInfo Table only. How should I go about it putting the record into 2 tables simultaneously?
Thanks
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/webBase.accdb");
mDB.Open();
Type csType = this.GetType();
//check to ensure that UserId keyed in is not being used by other Customers
OleDbCommand cmd;
OleDbCommand cmd1;
OleDbDataReader rdr;
OleDbDataReader rdr1;
string strSQLSelect = "SELECT sUserId FROM studentInfo ORDER BY sUserId";
string strSQLSelect1 = "SELECT cUserId FROM customerInfo ORDER BY cUserId";
cmd1 = new OleDbCommand(strSQLSelect1, mDB);
cmd = new OleDbCommand(strSQLSelect, mDB);
rdr = cmd.ExecuteReader();
rdr1 = cmd1.ExecuteReader();
this.txtPassword.Attributes.Add("value", this.txtPassword.Text);
// insert new record
string strSQLInsert = "INSERT INTO "
+ "studentInfo (sUserId,sPassword,sName,sAddress,sTel,sEmail,sLevel, sLevel2)"
+ "VALUES(#uid,#pw,#name,#addr,#em,#tel,#lvl,#lvl2)";
ClientScript.RegisterStartupScript(csType, "Successful!", scriptSuccessNewAccount);
cmd = new OleDbCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#uid", txtUserId.Text);
cmd.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#addr", txtAddress.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
cmd.Parameters.AddWithValue("#tel", txtTel.Text);
cmd.Parameters.AddWithValue("#lvl", DropDownList1.Text);
cmd.Parameters.AddWithValue("#lvl2", DropDownList2.Text);
string strSQLInsert1 = "INSERT INTO "
+ "customerInfo (cUserId,cPassword,cName,cAddress,cEmail,cTel,cCountry)"
+ "VALUES(#uid,#pw,#name,#addr,#em,#tel,#country)";
ClientScript.RegisterStartupScript(csType, "Successful!", scriptSuccessNewAccount);
cmd1 = new OleDbCommand(strSQLInsert1, mDB);
cmd1.Parameters.AddWithValue("#uid", txtUserId.Text);
cmd1.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd1.Parameters.AddWithValue("#name", txtName.Text);
cmd1.Parameters.AddWithValue("#addr", txtAddress.Text);
cmd1.Parameters.AddWithValue("#em", txtEmail.Text);
cmd1.Parameters.AddWithValue("#tel", txtTel.Text);
cmd1.Parameters.AddWithValue("#country", txtCountry.Text);
cmd.ExecuteNonQuery();
mDB.Close();
It looks like you're missing
cmd1.ExecuteNonQuery()
for the other table.

Save values between 'Steps' in Wizard ASP.NET

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.

Categories