Can't add a row to database after the query is fine - c#

I am trying to add a row into the database but something seems wrong. The connection is okay and the query is fine too but after pressing the button the row isn't added.
con.Open();
SqlCommand cm = new SqlCommand("INSERT INTO Sports (Спорт) VALUES (#Спорт)",con);
cm.Parameters.AddWithValue("#Спорт", tbAddSport.Text);
try
{
int exec = cm.ExecuteNonQuery();
if (exec > 0)
{
MessageBox.Show("Added");
}
else
{
MessageBox.Show("Error");
}
}
catch (Exception ex)
{
MessageBox.Show("Error (ex)");
con.Close();
}
finally
{
con.Close();
clearBoxes();
}

If there is no exception. I see some possible problems.
You don't need to Close connection in catch block. If exception happen the con.Close() in finally will be execute always.
The other problems I can't find any documentation about cyrillic parameter names. It is possible to be not supported.
Try it like this:
SqlCommand cm = new SqlCommand("INSERT INTO Sports (Спорт) VALUES (#Sport)",con);
cm.Parameters.AddWithValue("#Sport", tbAddSport.Text);
It is bad practise to write cyrillic column names in database. Change name to Sport in the Sports Table.
Also are you sure that clearBoxes(); doesn't remove the possible exception.

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

Why it doesn't insert into sql table?

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)

How to avoid entering duplicate values into table through winform?

