Insert statement into SQL Server database - c#

I'm trying to find this bug for the last several days, but without any success.
I'm trying to insert one new row in a database. Everything goes well: there is no error, and no program crashes.
My INSERT statement looks like this:
INSERT INTO Polozaj(Znesek, Uporabnik, Cas, Kupec, Popust, Poln_znesek)
VALUES(1,1,1,1,1,1)
That statement is ok, because when I run the query in my database it adds the new row.
My C# code looks like this:
string connection = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + Application.StartupPath + "\\Trgovina.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(connection);
string payment = ((Button)sender).Text, maxID = string.Empty;
double discount = Convert.ToDouble(discauntText.Text), totalPrice = Convert.ToDouble(fullPriceText.Text), fullPrice = Convert.ToDouble(discountPriceText.Text);
switch (payment)
{
case "Dobavnica": discount = 10; break;
case "Kartica": discount = 0; break;
case "Gotovina": discount = 5; break;
}
cn.Open();
SqlCommand maxIdCmd = new SqlCommand("SELECT MAX(Id_racuna) FROM Racun", cn);
maxID = Convert.ToString(maxIdCmd.ExecuteScalar());
maxID = maxID != "" ? Convert.ToString(Convert.ToInt32(maxID) + 1) : "1";
string stmt = "INSERT INTO Racun(Znesek, Uporabnik, Cas, Kupec, Popust, Poln_znesek) " +
"VALUES(#Price, #User, #Time, #Customer, #Discount, #FullPrice)";
SqlCommand cmd = new SqlCommand(stmt, cn);
cmd.ExecuteNonQuery();
cn.Close();
As I already mentioned, it looks like the program runs this query and everything is just normal, but when I look in the table Racun, there is no new row. Furthermore, when I try to refresh this table data visual studio (2012) gives me an error that looks like: This database cannot be imported. It is either unsupported SQL Server version or an unsupported database compatibility.
And my table Racun create query looks like this:
CREATE TABLE [dbo].[Racun] (
[Id_racuna] INT IDENTITY (1, 1) NOT NULL,
[Znesek] NUMERIC (10, 3) NULL,
[Uporabnik] NCHAR (20) NULL,
[Cas] NCHAR (15) NULL,
[Kupec] NCHAR (10) NULL,
[Popust] NUMERIC (10, 3) NULL,
[Poln_znesek] NUMERIC (10, 3) NULL,
PRIMARY KEY CLUSTERED ([Id_racuna] ASC)
);
I don't know what's going wrong. Can anyone help?

There is three possible scenarios for an insert like that:
The insert succeeds.
You get an exception.
You have a trigger that replaces the insert with some other action.
I guess that you don't have a trigger, and as you don't get a record in the table, there has to be an exception.
Do you have any code that catches the exception at any other level? That would explain why you don't see it, and it would also leave the database connection unclosed, which would explain why you have problems connecting to the database afterwards.
Using a using block for the database connection would close it properly even if there is an error in the code.
You are using a parameterised query, but I can't see that you add the parameters to the command object anywhere in the code. That would be something like:
cmd.Parameters.Add("Price", SqlDbType.Decimal).Value = price;
cmd.Parameters.Add("User", SqlDbType.NChar, 20).Value = user;
cmd.Parameters.Add("Time", SqlDbType.NChar, 15).Value = time;
cmd.Parameters.Add("Customer", SqlDbType.NChar, 10).Value = customer;
cmd.Parameters.Add("Discount", SqlDbType.Decimal).Value = discount;
cmd.Parameters.Add("FullPrice", SqlDbType.Decimal).Value = fullPrice;

