Using sql tableadapters to update database C# - c#

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();

Related

Connecting to a database and inserting data into a table

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)

inserting data into SQL DB from C# ASP.NET

I am trying to insert values into my SQL database, the query works on the SQL side but when it comes to implement it from C# ASP.NET, it will not insert anything into the SQL database. The code is as follows:
public partial class About : Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into sanctuary(SName) values('test')", con);
cmd = new SqlCommand("insert into species(Name) values('test1')", con);
cmd = new SqlCommand("insert into breed(SpeciesID, BreedName, FoodCost, HousingCost) SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Your help will be much appreciated!
If you want to execute three commands together you merge the sql of the three commands in a single string separating them with a semicolon (See Batch of Sql Commands)
string cmdText = #"insert into sanctuary(SName) values('test');
insert into species(Name) values('test1');
insert into breed(SpeciesID, BreedName, FoodCost, HousingCost)
SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species";
SqlCommand cmd = new SqlCommand(cmdText, con);
cmd.ExecuteNonQuery();
The first problem in your code is that you need to execute each single command and not just the last one. Finally, if you don't see even the insert for the last command could be because your table species is empty and thus the final command has nothing to insert.
Last note, the point underlined by Zohar Peled about NOT keeping a global connection object around, is very important, follow the advice.
You only execute the last command, so there is nothing in species. Since there is nothing in species, the select returns no results so nothing gets inserted into breed.
Also, keeping an SqlConnection object on the page level is not a good idea. SQL connections should be opened right before executing queries and disposed immediately after.
A better code would look like this:
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using(var com = new SqlCommand("insert into sanctuary(SName) values('test');insert into species(Name) values('test1');insert into breed(SpeciesID, BreedName, FoodCost, HousingCost) SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species", con)
{
con.Open();
com.ExecuteNonQuery();
}
}
You can, of course, execute each SQL statement separately (though in this case it's not the best course of action since it means 3 round trips to the database instead of just one):
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using(var com = new SqlCommand("insert into sanctuary(SName) values('test');", con)
{
con.Open();
com.ExecuteNonQuery();
com.CommandText = "insert into species(Name) values('test1');";
com.ExecuteNonQuery();
com.CommandText = "insert into breed(SpeciesID, BreedName, FoodCost, HousingCost) SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species;";
com.ExecuteNonQuery();
}
}

Couldn't delete all rows of a table from Microsoft Access via OleDB in C#

I had a method in which I intend for it to delete all data from the table. However, even as it is called, the deletion didn't happen at all.
Here below is the method.
Let's assume that the data is already loaded in the table.
Table "CartListClone" has 5 columns (excluding the ID). The table as you can see in the connection string derives from Access.
public void deleteEverything() {
OleDbConnection connect =
new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=POSDB.accdb;
Persist Security Info = False");
connect.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "DELETE * FROM CartListClone";
}
As of now, I feel that the problem is rooted at the method.
Is there something that I did wrong here?
Much appreciated for any help.
UPDATE: Following sstan's suggestion, here below is the rewritten method.
public void deleteEverything() {
OleDbConnection connect =
new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=POSDB.accdb;
Persist Security Info = False");
connect.Open();
OleDbCommand command = new OleDbCommand("DELETE * FROM CartListClone");
command.Connection = connect;
command.ExecuteNonQuery();
}
You're never executing the command object. You're missing this line at the end:
command.ExecuteNonQuery();

How to get the DataSource name in dropdownlist control in C# Winforms

Hi I am developing an application to retrieve data from one system to another remote system.
To do this I am firstly setting the connection string of the application by below screen.
When I chose the SQL Server from first dropdownlist I need that the available DataSource name or database instance name like sa or anything by witch the database installed, should be come in second dropdownlist and again when I select DataSource available, database name should be prompt in 3rd dropdownlist.
I don't have any idea about this how can I do this. Currently I am doing this manually but it's time consuming and error prone.
How can we resolve it and also for MySql too.
You can get the database instance name using following code
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();
foreach (System.Data.DataRow row in table.Rows)
{
cboServerName.Items.Add(row["ServerName"]);
}
and for the databases in that server you can use this code
SqlConnection SqlCon = new SqlConnection("server=" + cboServerName.SelectedItem.ToString() + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text);
try
{
SqlCon.Open();
//if connection was successful,fetch the list of databases available in that server
SqlCommand SqlCom = new SqlCommand();
SqlCom.Connection = SqlCon;
SqlCom.CommandType = CommandType.StoredProcedure;
SqlCom.CommandText = "sp_databases"; //sp_databases procedure used to fetch list of available databases
SqlDataReader SqlDR;
SqlDR = SqlCom.ExecuteReader();
while (SqlDR.Read())
{
cboDatabase.Items.Add(SqlDR.GetString(0));
}
}
catch
{
MessageBox.Show("Connection Failed...Please check username and password","Error");
}

How to add/edit/retrieve data using Local Database file in Microsoft Visual Studio 2012

I want to get into developing applications that use databases. I am fairly experienced (as an amateur) at web based database utilization (mysql, pdo, mssql with php and old style asp) so my SQL knowledge is fairly good.
Things I have done already..
Create forms application
Add four text boxes (first name, last name, email, phone)
Added a datagrid control
Created a database connection using 'Microsoft SQL Server Database File (SqlClient)'
Created a table with fields corresponding to the four text boxes.
What I want to be able to do now is, when a button is clicked, the contents of the four edit boxes are inserted using SQL. I don't want to use any 'wrapper' code that hides the SQL from me. I want to use my experience with SQL as much as possible.
So I guess what I am asking is how do I now write the necessary code to run an SQL query to insert that data. I don't need to know the SQL code obviously, just the c# code to use the 'local database file' connection to run the SQL query.
An aside question might be - is there a better/simpler way of doing this than using the 'Microsoft SQL Server Database File' connection type (I have used it because it looks like it's a way to do it without having to set up an entire sql server)
The below is inserting data using parameters which I believe is a better approach:
var insertSQL = "INSERT INTO yourTable (firstName, lastName, email, phone) VALUES (firstName, lastName, email, phone)";
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(insertSQL, cn))
{
cn.Open();
cmd.Parameters.Add("firstName", SqlDbType.NVarChar);
cmd.Parameters.Add("lastName", SqlDbType.NVarChar);
cmd.Parameters.Add("email", SqlDbType.NVarChar);
cmd.Parameters.Add("phone", SqlDbType.NVarChar);
cmd.Parameters["firstName"].Value = firstName;
cmd.Parameters["lastName"].Value = lastName;
cmd.Parameters["email"].Value = email;
cmd.Parameters["phone"].Value = phone;
cmd.ExecuteNonQuery();
}
This is selecting data from database and populating datagridview:
var dt = new DataTable();
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"
using (var cn = new SqlCeConnection(connectionString )
using (var cmd = new SqlCeCommand("Select * From yourTable", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
//resize the DataGridView columns to fit the newly loaded content.
yourDataGridView.AutoSize = true; yourDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
//bind the data to the grid
yourDataGridView.DataSource = dt;
}
}
This first example is an over view based upon how I think it will be easier to understand but this is not a recommended approach due to vulnerability to SQL injection (a better approach further down). However, I feel it is easier to understand.
private void InsertToSql(string wordToInsert)
{
string connectionString = Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=myDomain\myUsername;Password=myPassword;
string queryString = "INSERT INTO table_name (column1) VALUES (" + wordToInsert + ")"; //update as you feel fit of course for insert/update etc
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open()
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
connection.Close();
}
}
I would also suggest wrapping it in a try/catch block to ensure the connection closes if it errors.
I am not able to test this but I think it is OK!
Again don't do the above in live as it allows SQL injection - use parameters instead. However, it may be argued it is easier to do the above if you come from PHP background (just to get comfortable).
This uses parameters:
public void Insert(string customerName)
{
try
{
string connectionString = Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=myDomain\myUsername;Password=myPassword;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
connection.Open() SqlCommand command = new SqlCommand( "INSERT INTO Customers (CustomerName" + "VALUES (#Name)", connection);
command.Parameters.Add("#Name", SqlDbType.NChar, 50, " + customerName +");
command.ExecuteNonQuery();
connection.Close();
}
catch()
{
//Logic in here
}
finally()
{
if(con.State == ConnectionState.Open)
{
connection.Close();
}
}
}
And then you just change the SQL string to select or add!

Categories