I'm trying to enter the id, first and last name into a table and then according to a combo box input I create another record right after that saves id of the student and the id of the Team which was chosen bu the combo box. Here is my code. everything runs well the only problem is that after that the record in the TeamPlayers table is not added. Please anyone ?!?
try
{
string team = null;
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("INSERT INTO Students(BaruchID, FirstName, LastName) VALUES(#id, #first, #last)", conn);
conn.Open();
comm.Parameters.AddWithValue("#id", tbBaruchID.Text);
comm.Parameters.AddWithValue("#id", FirstName.Text);
comm.Parameters.AddWithValue("#id", LastName.Text);
comm.ExecuteNonQuery();
conn.Close();
}
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Junglists/Documents/Visual Studio 2013/Projects/SACC_Baruch/SACC_Baruch/Teams.accdb;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("SELECT TeamNum FROM Teams WHERE TeamName='" + cbTeam.Text +"'", conn);
conn.Open();
OleDbDataReader dr = comm.ExecuteReader(CommandBehavior.SingleResult);
if (dr.Read())
{
team = dr["TeamNum"].ToString();
}
conn.Close();
}
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Junglists/Documents/Visual Studio 2013/Projects/SACC_Baruch/SACC_Baruch/Teams.accdb;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("INSERT INTO TeamPlayers(ID, BaruchID, TeamID) VALUES(#i, #id, #teamid)", conn);
conn.Open();
comm.Parameters.AddWithValue("#i", 1);
comm.Parameters.AddWithValue("#id", tbBaruchID.Text);
comm.Parameters.AddWithValue("#teamid", int.Parse(team));
conn.Close();
}
MessageBox.Show("Student Added for team"+ cbTeam.Text);
}
The parameter names in the first INSERT statement are not used when adding the parameter values. All the comm.Parameters.AddWithValue("#id", .....); lines use #id. Therefore, the actual id value is never saved to table student.
The second INSERT has always uses 1 as the value of 'id'. Assuming that 'id' is a primary key, it can only contain unique values. Make the 'id' field an IDENTITY field and then remove it from the INSERT statement. Each time a record is then added to the table it will be given the next number in an ever incrementing sequence.
Corrected Code: http://dotnetfiddle.net/Dr9842
Related
I'm trying to allow values to be changed within the datagridview table
OnCellendEdit event
using (SqlConnection conn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "UPDATE employee SET #selected = '#upd' WHERE id = #id";
cmd.Parameters.AddWithValue("#selected", dataGridView1.CurrentCell.OwningColumn.HeaderText);
cmd.Parameters.AddWithValue("#upd", dataGridView1.CurrentCell.Value.ToString());
cmd.Parameters.AddWithValue("#id", dataGridView1.CurrentRow.Cells[0].Value);
cmd.ExecuteNonQuery();
conn.Close();
}
}
this.employeeTableAdapter.Fill(this.testDataSet.employee);
Using the above to build the update query but it just resets upon pressing enter
#selected retrieves column name
#upd retrieves entered value
#id retrieves id number
So the final query should be
UPDATE employees
SET firstName = 'john'
WHERE id = 1
but upon execution no changes are committed and the value resets to original.
Looked at values and they are being retrieved correctly.
I have tables Member and Office which use an auto-increment primary key, Member_Id and Office_Id. I am inserting data into the tables but would like to have primary key of the Member table inserted on the Office Table as a foreign key, so that a member is assigned to an office record. Please assist. Below is a snippet of my code for inserting the records but I just do not know how to link the two tables.
protected void capture()
{
string CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
conn.Open();
SqlCommand com = new SqlCommand();
SqlParameter myParam = new SqlParameter();
com.CommandText = "INSERT into Member(Appointment_Number, Initials, Surname, Designation) VALUES (#Appointment_Number, #Initials, #Surname, #Designation)";
com.Parameters.AddWithValue("#Appointment_Number", txtAppointmentNumber.Text);
com.Parameters.AddWithValue("#Initials", txtInitials.Text);
com.Parameters.AddWithValue("#Surname", txtSurname.Text);
com.Parameters.AddWithValue("#Designation", ddlDesignation.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
//Insert records into the office table
com.CommandText = "INSERT into Offices(Office_Number, Status, Building, Branch, Floor) VALUES (#Office_Number, #Status, #Building, #Branch, #Floor)";
com.Parameters.AddWithValue("#Office_Number", txtOffNo.Text);
com.Parameters.AddWithValue("#Status", ddlOStatus.Text);
com.Parameters.AddWithValue("#Building", ddlBuilding.Text);
com.Parameters.AddWithValue("#Branch", ddlBranch.Text);
com.Parameters.AddWithValue("#Floor", ddlFloors.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
if (IsPostBack)
{
Response.Redirect("~/Pages/MemberDetails.aspx");
}
}
}
I think, you want to set a relation between offices and members 1 to n.
So to do that, lets add officeid field in members table, insert the office record before the member and change the code like this;
protected void capture()
{
string CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
conn.Open();
SqlCommand com = new SqlCommand();
SqlParameter myParam = new SqlParameter();
//Insert records into the office table
com.CommandText = "INSERT into Offices(Office_Number, Status, Building, Branch, Floor) VALUES (#Office_Number, #Status, #Building, #Branch, #Floor)";
com.Parameters.AddWithValue("#Office_Number", txtOffNo.Text);
com.Parameters.AddWithValue("#Status", ddlOStatus.Text);
com.Parameters.AddWithValue("#Building", ddlBuilding.Text);
com.Parameters.AddWithValue("#Branch", ddlBranch.Text);
com.Parameters.AddWithValue("#Floor", ddlFloors.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
com.CommandText = "select max(Office_Id) from Offices";
int officeid = Convert.ToInt32(com.ExecuteScalar());
com.CommandText = "INSERT into Member(officeid,Appointment_Number, Initials, Surname, Designation) VALUES (#officeid,#Appointment_Number, #Initials, #Surname, #Designation)";
com.Parameters.AddWithValue("#officeid", officeid);
com.Parameters.AddWithValue("#Appointment_Number", txtAppointmentNumber.Text);
com.Parameters.AddWithValue("#Initials", txtInitials.Text);
com.Parameters.AddWithValue("#Surname", txtSurname.Text);
com.Parameters.AddWithValue("#Designation", ddlDesignation.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
if (IsPostBack)
{
Response.Redirect("~/Pages/MemberDetails.aspx");
}
}
}
Once you've inserted into your first table, using the same connection, SELECT SCOPE_IDENTITY() to get the auto-assigned identity value just created. You can then use that to insert into the second table.
Using SCOPE_IDENTITY() will ensure that you always get the id that you just created. If your system is being used by multiple users concurrently, you don't want to risk picking up the identity value created by another user that happened to be inserting data at the same time as you.
e.g. after your first insert:
com.CommandText = "SELECT SCOPE_IDENTITY()";
int my_id_just_created = Convert.ToInt32(com.ExecuteScalar());
The simplest way to do this is probably to insert your Office table first, get the scope identity, and put that in the FK of you member insert. To get the scope identity just use this syntax :
INSERT INTO YourTable
(val1, val2, val3 ...)
VALUES(#val1, #val2, #val3...);
SELECT SCOPE_IDENTITY();
Then you use com.ExecuteScalar() that will return you an Int with the PK of the Office table that you can use as the FK of the Member table.
I have an Asp.net application on my page the user requests for a user to be removed. This then populates my 'Admin_TaskList' db.
An administrator then goes in the secure area of the site and enters the users name and clicks a button. Upon the confirmation, the user is then deleted from my 'Users' db (already got this working) but I want my 'Admin_TaskList' db 'Status' column to change from 'To Do' to 'Completed'.
As I sad I have the delete bit working but I am struggling updating my other table.
Snippet of code I have tried
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
Full code
public void btnRemoveConfirmYes_Click(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = #Name", conn);
cmd1.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd1 = cmd1.ExecuteReader();
conn.Close();
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
txtRemoveUser.Text = "";
Response.Redirect("/AdminSide/TaskList.aspx");
}
Instead of using a SqlDataReader to update a value use SqlCommand.ExecuteNonQuery:
int updated = cmd2.ExecuteNonQuery();
Remember that you need to use ExecuteNonQuery on commands that modify your data like Delete, Insert or Update.
MSDN:
You can use the ExecuteNonQuery to perform catalog operations (for
example, querying the structure of a database or creating database
objects such as tables), or to change the data in a database without
using a DataSet by executing UPDATE, INSERT, or DELETE statements.
The complete method:
int deleted, updated;
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
using (var conn = new SqlConnection(connection))
{
conn.Open();
string delSql = "DELETE FROM Users WHERE Name = #Name";
using (var cmd = new SqlCommand(delSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
deleted = cmd.ExecuteNonQuery();
}
string updSql = #"UPDATE Admin_TaskList
SET Status = 'Complete'
WHERE Description = 'Remove User'
AND Name = #Name";
using (var cmd = new SqlCommand(updSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
updated = cmd.ExecuteNonQuery();
}
}
I have a textbox form that students fill out about their general information such as first and last name, city, state, etc. Sometimes a student can't remember if they filled out the form before and it will lead to duplicate entries in the ms-access database. Ideally I would like the code to first search the ms-access database for a matching first name AND last name on the same record before insertion. If there's a record that matches on both the entered first and last name fields then a script would run and say something like, "A matching record already exists, would you like to continue?" Clicking "Yes" would enter the record into a new row, clicking "Cancel" would not enter it into the database at all.
I started this code but I'm not sure if it's the right direction, any guidance would be appreciated, thanks.
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
(This is where I am stuck)
}
}
Below is the current code for the submit button.
protected void btnSubmit_Click(object sender, EventArgs e)
{
{
//Preforms insert statement on click to allow additions to the database
DateTime CurrentDate;
CurrentDate = DateTime.Now;
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\sites\schoolinfo\students_dev\App_Data\Studentdb.mdb";
string cmdstr = "INSERT into StudentList(FName, LName, BDay, Gender, School, Grade, Address, APT, City, State, Zip, Email, Phone, CellPhone, ParentFName, ParentLName, ParentEmail) values(#FName, #LName, #BDay, #Gender, #School, #Grade, #Address, #APT, #City, #State, #Zip, #Email, #Phone, #CellPhone, #ParentFName, #ParentLName, #ParentEmail)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
{
con.Open();
}
//The following fields are added from the student information to the corresponding database fields
com.Parameters.AddWithValue("#FName", txtFirstName.Text);
com.Parameters.AddWithValue("#LName", txtLastName.Text);
com.Parameters.AddWithValue("#BDay", txtBirthDate.Text);
com.Parameters.AddWithValue("#Gender", ddlGender.Text);
com.Parameters.AddWithValue("#School", txtSchool.Text);
com.Parameters.AddWithValue("#Grade", txtGrade.Text);
//The following fields are added from the contact information to the corresponding database fields
com.Parameters.AddWithValue("#Address", txtAddress.Text);
com.Parameters.AddWithValue("#APT", txtApt.Text);
com.Parameters.AddWithValue("#City", txtCity.Text);
com.Parameters.AddWithValue("#State", ddlState.Text);
com.Parameters.AddWithValue("#Zip", txtZip.Text);
com.Parameters.AddWithValue("#Email", txtEmail.Text);
com.Parameters.AddWithValue("#Phone", txtPhone.Text);
com.Parameters.AddWithValue("#CellPhone", txtCellPhone.Text);
com.Parameters.AddWithValue("#ParentFName", txtParentFName.Text);
com.Parameters.AddWithValue("#ParentLName", txtParentLName.Text);
com.Parameters.AddWithValue("#ParentEmail", txtParentEmail.Text);
com.ExecuteNonQuery();
con.Close();
//End database connection
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Student has been successfully added!')", true);
}
}
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
// Add your #Fname and #LName parameters here
com.Parameters.AddWithValue("#FName", firstName);
com.Parameters.AddWithValue("#LName", lastName);
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
myReader.Read();
int count = myReader.GetInt32(0);
// return count > 0 or whatever to indicate that it exists
}
}
couple of things:
you can set in your table the first name and last name as 1 primary key (yes it possible in ms-access). this way you will NEVER get any duplicate records
count(*) is not the best practice with databases.. but since you are dealing with ms-access
using (OleDbDataReader myReader = com.ExecuteReader())
{
// reads the first and only column count(*) and convert it to a number
if (Convert.ToInt16(myReader[0]) > 0)
{
// an entry already exists
}
}
You should use ExecuteScalar when the return value of your query is only a single row with a single column. Of course the OleDbCommand that has parameters placeholders in its command text needs to have also a corresponding Parameters collection
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
con.Open();
com.Parameters.AddWithValue("#FName", txtFirstName.Text);
com.Parameters.AddWithValue("#LName", txtLastName.Text);
int count = Convert.ToInt32(com.ExecuteScalar());
if(count == 0)
{
... record doesn't exist
}
else
{
... you have got count records
}
}
However let me say that this logic is rather weak. What happen if two students have the same First and Last name? What happen if someone mistype the name?. I think that you should require something more unique. Like a SSN or another ID provided by your school. (A Student Number or something alike)
if (txtYear.Text != "")
{
cmd = new SqlCommand("Select YearName from Year where YearName='" + txtYear.Text + "'", ConnOpen());
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if (i > 0)
{
MessageBox.Show("Duplicate Values are not valid!!!");
}
else
{
if (Classes.ClassDatabaseConnection.UserMessage("Are you srue you want to Add this Year!!!", "Confirm Updation") == true)
{
string insert = "insert into Year(YearName) values('" + txtYear.Text + "')";
int result = sqlrep.ExecuteNonQuery(insert);
if (result > 0)
{
System.Windows.Forms.MessageBox.Show("Year Added Successfully.", "Information", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
}
}
dataLoad();
}
}
I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?
I tried this
insert into student(id, name) values(,name)
but it is not insert to my table.
This is my code :
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.
You better use parameters when you insert data.
try
{
string sql = "insert into student(name) values (#name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
You don't need to mention the ID in first part.
insert into student(name) values('name')
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows:
commands executed in command shell of mssql like:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
Try the following query,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. If it is not working, the u have to check the identity column in the db.
use the key word "identity" to auto increment the id column
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query