I would try wrapping your code in a try block, and see if you can catch a SqlExecption:
try {
SqlCommand cmd = new SqlCommand(stmt, cn);
cmd.ExecuteNonQuery();
} catch (SqlException ex) {
Console.WriteLine(ex.Message);
}
Edit: It looks like you're missing your parameters for your INSERT statement, and you should probably look at using a SqlTransaction:
SqlCommand maxIdCmd = new SqlCommand("SELECT MAX(Id_racuna) FROM Racun", cn);
maxID = Convert.ToString(maxIdCmd.ExecuteScalar());
maxID = maxID != "" ? Convert.ToString(Convert.ToInt32(maxID) + 1) : "1";
string stmt = "INSERT INTO Racun(Znesek, Uporabnik, Cas, Kupec, Popust, Poln_znesek) " +
"VALUES(#Price, #User, #Time, #Customer, #Discount, #FullPrice)";
SqlCommand cmd = new SqlCommand(stmt, cn);
// Adding parameters to the insert statement:
cmd.Parameters.AddWithValue("#Price", price);
cmd.Parameters.AddWithValue("#User", user);
cmd.Parameters.AddWithValue("#Time", time);
cmd.Parameters.AddWithValue("#Customer", customer);
cmd.Parameters.AddWithValue("#Discount", discount);
cmd.Parameters.AddWithValue("#FullPrice", fullprice);
// Start a transaction so we can roll back if there's an error:
SqlTransaction transaction = cn.BeginTransaction();
cmd.Transaction = transaction;
try {
cmd.ExecuteNonQuery();
transaction.Commit();
} catch (SqlException ex) {
transaction.Rollback();
Console.WriteLine(ex.Message);
} finally {
cn.Close();
}

Related

How do I execute a SqlDataReader after sqlInsertCmd.ExecuteNonQuery

