SqlCommand INSERT query does not insert data into the database - c#

I am working on Visual Studio 2013.
In the below code the MessageBox.Show("Connected to database") is shown correctly, but the SQL query is not inserting data into the database table.
When I insert data manually then it inserts without any problems. But unfortunately the data fails to insert on the button_click command.
private void DataAdd_Load(object sender, EventArgs e)
{
try
{
conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=Pathname;Integrated Security=True;Connect Timeout=30");
conn.Open();
MessageBox.Show("Connected to database");
cmd = new SqlCommand("INSERT INTO datains (name, dob, gender, occupation, height, weight, relation, polexpo) values('abc', '22-Aug-2001', 'Male', 'qwe2', '23', '431', 'qw23e', 'asqwed');", conn);
}
catch (Exception e1)
{
MessageBox.Show("Connection failed");
}
}
What have I done wrong here or anything I have missed?

You have forgotten to execute the query:
cmd.ExecuteNonQuery();
It is also better to close the connection after the work is done:
conn.Close();

You have to run the ExecuteNonQuery() method of your cmd to make it work, but it's also advisable to wrap both connection and command into a using statement so that they will be disposed (the connection should be also explicitly closed)

Related

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

Cannot connect to database, getting System.InvalidOperationException

SqlConnection CON = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\VS_project\\WindowsFormsApplication1\\WindowsFormsApplication1\\myInfo.mdf;Integrated Security=True");
private void button4_Click(object sender, EventArgs e)
{
try
{
CON.Open();
SqlDataAdapter SDA = new SqlDataAdapter("INSERT INTO myInfo(Name,Address,Gender,LangKnownHindi)VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + Gender + "','" + LANG_Hin + "')", CON);
SDA.SelectCommand.ExecuteNonQuery();
CON.Close();
MessageBox.Show("Saved SuccessFully!!!!!");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
When I run this program I get:
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Data.dll. Additional information: The connection
was not closed. The connection's current state is open.
Having a SQL connection object exist in a shared scope is a famously bad idea. The connection should be created, used, and disposed within the scope of the operation using it. Otherwise other code may try to use the same connection object (or even this same code more than once), leaving it in an unknown state. Which is very likely what's happening here.
Create the connection in the method itself:
private void button4_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection CON = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\VS_project\\WindowsFormsApplication1\\WindowsFormsApplication1\\myInfo.mdf;Integrated Security=True"))
{
CON.Open();
SqlDataAdapter SDA = new SqlDataAdapter("INSERT INTO myInfo(Name,Address,Gender,LangKnownHindi)VALUES(#Name,#Address,#Gender,#LangKnownHindi)", CON);
SDA.SelectCommand.Parameters.AddWithValue("#Name", textBox1.Text);
SDA.SelectCommand.Parameters.AddWithValue("#Address", textBox2.Text);
SDA.SelectCommand.Parameters.AddWithValue("#Gender", Gender);
SDA.SelectCommand.Parameters.AddWithValue("#LangKnownHindi", LANG_Hin);
SDA.SelectCommand.ExecuteNonQuery();
CON.Close();
}
MessageBox.Show("Saved SuccessFully!!!!!");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Important: Also, note that I've done a couple of things here:
Wrapped the SqlConnection object in a using block. This basically creates a try/finally block which ensures that the connection is disposed after it's been used (by calling Dispose() in the finally block, so it only works on IDisposable objects). It's important to ensure disposal of I/O resources.
Replaced your SQL injection vulnerabilities with query parameters. You should always treat user input as parameter values, not as executable SQL code.
You should connect inside the method and handle disconnecting right. The easiest way to do so is by using using, which also disposes your connection handles in created in the background.
Also, in this case a SqlCommand fits the purpose better. Be aware of SQL injection too, since you concatenate user input to your SQL statement. Use parameters instead!
private void button4_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\VS_project\\WindowsFormsApplication1\\WindowsFormsApplication1\\myInfo.mdf;Integrated Security=True"))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO myInfo(Name,Address,Gender,LangKnownHindi)VALUES(#name, #address,#gender,#lang)", conn))
{
command.Parameters.AddWithValue("#name", textBox1.Text);
command.Parameters.AddWithValue("#address", textBox2.Text);
command.Parameters.AddWithValue("#gender", Gender);
command.Parameters.AddWithValue("#lang", LANG_Hin);
command.ExecuteNonQuery();
}
conn.Close();
MessageBox.Show("Saved SuccessFully!!!!!");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Are you sure dat u have used correct denoations of for 'myInfo' means caps nd small letters are in right order??..it is actually having an error in finding d database vid same name..use checkpoints in visual studio to check d execution of your program from starting..if you dont knw how to use checkpoints in visual studio den jst google d same..it vil show u step by step progress of ur code and den when u find error line of code just copy paste d line in sql server..if format of query in database and parameters given by you are correct den it vil execute in database or otherwise it vil fail to execute and vil show you error in sql statement

C# MS Access Database Connection System.Data.SqlClient.SqlException' occurred in System.Data.dll

I am not sure if this problem has anything to do with my code or simply the way that my database is set up. Any pointers would be awesome!
This is the error message that I get:
I have gone to "Modify Connection" and used the 'Test Connection' tool and that says that it connects fine but when the actual program runs nothing happens and I get the error.
Here is my code:
private void btnAddCustomer_Click(object sender, EventArgs e)
{
SqlConnection CustomerInfo = new SqlConnection("Data Source=C:\\Users\\Cory\\Desktop\\DeluxWrapsWindows\\DeluxWrapsWindows\\DeluxWraps_DB.mdb");
{
SqlCommand xp = new SqlCommand("Insert into CustomerInfo(LastName, FirstName, Email, PhoneNumber, Address, Instagram, CarMake, CarModel, AdditionalNotes) Values(#LastName, #Firstname, #Email, #PhoneNumber, #Address, #Instagram, #CarMake, #CarModel, #AdditionalNotes)", CustomerInfo);
xp.Parameters.AddWithValue("#LastName", txtLastName.Text);
xp.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
xp.Parameters.AddWithValue("#Email", txtEmail.Text);
xp.Parameters.AddWithValue("#PhoneNumber", txtPhoneNumber.Text);
xp.Parameters.AddWithValue("#Address", txtAddress.Text);
xp.Parameters.AddWithValue("#Instagram", txtInstagram.Text);
xp.Parameters.AddWithValue("#Carmake", txtCarMake.Text);
xp.Parameters.AddWithValue("#CarModel", txtCarModel.Text);
xp.Parameters.AddWithValue("#AdditionalNotes", txtAdditionalNotes.Text);
CustomerInfo.Open();
xp.ExecuteNonQuery();
CustomerInfo.Close();
}
}
You should try create the SqlCommand with:
SqlCommand xp = CustomerInfo.CreateCommand();
See this example:
https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlconnection.createcommand(v=vs.110).aspx
Update:
Try use OleDbConnection. See:
public DataSet GetDataSetFromAdapter(
DataSet dataSet, string connectionString, string queryString)
{
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbDataAdapter adapter =
new OleDbDataAdapter(queryString, connection);
// Set the parameters.
adapter.SelectCommand.Parameters.Add(
"#CategoryName", OleDbType.VarChar, 80).Value = "toasters";
adapter.SelectCommand.Parameters.Add(
"#SerialNum", OleDbType.Integer).Value = 239;
// Open the connection and fill the DataSet.
try
{
connection.Open();
adapter.Fill(dataSet);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
return dataSet;
}
See more details in: https://msdn.microsoft.com/en-us/library/System.Data.OleDb.OleDbParameterCollection(v=vs.110).aspx
It sounds like your trying to use a local database or auto-named database: Here is the syntax for your connection string:
Data Source=(LocalDB)\v11.0;
AttachDbFilename=Your local location here;
Integrated Security=True
Hope that helps.
The problem is you're using System.Data.Sql as the provider, when it should all be coming from System.Data.OleDb;
However, you can use <asp:SqlDataSource> in ASPX, to connect to an Access Database, but that is not the same thing as System.Data.Sql.

how to delete data in Sql Server 2012 using c#?

i want to delete data in my database and using this code but its now working
private static void DeletePreviousRecord()
{
string connectionString = "Data Source=ABDULLAH\\ABDULLAHZAFAR;Initial Catalog=FoodHunt;Integrated Security=True";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Delete From RestaurantsMenu", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
var result = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{ }
}
}
}
i tried this but this is not working, how can i do that, any suggestion?
Setting the CommandType to StoredProcedure when you clearly use a sql text directly cannot do any good at your code.
Remove that line because the default is CommandType.Text (and this is correct for your command)
But as stated in the comment above.
If you catch the exception, at least write in some log or display at
video what the error message is
If you don't add a WHERE clause at your sql statement, you delete
everything in the table (Probably you are lucky that this code has
not worked)
Looking at your comment below, if you want to delete every record (and reset the Identity column if any) a faster approach is
using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE RestaurantsMenu", con))
For a quick reading about the difference between TRUNCATE and DELETE look at this article

