I'm attempting to connect to a database and insert data into the pre-existing table. I'm able to connect to the database it seems but am having trouble getting the data to insert into the table. How do I insert
data into a database in visual studio?
I've already learned how to pass parameters and attempted that, but when I run the program I still receive exceptions. I've attached a screenshot of the error when I try and add a new record. I've looked up multiple different syntaxes for the insert statement, but not sure what I am doing wrong. Below I've included three screenshots one is the form itself, the error I receive, and at the bottom the table structure.
Insert Exception
Form
private void btnAccept_Click(object sender, EventArgs e)
{
if (IsValidData())
{
if (addProduct)
{
product = new Product();
this.PutProductData(product);
try
{
SqlConnection sqlConn = new SqlConnection("Data Source= (LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MMABooks.mdf;Integrated Security=True");
SqlCommand sqlComm = new SqlCommand();
sqlComm = sqlConn.CreateCommand();
sqlComm.CommandText = #"INSERT INTO Products (paramColum) VALUES
(#ProductCode, #Description,
#UnitPrice, #OnHandQuantity)";
sqlComm.Parameters.Add("#ProductCode", SqlDbType.VarChar);
sqlComm.Parameters.Add("#Description", SqlDbType.VarChar);
sqlComm.Parameters.Add("#UnitPrice", SqlDbType.VarChar);
sqlComm.Parameters.Add("#OnHandQuantity", SqlDbType.VarChar);
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
// Add code here to call the AddProduct method of the ProductDB class.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
frmAddModifyProduct addProductForm = new
frmAddModifyProduct();
addProductForm.addProduct = true;
DialogResult result = addProductForm.ShowDialog();
if (result == DialogResult.OK)
{
product = addProductForm.product;
txtCode.Text = product.Code;
this.DisplayProduct();
}
}
It should enter a record into the Products table. If I get it down for the insert statement, I'll figure out the retrieve, update, and delete.
TableStructure
You need to add the parameter values, something like:
command.Parameters.Add("#LastName", SqlDbType.VarChar, 30).Value = "Smith";
command.Parameters.Add("#GenderCode", SqlDbType.Char, 1).Value = "M";.
Original answer below, but as pointed in comments below, please avoid it, reasons
cmd.Parameters.AddWithValue("#ProductCode", product.Code);
cmd.Parameters.AddWithValue("#Description", product.Description);
In the current code you have just setup the parameters but not passed the value.
EDIT: Based on #MaxSzczurek comments above
Your INSERT INTO columns don't match your VALUES clause.
INSERT INTO Products (paramColumn) should be changed to:
INSERT INTO Products(ProductCode, Description, UnitPrice, OnHandQuantity)
Related
On my button click event I want to insert a row into a table. When I click the button, I get no exception and I also don't get my messagebox to show either. I have the messagebox as a way to check to see if the query had been executed.
When I step through it skips the MessageBox and doesn't throw an exception.
private void BtnSend_Click(object sender, EventArgs e)
{
string theDate = dateTimePicker1.Value.ToString("MM-dd-yyyy");
var select = "INSERT INTO Trinity3(Date, Device_S_N, Student_Last_Name, Student_First_Name, Student_Number, School, Grade, Damage)" +
"VALUES (#Date, #Serial, #LastName, #FirstName, #StudentNum, #School, #Grade, #Damage)" +
"COMMIT";
SqlConnection connection = new SqlConnection("Data Source=CPS1113020004; Initial Catalog=Coweta Public Schools; Integrated Security=True");
// Create a SqlCommand instance
SqlCommand command = new SqlCommand(select, connection);
// Add the parameter
command.CommandType = CommandType.Text;
command.CommandText = select;
command.Parameters.AddWithValue("#Date", theDate);
command.Parameters.AddWithValue("#Serial",txtSerial.Text);
command.Parameters.AddWithValue("#LastName",txtLastName.Text);
command.Parameters.AddWithValue("#FirstName",txtFirstName.Text);
command.Parameters.AddWithValue("#StudentNum", txtStudentNum.Text);
command.Parameters.AddWithValue("#School",txtSchool.Text);
command.Parameters.AddWithValue("#Grade", txtGrade.Text);
command.Parameters.AddWithValue("#Damage", txtDamage.Text);
// Execute the query
try
{
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Records inserted successfully");
}
catch
{
// Handle exception, show message to user...
}
finally
{
connection.Close();
}
this.Visible = false;
var searchForm = new SearchForm();
searchForm.ShowDialog();
}
You are throwing an exception but you are not seeing because there is nothing in your catch block.
Look up Try with Resources convention and always use it. This will automatically close your connection for you even if there is an exception.This is a must.
Add an exception to your catch block so you can see the error.
Your SQL string needs to have spaces after each section. When you are concatenating with "+" no extra space is created. So your query actually looks like this:
INSERT INTO Trinity3(Date, Device_S_N, Student_Last_Name, Student_First_Name, Student_Number, School, Grade, Damage)VALUES (#Date, #Serial, #LastName, #FirstName, #StudentNum, #School, #Grade, #Damage)COMMIT
Instead of writing your query in the application, you should create a stored procedure in the database that will contain all of the logic necessary to get the data. Then your application will simply call a one word stored proc instead of having a giant string representing your t-sql. ALSO you can actually test your stored proc and make sure it works without the application being involved.
I am building an application for a group of friends and myself to use for DnD sessions. Part of the program involves taking all of the values that are entered for our characters, items, etc and storing them to a database. I have the database built, and am pulling from the database into the program, however I am unable to return data to the database. I have the data coming into a dataset, and all of my edits are affecting the dataset, but I cannot get anything to affect the actual source database tables.
Below I have the button that I intend to use to update items in the characters' packs. I have both dataadapter, and tableadapter methods included that I have tried.
private void btnaddpack_Click(object sender, EventArgs e)
{
if (txtbxpack.Text != "")
{
/*connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Pack SET Item = (#ItemName)" + "WHERE Id = '" + this.lstpack.SelectedValue + "';";
cmd.ExecuteNonQuery();
cmd.Clone();*/
string packitem = txtbxpack.Text; //will take item from an textbox
this.packTableAdapter.Insert(packitem);
this.Validate();
this.packBindingSource.EndEdit();
this.packTableAdapter.Update(this.dnD_MachineDataSet.Pack);
}
PopulatePack();
Here is my populate code in case someone needs that:
private void PopulatePack()
{
using (connection = new SqlConnection(connectionString)) //this is all about opening the connection to the sqldatabase, normally it would need to be closed, but this uses idisposable, so it will close itself
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Pack", connection))
{
DataTable packtable = new DataTable();
adapter.Fill(packtable);
lstpack.DataSource = packtable;
lstpack.DisplayMember = "Item";
lstpack.ValueMember = "Id";
}
}
As mentioned above, all of the changes are appearing whenever I re-populate the listboxes that draw upon the dataset, hence why this is an issue of trying to get that data back into the source database. I will make the obligatory "I'm relatively new to using databases" statement as it will do no good to pretend that I am an expert.
Thanks.
In the commented code, you would need to do the following:
assign the connection object to the SqlCommand object's Connection
property
pass the item name to your #ItemName parameter
assign a parameter value to the 'Id' column in the WHERE clause
remove, 'cmd.Clone();', and replace with, 'connection.Close();'
Here is what the code should look like:
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "UPDATE Pack SET Item = (#ItemName) WHERE Id = #ID;";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ItemName", txtbxpack.Text);
cmd.Parameters.AddWithValue("#ID", this.lstpack.SelectedValue);
cmd.ExecuteNonQuery();
connection.Close();
This code, upon the sql commands succession should take me to a page and upon failure would show me the error page. Whenever i insert the values through the form it takes me to the error page. Somehow my items are not being inserted. Help would be appreciated
public partial class StudentManage : System.Web.UI.Page
{
protected void Add_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString);
con.Open();
// here added "#" to write continuous strind in new line
SqlCommand cmd = new SqlCommand(#"INSERT INTO ManageStudents(StudentName, StudentEmail, StudentAddress, StudentCity) VALUES(#name, #email, #address, #city)",con);
cmd.Parameters.AddWithValue("#name", txtStudentName.Text);
cmd.Parameters.AddWithValue("#email", txtStudentEmail.Text);
cmd.Parameters.AddWithValue("#address", txtStudentAddress.Text);
cmd.Parameters.AddWithValue("#city", txtStudentCity.Text);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da1.Fill(dt2);
if (dt2.Rows.Count > 0)
{
Response.Write("Table Updated");
Response.Redirect("StudentManage.aspx");
}
else
{
Response.Redirect("Error.aspx");
//ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
}
To execute INSERT, UPDATE, or DELETE statements you need to use the ExecuteNonQuery() method instead of a DataTable.
var result = cmd.ExeuteNonQuery();
if(result > 0)
{
Response.Write("Table Updated");
Response.Redirect("StudentManage.aspx");
}
// ...
I suppose that it is a test project, because your code has three major problem,
You should create a using or try finally to close the connection
put the data with call to the UI in the same layer it is not a good
practice.
Last Fill only make a select, does not update the table. Use command.ExecuteNotQuery instead
I hope that this help you
This is my code for insert into a table. It doesn't get any error, but it doesn't insert to the table. I tried by using stored_procedure too but it doesn't insert too. I can't find what I'm doing wrong.
private void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = Properties.Settings.Default.bm_DatabaseConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
//cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "INSERT INTO [tbl_Buildings] (buildingName,buildingImage,buildingAddress,floorNo,apartsNo, buildingDesc) VALUES (#builName,#builImage,#builAddr,#floorNo,#apartsNo,#builDesc)";//"prc_AddNewBuilding";
cmd.Parameters.Add("#builName", txtBuildingName.Text);
cmd.Parameters.Add("#builAddr", txtAddress.Text);
cmd.Parameters.Add("#builImage", "Undefined");
cmd.Parameters.Add("#floorNo", (int)numFloorNo.Value);
cmd.Parameters.Add("#apartsNo", (int)numApartsNo.Value);
cmd.Parameters.Add("#builDesc", txtBuilDesc.Text);
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("New building has been added successfully");
this.Close();
}
catch (SqlException sqlex)
{
MessageBox.Show(sqlex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I am using VS2012. What could I be doing wrong?
Try using:
Database.Command.Parameters.AddWithValue("#variableName", variable)
The only thing I could imagine why your values won't be inserted into your DB is a SQL Exception. Maybe you're missing some quotes?
Alternatiely use the complete "Add" Statement like this:
Database.Command.Parameters.Add(item, System.Data.SqlDbType.VarChar).Direction = ParameterDirection.Input
Item in this case is your variable containing the data you want to store
EDIT
My original answer assumed SQL Server was the database. As it turns out, the OP is using MS Access. Seems, based on other evidence, the file path for the .mdb file was the culprit, not the C# or SQL.
My original answer:
Using the connection string...
Server=myhost;Database=testdatatbase;Trusted_Connection=True;
the code you provided above works. I went to SQL Enterprise Manager, created a table named dbo.tbl_Buildings with the following attributes...
buildingName = nvarchar(50)
buildingImage = nvarchar(50)
buildingAddress = nvarchar(50)
floorNo = int
apartsNo = int
buildingDesc = nvarchar(50)
I then passed in dummy values, then ran the following query...
select * from testdatatbase.dbo.tbl_Buildings
and it shows the record....
-- seems to work for me...
(Maybe check your datatypes - make sure your table types match your types in the code)
I have read TONS of tutorials, articles and whatever regarding my issue and honestly, due to my lack of experience I can't twist my fingers around this one so I hope some of you guys can help me out :)
I am working on a project (simply to learn how to program so it's probably very basic), but I have this "News" page where I can update and delete data using a GridView.
Now I would like to INSERT something into my database using 3 textboxes and 1 submit button.
I have 3 rows that has to be inserted:
Headline
Date
Content/the news itself.
Which are stored under NyhedTB from the connectionstring: BoligStjernenConnectionString
My query looks like this:
INSERT INTO [NyhedTB] ([NyhedDato], [NyhedTitel], [NyhedTekst])
VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)
I read on the internet that this code should do the magic for me (I will have to insert my own values ofc.):
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
"#Id, #Name, #Address)", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Amal Hashim");
cmd.Parameters.AddWithValue("#Address", "Bangalore");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
I looked at this code and thought it should be easy enough but really, I can't figure it out.
Here is some advice to get you going, learning programming is a lot of
trial and error.
Start off basic, litrally put three textboxes on a form/page and a
button.
Double click the button to go the code-behind and view the buttons
click event.
Paste in the body of code included with your question (everything in the try-catch).
Put a break-point on the Public Void Button_Click line of code and press F11 to
step through the code.
"one thing is having the code-behind working but how to make the buttons and textboxes working is still a misery"*
Put the textbox as the value rather than your hardcoded values:
cmd.Parameters.AddWithValue("#Address", textBox1.Text);
You also should not insert the Id value, instead modify the EmployeeDetails table and set the ID column to in the properties set Identity Specification (IS Identity) = True. Then right click the ID column and set Primary Key.
Post any error messages you encounter here and when you do get get it working, an additional exercise (that will be very valuable for you) would use a database stored procedure rather than ad-hoc SQL, to safe-guard against sql-injection attacks.
I'm assuming you have SQL Server installed and have a 'employee' database with a table called EmployeeDetails.
protected void GvManualShows_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//label lbl = (label)e.Row.FindControl("lblHidden");
if (e.Row.Cells[14].Text == "Y")
{
// CheckBox cb = (CheckBox)e.Row.FindControl("chk");
CheckBox chk = (CheckBox)e.Row.Cells[0].FindControl("chkBox");
chk.Checked = true;
}
}
}
It's fairly simple. You just have to modify the connection string, the query and its parameters:
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString =
"server=SQLServer;" + // SQLServer is your SQL server machine
"initial catalog=employee;" + // employee is your database
"user id=sa;" + // sa is the login to connect the database
"password=sa123"; // sa123 is the password of the login
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO [NyhedTB] ([NyhedDato], [NyhedTitel], [NyhedTekst]) " +
"VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)", conn))
{
cmd.Parameters.AddWithValue("#NyhedDato", textBoxDate.Text);
cmd.Parameters.AddWithValue("#NyhedTitel", textBoxTitle.Text);
cmd.Parameters.AddWithValue("#NyhedTekst", textBoxBody.Text);
int rows = cmd.ExecuteNonQuery(); // Inserted rows number
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
I made changed example code with your requirements and added comments, hope it would be a bit clearer for you to understand whats going on:
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=MyDatabaseName;" + //here you write database name where your NyhedTB table is
"user id=sa;" + //user name to connect to database
"password=sa123"; //password
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("INSERT INTO NyhedTB (NyhedDato, NyhedTitel, NyhedTekst) VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)", conn))
{
//all "things" in your sql command what beggins with #
//means that it is parameter and you need to pass values for these parameters:
//For #NyhedDato parameter you set text from your textbox
cmd.Parameters.AddWithValue("#NyhedDato", txtDate.Text);
//For #NyhedTitel parameter you set text from title textbox
cmd.Parameters.AddWithValue("#NyhedTitel", txtTitle.Text);
//For #NyhedTekst parameter you set text from content textbox
cmd.Parameters.AddWithValue("#NyhedTekst", txtContent.Text);
//Execute insert command and get how many records was efected, in this case it should be rows = 1 because you inserting just one record
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
P.s. code not tested. And when you say
I have 3 rows that has to be inserted:
Headline
Date
Content/the news itself.
actually you mean you want to insert record with fields