I am inserting a data row into my SQL Server database and then I want to query the data to get the unique identifier from the inserted row but my SqlDataReader is returning an empty dataset. I am thinking it maybe that the transaction hasn't been committed or something like that but I am not sure. I do not get an error.
Here is my code:
try
{
strQuery = "INSERT INTO clientnames VALUES(NEWID(),'" + txtACLastName.Text + "','" + txtACFirstName.Text + "'," + 1 + ")";
using (SqlCommand sqlInsertCmd = new SqlCommand(strQuery, sqlConn))
{
intQueryResult = sqlInsertCmd.ExecuteNonQuery();
if (intQueryResult == 0)
{
blnSuccess = false;
goto InsertClientNamesError;
}
else
{
blnSuccess = true;
}
sqlInsertCmd.Dispose();
}
if (blnSuccess)
{
strQuery = "select clientID from clientnames where firstname = '" + txtACFirstName.Text + "' and lastname = '" + txtACLastName.Text + "'";
using (SqlCommand sqlSelectCmd = new SqlCommand(strQuery, sqlConn))
{
SqlDataReader sqlDataRead = sqlSelectCmd.ExecuteReader();
while (sqlDataRead.Read())
{
strClientID = sqlDataRead.ToString();
}
sqlDataRead.Close();
sqlSelectCmd.Dispose();
}
}
}
catch (Exception exQuery)
{
System.Windows.MessageBox.Show("InsertClientNames: Error, " + exQuery.Message + ", has occurred.");
}
You are not getting the desired result because perhaps the SqlConnection is not opened explicitly (just a guess hard to tell without having full code). But this link shows you how to read from reader --> https://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.110).aspx
But I suggest that you Please do not do it this way. Reason is you are making Two round trips to the DB Server when only one would have done the job for you IF you were using stored procedures. Also you are exposing yourselves to SQL Injection attacks as you are not parameterizing your queries.
Stored procedure:
CREATE PROCEDURE dbo.INS_clientnames
(
#FirstName varchar(100),
#LastName varchar(100),
#NewID int out
)
AS
BEGIN
Declare #Err int
set #NewID = NewID() -- Get the New ID and store it in the variable ( #NewID ) that the SP will return back to the caller
INSERT INTO clientnames values (#NewID , #FirstName , #LastName)
SET #Err = ##ERROR
IF #Error <> 0 -- Check If there was an error
Begin
SET #NewID = -1 -- Indicates that there was an error. You could log this into a Log Table with further details like error id and name.
END
RETURN
END
C# code to execute the above stored procedure and get the NewID:
using(SqlConnection conn = new SqlConnection(connectionString ))
{
using(SqlCommand cmd = new SqlCommand("dbo.INS_clientnames", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters that the Stored Procedure expects
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 100);
cmd.Parameters.Add("#LastName" , SqlDbType.VarChar, 100);
cmd.Parameters.Add("#NewId" , SqlDbType.Int).Direction = ParameterDirection.Output;
// set parameter values that your code will send to the SP as parameter values
cmd.Parameters["#FirstName"].Value = txtACFirstName.Text ;
cmd.Parameters["#LastName"].Value = txtACLastName.Text ;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from #NewId
int NewID = Convert.ToInt32(cmd.Parameters["#NewId"].Value);
}
}
Add the following line to your stored procedure that inserts the record
SELECT SCOPE_IDENTITY()
This will return the last identity value inserted in that table.
And use cmd.ExecuteScalar() instead of ExecuteNonQuery()
ExecuteScalar() executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. [More info][1]
I see two approaches to do this:
either you generate the new GUID on the client side in your C# code and pass it into the query - then you already know what the new id is going to be, so you don't need to do a second query to get it:
you create your GUID on the server side and return it to the caller using the OUTPUT clause in your query
Approach #1:
// define connection string and query
string connStr = "--your connection string here--";
string query = "INSERT INTO dbo.Clients(ClientID, FirstName, LastName) VALUES(#ID, #First, #Last);";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
// create the GUID in C# - this is the ID - no need to go get it again - this *IS* the id
Guid id = Guid.NewGuid();
// set the parameters
cmd.Parameters.Add("#ID", SqlDbType.UniqueIdentifier).Value = id;
cmd.Parameters.Add("#First", SqlDbType.VarChar, 50).Value = "Peter";
cmd.Parameters.Add("#Last", SqlDbType.VarChar, 50).Value = "Miller";
// open connection, execute query, close connection
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Approach #2:
// define connection string and query
string connStr = "--your connection string here--";
// query has an "OUTPUT" clause to return a newly inserted piece of data
// back to the caller, just as if a SELECT had been issued
string query = "INSERT INTO dbo.Clients(ClientID, FirstName, LastName) OUTPUT Inserted.ClientID VALUES(NEWID(), #First, #Last);";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
// set the parameters - note: you do *NOT* send in a GUID value - the NEWID() will create one automatically, on the server
cmd.Parameters.Add("#First", SqlDbType.VarChar, 50).Value = "Frank";
cmd.Parameters.Add("#Last", SqlDbType.VarChar, 50).Value = "Brown";
// open connection
conn.Open();
// execute query and get back one row, one column - the value in the "OUTPUT" clause
object output = cmd.ExecuteScalar();
Guid newId;
if (Guid.TryParse(output.ToString(), out newId))
{
//
}
conn.Close();
}

Insert/Update in asp.net and SQL SERVER 2008

