Why it doesn't insert into sql table? - c#

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)

Related

sqlite insert with c#

i am testing my sqlite local server with c#, I have the connection and query setup without problem. I tried to copy the query to sqlite and it runs without problem. However, when I run it in my program, nothing insert into the db. Wondering what the problem is.
I have set the db build action to Content, and the copy to output directory options to copy if newer
private void insertIntoDB(string query)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=.\\VHTDatabase.db"))
{
using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
{
conn.Open();
Console.WriteLine(query);
cmd.CommandText = query;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
Try a full path to your database in your Connectionstring
Then maybe try to add the CommandText before you open the Connection.
i mean:
cmd.CommandText = query;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Does your database give you informations with SELECT?
Maybe you need to reconfigure the User of the Database and give him rights to write, change and delete.
If nothing helps, then you can check, if it gives you an error.
try
{
cmd.CommandText = query;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex);
}

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)

C# delete query not working

I have written this query in c# , query syntax is OK, query is also receiving parameter values as I have checked using breakpoints and also same query is working in SQL server management studio, but in visual studio it does not gives any error but also does not delete item from table.
private void deleteItem(int itemId, int saleId)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand deleteItem = new SqlCommand(
"Delete FROM items_in_sales WHERE sale_id=#sale_id AND item_id=#item_id",
conn);
deleteItem.Parameters.AddWithValue("#sale_id", itemId);
deleteItem.Parameters.AddWithValue("#item_id", saleId);
try
{
conn.Open();
deleteItem.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
please help.
Fix your parameters they are wrong way around
deleteItem.Parameters.AddWithValue("#sale_id", itemId);
deleteItem.Parameters.AddWithValue("#item_id", saleId);
should be
deleteItem.Parameters.AddWithValue("#sale_id", saleId);
deleteItem.Parameters.AddWithValue("#item_id", itemId);

Deleting and updating a database c#

I have problem with trying to figure out how to update and delete data inside a database using textboxes and a button.
My insert code is:
private void button4_Click(object sender, EventArgs e)
{
try
{
string query = "insert into Prodaja values (#Prodajalec,#Prodajalna,#Kupec,#Vozilo,#DatumNakupa)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#Prodajalec", textBoxProdajalec.Text);
command.Parameters.AddWithValue("#Prodajalna", textBoxProdajalna.Text);
command.Parameters.AddWithValue("#Kupec", textBoxKupec.Text);
command.Parameters.AddWithValue("#Vozilo", textBoxVozilo.Text);
command.Parameters.AddWithValue("#DatumNakupa", textBoxDatumNakupa.Text);
command.ExecuteNonQuery();
}
MessageBox.Show("Uspešno dodano");
this.prodajaTableAdapter.Fill(this.prodajaDataSet.Prodaja);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I tried a couple of different methods but they didnt really work out. Any help would be appreciated!
You seem to be mixing up the syntax of your insert vs update statement.
Insert statement:
insert into #table (col1,col2) values ('col1','col2')
Update statement
Update #table set col1 = 'col1', col2 = 'col2' where id = 'id'
EDIT: Delete Syntax
Delete from #table where id = 'id'

Storing the url in SQLSERVER 2005 using C# code(data sets)

I was trying to store the url on button click using the following code.There were no error but the required url is not sroeing in my column field (i used ntext data tpe for this).Please help me if there was some mistake in my code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Storetxt(String txt)
{
//connection to the database
string connection = "Data Source=.\\sqlexpress2005;Initial Catalog=PtsKuratlas;Integrated Security=True";
SqlConnection conn = new SqlConnection(connection);
//dataset object to store and manipulating data
DataSet myDataSet = new DataSet();
//data adapters to execute SQL
SqlDataAdapter myDataAdapter = new SqlDataAdapter("SELECT * FROM gti_analytics", conn);
myDataAdapter.Fill(myDataSet, "gti_analytics");
myDataAdapter.InsertCommand = new SqlCommand("INSERT INTO gti_analytics [links] VALUES [txt]");
}
protected void Button1_Click(object sender, EventArgs e)
{
String text = "http://google.com";
Storetxt(text);
}
}
The problem is that you're not actually executing the command against the database. You're defining the InsertCommand to use, but it's not being executed.
Based on that code, I don't see that you need to use a DataAdapter/DataSet anyway, just use an SqlCommand to do the insert, which is more lightweight. Something like this:
public void Storetxt(String txt)
{
//connection to the database
string connection = "Data Source=.\\sqlexpress2005;Initial Catalog=PtsKuratlas;Integrated Security=True";
SqlConnection conn = null;
SqlCommand cmd = null;
try
{
conn = new SqlConnection(connection);
cmd = new SqlCommand("INSERT INTO gti_analytics (Links) VALUES (#Link)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Link", txt);
conn.Open();
cmd.ExecuteNonQuery();
}
catch{//handle exceptions}
finally
{
if (cmd != null) cmd.Dispose();
if (conn != null)
{
if (conn.State == ConnectionState.Open) conn.Close();
conn.Dispose();
}
}
}
I'd also recommend not using ntext for this in your db. If you really need unicode support, use nvarchar which can go up to 4000 chars pre-sql 2005, or nvarchar(max) which can store as much as ntext from SQL 2005 onwards. If you don't need unicode support, use varchar instead (8000 chars pre-sql 2005, VARCHAR(MAX) from SQL 2005 onwards allows same as text)
shouldn't you be calling myDataAdapter.Update() at the end of the Storetxt method?
oh and i think using ntext for this is overkill.
Your txt method argument is not actually used anywhere in your method which is one reason why it's not being stored in the db.
You don't need a SqlDataAdapter or a DataSet for this operation, as AdaTheDev said. Follow the sample code, although it needs quite a bit of cleaning up.
Also, there's a protocol limit on the number of characters/bytes in the URL, nvarchar should have enough maximum capacity, so you should need neither nvarchar(max) nor (pre-SQL Server 2005) ntext.

Categories