in my project I have set the client name as primary key and if I enter the same value, I will get exception, now I want to write the validation, i.e if I re enter the primary key value then I should get a message like "Data already exists", Please help me to do that, The code I am using to insert value is:
private void btnInsert_Click(object sender, EventArgs e)
{
if (txtName.Text == string.Empty)
{
MessageBox.Show("Please enter a value to Project Name!");
txtName.Focus();
return;
}
if (txtContactPerson.Text == string.Empty)
{
MessageBox.Show("Please enter a value to Description!");
txtContactPerson.Focus();
return;
}
SqlConnection con = Helper.getconnection();
con.Open();
string commandText = "InsertClient";
SqlCommand cmd = new SqlCommand(commandText, con);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#ContactPerson", txtContactPerson.Text);
cmd.CommandType = CommandType.StoredProcedure;
MessageBox.Show("Client details are inserted successfully");
txtName.Clear();
txtContactPerson.Clear();
object Name = cmd.ExecuteNonQuery();
con.Close();
BindData();
}
First, you can prevent a duplicate from ever occurring in the table by using a unique index or constraint. An index/constraint can work in concert with the suggestions below. If you only use a unique index and not one of the below solutions, inserting a duplicate record will throw an error and you will need to handle that on the other end.
you could check for the records existence and insert or update manually:
create procedure MyProcedure
(
#Name nvarchar(100),
...
)
as
if not exists (select * from MyTable where Name = #Name)
begin
insert into MyTable (Name,...) values (#Name,...)
end
else
begin
update MyTable
set ...
where Name = #Name
end
I would tend to allow the user to try to enter any superficially valid primary key, If it is a duplicate then there will be an exception that you can catch and display to the user.
The reason for this is you would have to check the database for an existing key so you might as well do this by trying to insert it and handling any errors.
You could probably improve the validation and error handling a lot more, popping up a message box on every individual problem is annoying, better to have a summary with all the problems. Also holding open a database connection while displaying a message box probably isn't advisable either.
private void btnInsert_Click(object sender, EventArgs e)
{
if (txtName.Text == string.Empty)
{
MessageBox.Show("Please enter a value to Project Name!");
txtName.Focus();
return;
}
if (txtContactPerson.Text == string.Empty)
{
MessageBox.Show("Please enter a value to Description!");
txtContactPerson.Focus();
return;
}
SqlConnection con = Helper.getconnection();
con.Open();
string commandText = "InsertClient";
SqlCommand cmd = new SqlCommand(commandText, con);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#ContactPerson", txtContactPerson.Text);
cmd.CommandType = CommandType.StoredProcedure;
try
{
object Name = cmd.ExecuteNonQuery();
MessageBox.Show("Client details are inserted successfully");
txtName.Clear();
txtContactPerson.Clear();
BindData();
}
catch(Exception ex)
{
//Handle exception, Inform User
}
finally
{
con.Close();
}
}
I understand your requirement, I see that you are asking about using of your own code instead of the exception. You can get it by using the try catch block. Try the following code:
try
{
object Name = cmd.ExecuteNonQuery();
MessageBox.Show("Client details are inserted successfully");
txtName.Clear();
txtContactPerson.Clear();
BindData();
}
catch(Exception ex)
{
//Handle exception, Inform User
}
finally
{
con.Close();
}
I tend to use Entity Framework as it will throw an exception in this case, however I suppose you could run an sql query first to check whether it exists or not, or though there may be a significant performance overhead with that

SQL Reading from a DB problem using a DataReader

I have a table of Users (tblUsers) which contains details of University staff. I am trying to populate a text box with the names of lecturers associated with a selected module.
I am getting all UserIDs associated with a particular module, testing if the User is a lecturer, if so then I add the ID to an ArrayList.
I then iterate through this array and call the method below during each iteration passing through the current ID.
However, if you look at the method below I am using a SqlDataReader and am getting an error while reading from it on this line:
txtLecturerName.Text += myReader["First_Name"].ToString();
The error message is:
'myReader["First_Name"]' threw an exception of type 'System.IndexOutOfRangeException'
The table layout I am using is below the method code. Any help with this would be greatly appreciated, I am one cup of coffee away from putting my head through the screen.
public void outputLecturerNames(string lecturerID)
{
// Create a new Connection object using the connection string
SqlConnection myConnection = new SqlConnection(conStr);
// If the connection is already open - close it
if (myConnection.State == ConnectionState.Open)
{
myConnection.Close();
}
// 'using' block allows the database connection to be closed
// first and then the exception handling code is triggered.
// This is a better approach than using a 'finally' block which
// would close the connection after the exception has been handled.
using (myConnection)
{
try
{
// Open connection to DB
myConnection.Open();
SqlCommand selectCommand = new SqlCommand(selectQuery, myConnection);
// Declare a new DataReader
SqlDataReader myReader;
selectQuery = "SELECT * FROM tblUsers WHERE User_ID='";
selectQuery += lecturerID + "'";
myReader = selectCommand.ExecuteReader();
while (myReader.Read())
{
txtLecturerName.Text += myReader["First_Name"].ToString();
txtLecturerName.Text += " ";
txtLecturerName.Text += myReader["Last_Name"].ToString();
txtLecturerName.Text += " , ";
}
myReader.Close();
}
catch (Exception err)
{
Console.WriteLine("Error: " + err);
}
}
}
tblUsers:
[User_ID][First_Name][Last_Name][Email_Address]
In your method, the variable selectQuery is not declared, and it is used as parameter to SqlCommand before it is assigned the query string on tblUsers.
You've probably misspelled a column name.
In general, you should never write SELECT * FROM ....
Instead, you should select only the columns you need.
This will make your program run faster by only querying the information that you need, and can produce better error messages.
This error is created when the column name given is not found. If you are anything like me, you've probably checked it several times, but is the table name correct (correct database, correct schema) and is the column name correct?
http://msdn.microsoft.com/en-us/library/f01t4cfy.aspx
You might try fully qualifying the name of the table (database.dbo.tblUsers). This would ensure that you are hitting the table you think you are. Also, try and put the names of the columns into the SQL statement. If they are not correct, your SQL statement will not execute properly.

Using OleDbCommand to update a record with byte[] data in binary format

Im using the code below, to update a record in an MS Access database, to store some information related to a property grid, however, im receiving a syntax error when the query tries to execute, and i cannot figure out why. ConnCheck simply looks to see if the connection is open, and if not, it opens it.
Thanks in advance
Main_Class.ConnCheck();
OleDbCommand cmd = new OleDbCommand("UPDATE [CALCULATION_RUN_TBL] SET [CAP_INPUTS]=?, [RA_INPUTS]=?, WHERE [CALCULATION_RUN_ID]=?", Main_Class.con);
try
{
cmd.Parameters.Add("#CAP_INPUTS", OleDbType.LongVarBinary).Value = SaveCAPSettings();
cmd.Parameters.Add("#RA_INPUTS", OleDbType.LongVarBinary).Value = eig.SaveSettings();
cmd.Parameters.Add("#CALCULATION_RUN_ID", OleDbType.Integer).Value = Main_Class.Calculation_Run_ID;
//Main_Class.con.Open();
cmd.ExecuteNonQuery();
Main_Class.con.Close();
}
catch (OleDbException ex)
{
//get the error message if connection failed
MessageBox.Show("Error in connection ..." + ex.Message);
Main_Class.con.Close();
}
Well a quick look says you have an extra comma
This: [RA_INPUTS]=?, WHERE should be [RA_INPUTS]=? WHERE

Categories