Values from textBox not getting inserted into database

This is my code for inserting into database from textfields.
SqlConnection Connection = new SqlConnection("Data Source=ESHA\\SQLEXPRESS;Initial Catalog=Gen_Lic;User ID=sa;Password=sa#");
SqlCommand Command = Connection.CreateCommand();
try
{
// Open Connection
Connection.Open();
////Console.WriteLine("Connection Opened");
// Create INSERT statement with named parameters
Command.CommandText = "INSERT INTO Gen_Lic(Lic_No, UserID, Org, UserName, SolType, Version, Lic_Type, Meap_Supp, Lic_From, Lic_To, Supp_From, Supp_To, Max_User, Max_Mach, Mach_IP, Mach_MAC) VALUES (#Lic_No, #UserID, #Org, #UserName, #SolType, #Version, #Lic_Type, #Meap_Supp, #Lic_From, #Lic_To, #Supp_From, #Supp_To, #Max_User, #Max_Mach, #Mach_IP, #Mach_MAC)";
// Add Parameters to Command Parameters collection
Command.Parameters.AddWithValue("#Lic_No", txtLNo.Text);
Command.Parameters.AddWithValue("#UserID", txtUID.Text);
Command.Parameters.AddWithValue("#Org", txtOrg.Text);
Command.Parameters.AddWithValue("#UserName", txtUName.Text);
Command.Parameters.AddWithValue("#SolType", txtSType.Text);
Command.Parameters.AddWithValue("#Version", txtVer.Text);
Command.Parameters.AddWithValue("#Lic_Type", drpLType.SelectedItem.Text);
Command.Parameters.AddWithValue("#Meap_Supp", rdoMeapSupport.SelectedValue.ToString());
Command.Parameters.AddWithValue("#Lic_From", lblLFrom.Text);
Command.Parameters.AddWithValue("#Lic_To", lblLTo.Text);
Command.Parameters.AddWithValue("#Supp_From", lblSuppFrom.Text);
Command.Parameters.AddWithValue("#Supp_To", lblSuppTo.Text);
Command.Parameters.AddWithValue("#Max_User", txtMaxUsr.Text);
Command.Parameters.AddWithValue("#Max_Mach", txtMaxMach.Text);
Command.Parameters.AddWithValue("#Mach_IP", txtMachIP.Text);
Command.Parameters.AddWithValue("#Mach_MAC", txtMachMac.Text);
Connection.Close();
}
Now the problem is the code is working fine, but the values are not getting inserted into the database. Also, when I apply a breakpoint at the starting of the connection formation, a new blank IE window opens up.
Can someone guide me where am I going wrong?
I think, you are missing the following:
Command.ExecuteNonQuery();
before the Connection.Close()
Please run this query again the database
Command.ExecuteNonQuery();
before closing the connection

Categories