I am trying to insert a record if requested prodName doesnot exist in database. If it exists I want to update the value of quantity attribute. I have used the following it neither inserts nor Updates any record. I get following exception:
ExecuteScalar requires an open and available Connection. The connection's current state is closed
This is the code
public static void manageStock(CompanyStock stock)
{
///// Check if record exists/////////
cmd = new SqlCommand("select count(*) from tblStock where prodName=#prodName", con);
cmd.Parameters.AddWithValue("#prodName", stock.prodName);
con.Open();
Int32 count = (Int32)cmd.ExecuteScalar(); //returns null if doesnt exist
con.Close();
if (count > 0)
{
cmd = new SqlCommand("update tblStock set quantity = #quantity where prodName=#prodName", con);
cmd.Parameters.AddWithValue("#prodName", stock.prodName);
cmd.Parameters.AddWithValue("#quantity", stock.quantity);
}
else
{
cmd = new SqlCommand("insert into tblStock(prodName,quantity) values (#prodName, #quantity)", con);
cmd.Parameters.AddWithValue("#prodName",stock.prodName);
cmd.Parameters.AddWithValue("#quantity",stock.quantity);
}
try
{
con.Open();
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
}
Edited
I edited my code. It works fine now. I had to open my connection before executing ExecuteScalar But I want to know the standard way of writing this opening and closing stuff. It looks kind of haphazard. How can I improve this?
You can use Convert.ToInt32() method for converting the result into integer value.
if the value is null it converts it into 0.
Try This:
int count = Convert.ToInt32(cmd.ExecuteScalar());
Consider using MERGE clause in sql-server. Here is a good Microsoft article you can use.
What does it do when you step through the code?
In some SQL collations (Latin1_General_BIN for example), variables are case sensitive. In your first select statement you have #ProdName in your query and #prodName in your parameters collection. If you have a case sensitive collation, you're never getting past this part. Right-click on the database in Management Studio and click Properties to find the collation.
Error say that there's no connection.May u check first of all that issue so
Check connection and if is not null and exist at this point check it con.State = Open or any other value. I connection state is closed open it.But first of all where is connections declaration ? i don't see it in your code.
TRY THIS :
//USING THE STATEMNET USING IT WILL TAKE CARE TO DISPOSE CONNECTION AND PLACE TRY CATCH WITHIN PROCS
{
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings("connectionString"))) {
if (cnn.State == System.Data.ConnectionState.Closed)
cnn.Open();
using (SqlCommand cmd = new SqlCommand()) {
try {
cmd.Connection = cnn;
cmd.CommandText = "YOUR SQL STATEMENT";
int I = Convert.ToInt32(cmd.ExecuteNonQuery);
if (I > 0)
{
cmd.CommandText = "YOUR SQL STATEMENT";
//ADDITIONAL PARAMTERES
}
else
{
cmd.CommandText = "YOUR SQL STATEMENT";
//ADDITIONAL PARAMETERS
}
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
}
You can try this code. First write a stored procedure:
CREATE PROCEDURE sprocquanupdateinsert
#prodName nvarchar(250),
#quantity int
AS
BEGIN
UPDATE tblStock
SET quantity = #quantity
WHERE prodName = #prodName
IF ##ROWCOUNT = 0
INSERT INTO tblStock(prodName, quantity)
VALUES (#prodName, #quantity)
END
GO
Then in code behind you can use this
using (conn)
{
SqlCommand cmd = new SqlCommand("sprocquanupdateinsert", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#prodName", stock.prodName);
cmd.Parameters.AddWithValue("#quantity", stock.quantity);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

error with select using Scope_Identity

I am trying to understand what is wrong with this select.
I want to get the last user_Id which was been added.
Here is the error message:
The parameterized query '(#Id_user int)SELECT SCOPE_IDENTITY() AS id_user' expects the parameter '#Id_user', which was not supplied.
Here is the SQL statement:
if (count >= 1) /* <=== verification from the insert SQL */
{
string selectStatement = "SELECT SCOPE_IDENTITY() AS id_user";
SqlCommand selectCommand = new SqlCommand(selectStatement, sqlConnection);
selectCommand.Parameters.Add("#Id_user", SqlDbType.Int, 0, "Id_user");
int newID = (int)selectCommand.ExecuteScalar();
int User_ID = Convert.ToInt32(selectCommand.Parameters["#Id_user"].Value);
Session["Id_user"] = User_ID;
buserIdAuthenticated = true;
Session["userIdAuthenticated"] = buserIdAuthenticated;
Response.Redirect("../pages/Welcome.aspx");
}
}
catch (SqlException ex)
{
lblMessage.Text = ex.Message;
}
finally
{
sqlConnection.Close();
}
you haven't defined an #parameter in your sql statement so you don;t need to add the parameter at all - just get the result of ExecuteScalar - you should be able to cast it to an int - although I cast it specifically in the sql statement too -
select cast(Scope_identity() as int) ....
so you'd end up with somthing like
string selectStatement = "SELECT cast(SCOPE_IDENTITY() AS int)";
SqlCommand selectCommand = new SqlCommand(selectStatement, sqlConnection);
object newIDobj = (int)selectCommand.ExecuteScalar();
if(newIDobj!=null)
Session["Id_user"] = (int)newIDobj;
Even better you could create a stored procedure and have the insert done there, where it can then return scope identity.
Edited to include example with insert. (just typed in here - so likely some typos)
int newID = -1;
string commandString = "insert (code, desc, numbervalue) values (#code, #desc,#numbervalue); select cast(scope_identity() as int);"
using(SqlCommand cmd = new SqlCommand(commandString))
{
try
{
cmd.Parameters.Add("#code", )
// etc
int newid=(int)(cmd.ExecuteScalar()??-1);
}
catch(Exception e)
{
// something went wrong
}
}
if(newID!=-1)
{
// do something;
}

One time record insertion then update many times

I have a form where a user can insert, view and update data. Data insertion is done only once, then updates can be done many times. By default, the user will be able to view the data if it exists in the database.
I tried this but it doesn't insert into database. Then suppose a data exists in database and when the user wants to update the record, it throws an error - DataReader is open.
private void display_Emp()
{
try
{
using (sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
{
sqlCon.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Employee", sqlCon);
DataSet ds = new DataSet("Employee");
da.Fill(ds, "Employee");
int x = 0;
for (x = 0; x < ds.Tables[0].Rows.Count; x++)
{
txtID.Text = ds.Tables[0].Rows[x][1].ToString();
txtEmpName.Text = ds.Tables[0].Rows[x][2].ToString();
}
}
}
catch(Exception exx) {
MessageBox.Show(exx.Message);
}
finally {
sqlCon.Close();
}
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
using (sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
{
sqlCon.Open();
SqlCommand com = new SqlCommand("SELECT * FROM Employee", sqlCon);
read = com.ExecuteReader();
while (read.Read())
{
if (read.HasRows)
{
SqlCommand update = new SqlCommand("UPDATE Employee SET EmpID = '" + txtID.Text + "' , EmpName = '" + txtEmpName.Text + "', sqlCon);
update.ExecuteNonQuery();
MessageBox.Show("Employee details updated!", "Employee", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
SqlCommand comm = new SqlCommand("INSERT INTO Employee(EmpID, EmpName) VALUES ('" + txtID.Text + "','" + txtEmpName.Text + "')", sqlCon);
comm.ExecuteNonQuery();
MessageBox.Show("Employee details saved!", "Employee", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
read.Close();
sqlCon.Close();
}
}
EDIT:
Table:- Deepz (ID int PK, Goodname varchar(50) )
DECLARE #ID int
DECLARE #Goodname varchar(50)
MERGE Deepz t
USING (SELECT #ID[ID], #Goodname[Goodname]) s
ON (t.ID = s.ID)
WHEN MATCHED THEN
UPDATE
SET t.Goodname = #Goodname
WHEN NOT MATCHED THEN
INSERT (ID, Goodname)
VALUES (#ID, #Goodname);
Errors:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 't'.
Msg 137, Level 15, State 2, Line 2
Must declare the scalar variable "#ID".
You should change your save functionality to:
If you're on SQL Server 2008 or later, use SQL Merge statement to insert or update depending on whether record exists or not
DECLARE #nameField VarChar(50) = 'some data'
MERGE dbo.MyTable t
USING (SELECT #nameField [field]) s
ON t.myData = s.field
WHEN MATCHED THEN
UPDATE
SET t.myData = #nameField
WHEN NOT MATCHED THEN
INSERT (myData)
VALUES (#nameField);
If you are on SQL Server 2005 or earlier, you will need to use something like below, but you may have a race condition (but imho will still be better than your original design, which has the potential for a race condition as well) so depending on your environment you may need to play around with locks, etc
IF EXISTS (SELECT * FROM Deepz WHERE [ID] = #ID)
BEGIN
UPDATE Deepz
SET Goodname = #Goodname
WHERE [ID] = #ID
END
ELSE
BEGIN
INSERT Deepz (ID, Goodname)
VALUES (#ID, #Goodname);
END
Use sql params instead of building the statement by concatenation, will save you from SQL injection attacks
UPDATE Employee SET EmpID = #id, EmpName = #name
then
SqlCommand comm = new SqlCommand(...);
// note below is a bit simplified, in reality you should do int.TryParse
comm.Parameters.Add(#id, SqlDbType.Int).Value = int.Parse(txtID.Text);
This is a bit of a shot in the dark but, try this:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
using (sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
{
sqlCon.Open();
SqlCommand com = new SqlCommand("SELECT * FROM Employee", sqlCon);
com.Parameters.AddWithValue(#empID, SqlDbType.Int).Value = int.Parse(txtID.Text); // Add this line
com.Parameters.AddWithValue(#empName, SqlDbType.NVarChar).Value = txtEmpName.Text; // Add this line too
SqlDataReader read = new SqlDataReader(); // You also need to 'new' up your SqlDataReader.
read = com.ExecuteReader();
while (read.Read())
{
if (read.HasRows)
{
SqlCommand update = new SqlCommand("UPDATE Employee SET EmpID = #empID, EmpName = #empName", sqlCon);
update.ExecuteNonQuery();
MessageBox.Show("Employee details updated!", "Employee", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
SqlCommand comm = new SqlCommand("INSERT INTO Employee(EmpID, EmpName) VALUES (#empID, #empName)", sqlCon);
comm.ExecuteNonQuery();
MessageBox.Show("Employee details saved!", "Employee", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
read.Close();
sqlCon.Close();
}
}
From the examples i'm looking at the "If" condition and "While" condition look like they are inverted.
http://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.80%29.aspx
You check to see if there are rows first and then iterate over them

Adding to a sql integer column using C#

I am trying to update a SQL table from my C# backend, but it never successfully executes; mainServiceButton is a pre-existing value in the linkName column. Here is what I have so far:
conn.Open();
string qry = "UPDATE clickStream SET clickCount = (clickCount + 1) WHERE linkName = mainServiceButton";
SqlCommand cmd = new SqlCommand(qry, conn);
try
{
cmd.ExecuteScalar();
}
catch
{
MessageBox.Show("not executed");
}
conn.Close();
This is how the table was created:
CREATE TABLE clickStream(
click_ID int identity(1,1),
linkName nvarchar(50) not null,
clickCount int,
PRIMARY KEY(click_ID));
The desired result is to increase the clickCount by 1 every time a link(linkName) is clicked on. Any Suggestions?
MessageBox.Show("not executed"); is not going to help you much except to obscure the details of the error: you need to instead output the details of the caught exception to understand what happened.
Addressing this and other suggestions made in comments...
mainServiceButton nakedly inline in the SQL text not possibly being what you want
a SqlParameter being warranted to accept a value for the WHERE sanely
ExecuteNonQuery() instead of ExecuteScalar() being the right call
..., see what sort of mileage you get with this instead:
conn.Open();
string qry = "UPDATE clickStream SET clickCount = (clickCount + 1) WHERE linkName = #linkName";
SqlCommand cmd = new SqlCommand(qry, conn);
// Use a SqlParameter to correct an error in the posted code and do so safely.
cmd.Parameters.Add(new SqlParameter("#linkName", "mainServiceButton"));
try
{
cmd.ExecuteNonQuery(); // not ExecuteScalar()
}
catch (SqlException sex)
{
// Output the exception message and stack trace.
MessageBox.Show(sex.ToString());
}
conn.Close();
Try the below, not tested so you may need to fix minor bugs:
conn.Open();
string qry = "UPDATE clickStream SET clickCount = (clickCount + 1) WHERE linkName = 'mainServiceButton';SELECT ##ROWCOUNT;";
SqlCommand cmd = new SqlCommand(qry, conn);
try
{
int rowsAffected = (int)cmd.ExecuteScalar();
if (rowsAffected != 1)
throw new ApplicationException("Rows affected should be 1, " + rowsAffected + " were affected.");
}
catch (Exception ex)
{
MessageBox.Show("Not executed successfully, exception: " + ex.ToString());
}
conn.Close();

Categories