问题
Whenever I run the following code I get the expected output
private int NewBorrower(string givenName, string surname)
{
int returnValue = 0;
using (conn)
{
conn.Open();
string sql = "AddBorrower";
cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@givenName", SqlDbType.NVarChar).Value = givenName;
cmd.Parameters.Add("@surname", SqlDbType.NVarChar).Value = surname;
SqlParameter id = cmd.Parameters.Add("@id", SqlDbType.Int);
id.Direction = ParameterDirection.ReturnValue;
try
{
cmd.ExecuteNonQuery();
returnValue = (int)cmd.Parameters["@id"].Value;
}
catch (Exception e)
{
Console.WriteLine("Commit Exception Type: {0}", e.GetType());
Console.WriteLine(" Message: {0}", e.Message);
}
}
return returnValue;
}
When run from the front end I get the results I want, but when I check the database it doesn't show up in the table.
For good measure this is also the stored procedure being used
CREATE PROCEDURE [dbo].[AddBorrower]
@givenName nvarchar(50),
@surname nvarchar(50),
@id int = NULL OUTPUT
AS
INSERT INTO llBorrowers (givenName, surname)
VALUES (@givenName, @surname);
SET @id = SCOPE_IDENTITY();
RETURN @id
I've tried using transactions on both the c# and sql sides, and that didn't work at all. I should also mention that it is a local database, but I'm not sure that should affect it.
回答1:
When you use the DataDirectory substitution string in a WinForms application, its real value changes depending on your debug or release configuration.
In DEBUG your DataDirectory points to PROJECTFOLDER\BIN\DEBUG (or x86 variation if it is the case).
So it is extremely easy to get fooled by this. You create a connection in server explorer but this connection is ignored by your code that works on a different database.
You could create another connection in Server Explorer and name it DebugConnection, still keeping the original one for schema changes while you use the DebugConnection to check if your code executes as expected
As a side note, keep particular attention to the property Copy To the Output Directory
property on the MDF file if it is listed between the project items. If you set it to Copy Always
every time you start a debug session a fresh copy of your db will be copied from the project directory to the output directory effectively destroying the updates executed by your code. I recommend to set it to Copy Never
and handle manually the database schema changes
A reference: Where is DataDirectory
回答2:
You may try creating a SQLTransaction in C# part
Also, try changing your code like -
//Just create a SQL connection - cmd = new SqlCommand(conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "AddBorrower";
来源:https://stackoverflow.com/questions/21074944/c-sharp-sql-stored-procedure-isnt-committing