SQL Exception Handling And SQL Transactions
Jan 31, 2008
Hi guys,
Does any one know how to detect when a SQL transaction has been rolled back in either a windows application or ASP.NET. My Transactions always run but when they are rolled back Visual Basic does not pick up any errors in the 'Try Catch SqlException'. Does any one know a way round this. Sorry for the lack of code. Im writing this post on a friends PC but i wil put up my code as soon as possible. Thanks in advance
Matt
View 4 Replies
ADVERTISEMENT
Sep 7, 2007
it gives error while calling a sql stored procedure as "INPUT STRING WAS NOT IN A CORRECT FORMAT". I am providing the code here.public void get_issid(string cse_email, string tech_email, string subject, string issue_details, string response, string solv_date, out int issid)
{
// Establish ConnectionSqlConnection oConnection = GetConnection();
// build the commandSqlCommand oCommand = new SqlCommand("get_issid", oConnection);
oCommand.CommandType = CommandType.StoredProcedure;
// ParametersSqlParameter paracse_email = new SqlParameter("@cse_email", SqlDbType.VarChar, 50);
paracse_email.Value =cse_email;
oCommand.Parameters.Add(paracse_email);
SqlParameter paratech_email = new SqlParameter("@tech_email", SqlDbType.VarChar,50);
paratech_email.Value = cse_email;
oCommand.Parameters.Add(paratech_email);SqlParameter parasubject = new SqlParameter("@subject", SqlDbType.VarChar, 50);
parasubject.Value = subject;
oCommand.Parameters.Add(parasubject);SqlParameter paraissue_details = new SqlParameter("@issue_details", SqlDbType.VarChar, 500);
paraissue_details.Value = issue_details;
oCommand.Parameters.Add(paraissue_details);SqlParameter pararesponse = new SqlParameter("@response", SqlDbType.VarChar, 500);
pararesponse.Value = response;
oCommand.Parameters.Add(pararesponse);SqlParameter parasolv_date = new SqlParameter("@solv_date", SqlDbType.DateTime);
parasolv_date.Value = solv_date;
oCommand.Parameters.Add(parasolv_date);SqlParameter paraissid = new SqlParameter("@issid", SqlDbType.Int);paraissid.Direction = ParameterDirection.Output;
oCommand.Parameters.Add(paraissid);
try
{
oConnection.Open();
oCommand.ExecuteNonQuery();issid = int.Parse(paraissid.Value.ToString());
}catch (Exception oException)
{throw oException;
}
finally
{
oConnection.Close();
}
}
the stored procedure is:
create proc [dbo].[get_issid](@tech_email varchar(50), @cse_email varchar(50),@subject varchar(50),@issue_details varchar(500),@response varchar(500),@solv_date datetime, @issid int output)
as
select @issid=tech_response.issue_id from tech_response,issue_details where tech_response.tech_email=@tech_email and tech_response.cse_email=@cse_email and tech_response.subject=@subject and tech_response.issue_details=@issue_details and response=@response and solv_date=@solv_date and tech_response.issue_id=issue_details.issue_id
requested to help in this
View 2 Replies
View Related
Nov 14, 2007
I'm unsure how to handle an SQL Exception correctly when the database is unavailable/offline.
I have my aspx file with the C# code-behind, but all of the SQL stuff is done in a separate code file in the App_Code directory.E.g.
CODE-BEHINDDatabaseModifier.deleteUser(username);
DATABASEMODIFIER.cspublic static void deleteUser(string username){ SqlConnection conn = SqlLogin.SqlConnect; SqlCommand command = new SqlCommand("DELETE FROM <table> WHERE Username = '" + username + "'", conn); conn.Open() command.ExecuteNonQuery(); conn.Close()}
Now, that code works perfectly, however if the database I'm connecting to is offline, an SQLException is thrown and because the SQL is handled in my DatabaseModifier class, I'm not sure how to handle it correctly.If I use a Try/Catch block in my code-behind, it doesn't get thrown because the error occurs in my DatabaseModifier class. If I use a Try/Catch block in my DatabaseModifier class, what can I put in the catch block that will inform the user of the database being offline and/or how can I perform a url redirection?
Any help is greatly appreciated.
View 3 Replies
View Related
Apr 18, 1999
Hi,
Im Nithyananda working on a project with SQL server 6.0
Im having a stored procedure which inserts into a table .
If I violate the primary key constraint on the table , I get a 2627 error.
I would like to replace this error with my own.Could u tell me how to do it?
Im an ORACLE guy and relatively new to SQL server.
Is it possible for me to propogate the same error message to any front end?
In my case ,Im using VC++ as front end.
Could someone also tell me the way of calling a SQL stored procedure from
VC++?
Regards
Nithyananda
View 1 Replies
View Related
Aug 22, 2007
Hi All
I m new to the sqlserver.In Oracle we can handle exceptions like this
declare
name varchar(20);
begin
select ename into name from emp where eno=&eno;
dbms_output.put_line(name);
exception
when no_data_found then
dbms_output.put_line('No Entry');
end;
/
We will get the message No Entry When corrsponding employee number dosent exists.
In Sqlserver how to handle these things.
Specifically my requirement is with select statement(Like above program)
Waiting for valuable suggestions
Baba
View 4 Replies
View Related
Sep 24, 2007
Hello,
I am trying to catch an error, but not able to. I am storing the value of @@Error soon after the statement which I believe would generate error. In order to produce the error I have deliberately used a wrong table name. So, the statement breaks but never comes to my error handling code snippet. Instead, it just throws the SQL server error message and quits. What am I doing wrong here? Here is the code snippet. The actual name of the temporary table is #TEMPO_TABLE, but in order to generate the error I have used #TEMPO_. Since this would surely error out, it should go to the label ROLLITBACK. But is not going to that label. Neither is it printing the error number as per the PRINT statement there. It just throws the SQL error and quits the execution. (Or should it NOT??). The Error that it throws it this:
Server: Msg 208, Level 16, State 1, Procedure FEED_PULL_XX, Line 157
Invalid object name '#TEMPO_'.
Can you please let me know whats going wrong here? Thanks a lot in advance.
INSERT INTO Table1
(
[ITAM_ASSET_EUP_BUS_LINE],
[ITAM_MACHINE_STATUS],
[ITAM_OWNER_ID],
[ITAM_ASSET_ADMIN],
[ITAM_MODEL],
[ITAM_ASSET_NAME],
[ITAMMACHINE_PURPOSE]
)
SELECT
[ITAM_ASSET_EUP_BUS_LINE],
[ITAM_MACHINE_STATUS],
[ITAM_OWNER_ID],
[ITAM_ASSET_ADMIN],
[ITAM_MODEL],
[ITAM_ASSET_NAME],
[ITAMMACHINE_PURPOSE]
FROM
#TEMPO_
SET @ErrNo = @@Error
PRINT '@ErrNo is ' + ltrim(str(@ErrNo)) + '.'
IF @ErrNo <> 0
Begin
PRINT '@ErrNo is ' + ltrim(str(@ErrNo)) + '.'
GOTO ROLLITBACK
End
View 7 Replies
View Related
Jun 17, 2006
I need help please....
I am using exception handling and Transaction handling combined.
The code is written to delete a record from 2 different table.
The purpose of using exception and transaction handling combined is to
make sure that the record is deleted in BOTH table. If there is error
while deleting a record from one of the tables, it will rollback the
database to the original and will stop deleting any record.
However, The Transaction handling is not working. When error occurs
while deleting a record on table A, the code still delete a record from
one table B. The transaction.RollBack() doesn't work. This is my code:
Try
Conn
= New
SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Conn.Open()
Trans = sConn.BeginTransaction
For Each row In GridView1.Rows
Dim sql As String = "SELECT * FROM Member
Using Cmd As New SqlCommand(sql, Conn, Trans)
SqlDataSource1.DeleteParameters("MemberID").DefaultValue =
DropDownListMember.SelectedValue
SqlDataSource1.Delete()
SqlDataSource2.DeleteParameters("CarID").DefaultValue =
DropDownListCar.SelectedValue
SqlDataSource2.Delete()
End Using
End If
Next
sTrans.Commit()
Label1.Text = "deleted."
Catch ex As Exception
If sTrans IsNot Nothing Then
sTrans.Rollback()
End If
Label1.Text = "error"
Return
Finally
If sConn IsNot Nothing Then
sConn.Close()
End If
End Try
soo much thanks in advanced!!!
View 1 Replies
View Related
Feb 4, 2008
Hi,
I'm trying to do exception handling in a stored procedure, such as IF (@@ERROR <> 0) execute and insert on to an error log table. I have set the volatile @@ERROR global to a variable, but the proc is still throwing a primary key exception; hence, it's not being trapped. My question is why isn't my exception being handled?
Here's my code, your help is much obliged. (my error proc is below the caller)
CREATE PROCEDURE [dbo].[INSERT_STATS_NO_GROUP_PROC]
@stat_type_id int,
@stat_delimited_file_id smallint,
@time_interval datetime,
@call_volume int,
@Err int OUTPUT
AS
SET @Err = 0
DECLARE @Error int
BEGIN TRANSACTION
INSERT INTO DAILY_SUMMARY_STATISTICS
(
stat_type_id,
stat_delimited_file_id,
ssda_customer_id,
time_interval,
call_volume
)
VALUES
(
@stat_type_id,
@stat_delimited_file_id,
NULL,
@time_interval,
@call_volume
)
SET @Error = @@ERROR
IF(@Error <> 0)
BEGIN
GOTO abort
END
COMMIT TRANSACTION
abort:
ROLLBACK TRANSACTION
EXECUTE SET_ERROR_TO_LOG_PROC @SQLErrorID = @Error,@ObjectName = 'INSERT_STATS_NO_GROUP_PROC'
SET @Err = @Error
/*ERROR PROC*/
CREATE PROCEDURE [dbo].[SET_ERROR_TO_LOG_PROC]
@SQLErrorID int,
@ObjectName varchar(50)
AS
DECLARE @SQLErrDescription varchar(200)
SELECT @SQLErrDescription = description FROM master..sysmessages WHERE error = @SQLErrorID
BEGIN TRANSACTION
INSERT INTO [dbo].[OSAUTOREPORTS_ERROR_LOG]
(
error_id,
error_description,
object_name
)
VALUES
(
@SQLErrorID,
@SQLErrDescription,
@ObjectName
)
COMMIT TRANSACTION
Thanks Russ
View 5 Replies
View Related
May 20, 2008
can I handle exception in SQL functions? how??
I am tring to migrate the Database from Oracle 9i to SQL server 2005 with SSMA which converts function in one procedure and wrapper function because of exception handling in Oracle.
View 11 Replies
View Related
Feb 29, 2008
in my package i'm using a for each loop container in order to process all files in a certain folder. everything works fine but of course when i start the service and there are no files available the package waits. is there a way to simply say skip the for each loop or semething like that?
View 2 Replies
View Related
Mar 6, 2009
I am trying to handle exceptions using try catch with remote database.
I am writing the following code which works fine if login locally but when I am trying to do the same on linked server its not being caught in try..catch block.
The procedure I am writing to raiserror
create proc CustomError
as
RAISERROR ('db error', 16, 1);
I am calling the above procedure in local database using following code
BEGIN TRY
exec CustomError
END TRY
BEGIN CATCH
select ERROR_MESSAGE() as ERROR_MESSAGE;
END CATCH;
GO
and it works perfectly. I am able to catch the error in catch block.
and i m getting the following result
db error
but when i am trying to do the same on linked server the code doesn't take me to catch block. I am getting following error while executing the code
go
BEGIN TRY
exec [192.168.0.50].[BM].dbo.CustomError
END TRY
BEGIN CATCH
select ERROR_MESSAGE();
END CATCH;
GO
where [192.168.0.50] is a linked server name and BM is the database name and custom error is my sp which is on remote server.
its giving me following error
Msg 50000, Level 16, State 1, Procedure CustomError, Line 11
db error
View 1 Replies
View Related
May 29, 2007
I'm creating a class that will wrap a SqlException and will offer the developer a way of determining how to proceed in handling the exception by offering a suggestion of retrying, revalidating the data, and/or calling the entire process a no go.
One of the ways i've come up with to accomplish this is by using the severity (SqlException.Class) to assist in making a suggestion to the developer.
I'm hoping to get some feedback from the developers who use this forum if they feel severity is or is not the way to go, and also to offer any other ways of accomplishing that they can come up with.
Thanx
AJ
View 3 Replies
View Related
Mar 18, 2008
I have a cursor that loops through some records.
Upon an exception being caught (i.e. when inserting a record, it violates integrity constraint), I would like to do my normal exception handling routine and then continue with the loop to the next record.
Is this possible? If so, how do I implement this behavior?
Thanks.
View 1 Replies
View Related
Aug 28, 2015
I created an SSIS packages on VS 2013 using SQL 2014. I have to use transactions and without MSDTC as we don't have that environment.
Ok my issue when I load a stage table during the process and then I select from that same stage table my records on another table are not being inserted. why? I have done sql profiler an all sql statements are being ran under same SPID.
Package design
1. For each container - this is to process files on a folder
2. Execute sql task - begin tran
3. sequence container - to hold all and organize containers
4. execute sql task - truncate ImpTableA
5. Data Flow task - Import data into ImpTableA from file
6. execute sql task - insert into DimProducts and new products found in ImpTableA that are not in DimProducts so I'm joining the 2 tables together as a outter join and getting the new ones.
7. Execute sql task - commit tran
8. Execute sql task - rollback tran
On Step 6 I don't find any new rows on DimProducts even though I know there is new products. I have tested the sql statement in SSMS and it works and I find new rows. For some reason SSIS is not finding new products, I'm assuming that the rows are not committed yet and therefore can query them but I thought if I was under the same transaction and SPID I would be able to read uncommitted rows.
Need to be able to read from table that was just inserted in a transaction incase of a failure roll everything back.
View 3 Replies
View Related
Dec 2, 2005
I'm trying to get to grips with the formview control and have a problem regarding where an exception is raised if SQL server raises an error when an insert is taking place. I am new to both asp.net & c#
I have put the following code in the SqlDataSource2_Inserted & Formview1_Inserted events as a way of determining where the exception is raised:
if (e.ExceptionHandled){ string exceptionmessage = e.Exception.Message; lblStatus.Text = exceptionmessage;}
These two events are the only one's that have the ExceptionHandled and Exception properties.
I run the code with data that will raise a duplicate key error from SQL Server but the error is not being caught by either of these two handlers. All I get is a page that starts with
Server Error in '/SourceCode' Application.
Violation of UNIQUE KEY constraint 'IX_reftblAntigens'. Cannot insert duplicate key in object 'reftblAntigens'.The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint 'IX_reftblAntigens'. Cannot insert duplicate key in object 'reftblAntigens'.The statement has been terminated....
Is there somewhere else I should be looking to handle this sort of thing? I thought using the databound controls would make life easier but I'm actually finding it more of a pain than coding everything myself.
View 4 Replies
View Related
Jan 16, 2008
Greetings everyone, I am attempting to build my first application using Microsofts Sql databases. It is a Windows Mobile application so I am using Sql Server Compact 3.5 with Visual Studio 2008 Beta 2. When I try and insert a new row into one of my tables, the app throws the error message shown in the title of this topic.
'((System.Exception)($exception)).Message' threw an exception of type 'System.NotSupportedException'
My table has 4 columns (i have since changed my FavoriteAccount datatype from bit to Integer)
http://i85.photobucket.com/albums/k71/Scionwest/table.jpg
Account type will either be "Checking" or "Savings" when a new row is added, the user will select what they want from a combo box.
Next is a snap shot of my startup form.
http://i85.photobucket.com/albums/k71/Scionwest/form.jpg
Where it says "Favorite Account: None" in the top panel, I am using a link label. When a user clicks "None" it will go to a account creation wizard, and set the first account as it's primary/favorite. As more accounts are added the user can select which will be his/her primary/favorite. For now I am just creating a sample account when the label is clicked in an attempt to get something working. Below is the code used.
private void lnkFavoriteAccount_Click(object sender, EventArgs e)
{
FinancesDataSet.BankAccountRow account = this.financesDataSet.BankAccount.NewBankAccountRow();
account.Name = "MyBank Checking Account";
account.AccountType = "Checking";
account.Balance = Convert.ToDecimal("15.03");
account.FavoriteAccount = 1;//datatype is an integer, I have changed it since I took the screenshot.
financesDataSet.BankAccount.Rows.Add(account);
//The next three lines where added while I was trying to get this to work.
//I don't know if I really need them or not, I receive the error regardless if these are here or not.
this.bankAccountTableAdapter1.Update(financesDataSet);
this.financesDataSet.AcceptChanges();
refreshDatabase();
}
the refreshDatabase() code is here:
private void refreshDatabase()
{
this.bankAccountTableAdapter1.Fill(this.financesDataSet.BankAccount);
//Aquire a count of accounts the user has
int numAccounts = financesDataSet.BankAccount.Count;
//Loop through each account and see which one is the primary.
for (int num = 0; num != numAccounts; num++)
{
//Works ok in frmMain_Load, but when my lnkFavoriteAccount_click calls this, it throws the error.
if (this.financesDataSet.BankAccount[num].FavoriteAccount == 1)
{
//Display the primary account on our home page. User can click the link label & be taken to their account register.
this.lnkFavoriteAccount.Text = this.financesDataSet.BankAccount[num].Name.ToString();
this.lnkFavoriteFunds.Text = this.financesDataSet.BankAccount[num].Balance.ToString();
break;
}
}
}
and my form_load code
private void frmMain_Load(object sender, EventArgs e)
{
refreshDatabase();
}
So, when I click on the lnkFavoriteAccount label, and my new row gets added, the app stops at the following line in my DataSet.Designer
[global:ystem.Diagnostics.DebuggerNonUserCodeAttribute()]
public byte FavoriteAccount {
get {
try {
return ((byte)(this[this.tableBankAccount.FavoriteAccountColumn]));
}
catch (global:ystem.InvalidCastException e) {
//Stops at the following line, this error was caused by 'if (this.financesDataSet.BankAccount[num].FavoriteAccount == 1)'
throw new global:ystem.Data.StrongTypingException("The value for column 'FavoriteAccount' in table 'BankAccount' is DBNull.", e);
}
}
set {
this[this.tableBankAccount.FavoriteAccountColumn] = value;
}
}
I have no idea what I am doing wrong, all of the code I used I retreived from Microsofts help documentation included with VS2008. I have tried used my TableAdapter.Insert() method and it still failed when it got to
if (this.financesDataSet.BankAccount[num].FavoriteAccount == 1)
in my refreshDatabase() method it still failed.
When I look, the data has been added into the database, it's just when I try to retreive it now, it bails on me. Am I retreiving the information wrong?
Thanks for any help you guys can offer.
Johnathon
View 1 Replies
View Related
Jan 31, 2007
Hi,
I got an strange problem with one of my packages.
When running the package in VisualStudio it runs properly, but if I let this package run as part of an SQL-Server Agent job, I got the message "The script threw an exception: Exception of type 'System.OutOfMemoryException' was thrown." on my log and the package ends up with an error.
Both times it is exactly the same package on the same server, so I don't know how the debug or even if there is anything I need to debug?
Regards,
Jan
View 2 Replies
View Related
May 22, 2005
Hi there,
I have decided to move all my transaction handling from asp.net to stored procedures in a SQL Server 2000 database. I know the database is capable of rolling back the transactions just like myTransaction.Rollback() in asp.net. But what about exceptions? In asp.net, I am used to doing the following:
<code>Try 'execute commands myTransaction.Commit()Catch ex As Exception Response.Write(ex.Message) myTransaction.Rollback()End Try</code>Will the database inform me of any exceptions (and their messages)? Do I need to put anything explicit in my stored procedure other than rollback transaction?
Any help is greatly appreciated
View 3 Replies
View Related
Apr 21, 2006
1) We are writing a custome Source component for Oracle with OCI calls, Could some one please let me know how to Enable Error Handling for the Same,
2) Is it possible to write Custome Error Handeling Component for SSIS? if yes could you please help me on how to write it.
Thanks in advance.
View 1 Replies
View Related
Feb 25, 2006
Hi,
I am executing script like this. How to check for the errors if "master..xp_cmdshell @bcpCommand" fails. Is there any way to verify that BCP is completed successfully
DECLARE @FileName varchar(50),
@bcpCommand varchar(2000)
SET @FileName = 'E:TestBCPOut.txt'
SET @bcpCommand = 'bcp "SELECT * FROM pubs1..authors ORDER BY au_lname" queryout "'
SET @bcpCommand = @bcpCommand + @FileName + '" -c -U -P'
EXEC master..xp_cmdshell @bcpCommand
Thanks in Advance,
View 10 Replies
View Related
Jun 29, 2006
Guys, I need your help on this one. I have a problem here. There is an exception on my conn.Open.
It said that "SQL Exception was unhandled by user code. Cannot open database requested in login 'MUSIC STORE'. Login fails.Login failed for user 'IT785P13student'."
Does anyone have any idea what this means?
View 2 Replies
View Related
Nov 19, 2006
I downloaded a web site from internet and tried to open it in visual web developer express edition but it gave an error and the code and the error was:
CODE- Return CType(Me.GetPropertyValue("Theme"),String)
ERROR -An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
An answer will be very good for me
View 1 Replies
View Related
May 25, 2007
Hi - I am new to *** forum and could really use some help. I am trying to insert the following values in an sql server 2003 database and I get an exception labeled:System.Data.SqlClient.SqlException: Incorrect syntax near ')'. Source:Line 91: connection.Open();Line 92: int numRowsAffected;Line 93: numRowsAffected= command.ExecuteNonQuery();Line 94: connection.Close();Line 95: Stack Trace:[SqlException (0x80131904): Incorrect syntax near ')'.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +95 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +82 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +346 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +3244 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +186 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +1121 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +334 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +407 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +149 _Default.Button1_Click(Object sender, EventArgs e) in e:Hampton DirectWebsitesLunchOrderRestaurantEditor.aspx.cs:93 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +96 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +116 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +31 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +32 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +72 Source Code: SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["LunchOrderTestDBConnectionString1"].ToString());SqlCommand command = new SqlCommand("INSERT INTO Restaurants (Name,Address1,Phone,Fax,Menu_Pages,) VALUES ( @Name,@Address1,@Phone,@Fax,@Menu_Pages)", connection); //@MenuSqlParameter param0 = new SqlParameter( "@Name", SqlDbType.VarChar,50 );param0.Value = TextBox1.Text;command.Parameters.Add( param0 );SqlParameter param1 = new SqlParameter("@Address1", SqlDbType.VarChar, 50);param1.Value = TextBox2.Text;command.Parameters.Add(param1);SqlParameter param2 = new SqlParameter("@Phone", SqlDbType.VarChar, 50);param2.Value = TextBox3.Text;command.Parameters.Add( param2 );SqlParameter param3 = new SqlParameter("@Fax", SqlDbType.VarChar, 50);param3.Value = TextBox5.Text;command.Parameters.Add(param3);//SqlParameter param4 = new SqlParameter("@Menu", SqlDbType.Image);//param4.Value = byte_data;//command.Parameters.Add(param4);SqlParameter param5 = new SqlParameter("@Menu_Pages", SqlDbType.Int, 50);param5.Value = Int32.Parse(TextBox6.Text);command.Parameters.Add(param5);connection.Open();int numRowsAffected;numRowsAffected= command.ExecuteNonQuery();connection.Close();Thank You in advance for all help and suggestions!
View 1 Replies
View Related
Jul 23, 2007
I am trying to insert data into a table and I am getting a SQL Exception: System.Data.SqlClient.SqlException {"Incorrect syntax near 'nvarchar'. Must declare the scalar variable "@"."}
This is my subroutine that is executed once the submit button is clicked.
Please advise. Thank you for your time!
1 Protected Sub SubmitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
2 Dim CMLdataSource As New SqlDataSource()
3 Dim commStr As String
4
5 CMLdataSource.ConnectionString = ConfigurationManager.ConnectionStrings("CMLConnectionString1").ToString()
6
7 CMLdataSource.InsertCommandType = SqlDataSourceCommandType.Text
8 commStr = "INSERT INTO SCOs (ProjCode, SCONum, SCORev, DateIssued, DateAssigned, ProjName, CSCI, Description, [IDENT NUMBER], REV, PPRChgAbstract, SourceCodeChange, DocumentChange, "
9 commStr = commStr & "DocChangeRev, ChangeNoticeNum, TechInvest, CDMRep, TestEngineer, SQE, SCCBChair, CDMLibrarian, ECPNum, [CLASS 1], [CLASS 2]) "
10 commStr = commStr & "VALUES (@ProjCode, @SCONum, @SCORev, @DateIssued, @DateAssigned, @ProjName, @CSCI, @Description, @[IDENT NUMBER], @REV, @PPRChgAbstract, @SourceCodeChange, @DocumentChange, "
11 commStr = commStr & "@DocChangeRev, @ChangeNoticeNum, @TechInvest, @CDMRep, @TestEngineer, @SQE, @SCCBChair, @CDMLibrarian, @ECPNum, @[CLASS 1], @[CLASS 2])"
12
13 CMLdataSource.InsertCommand = commStr
14
15 CMLdataSource.InsertParameters.Add("ProjCode", CodeList.Text)
16 CMLdataSource.InsertParameters.Add("SCONum", scoNum.Text)
17 CMLdataSource.InsertParameters.Add("SCORev", ScoRevTextBox.Text)
18 CMLdataSource.InsertParameters.Add("DateIssued", DateIssuedTextBox.Text)
19 CMLdataSource.InsertParameters.Add("DateAssigned", DateAssigTextBox.Text)
20 CMLdataSource.InsertParameters.Add("ProjName", ProjectList.Text)
21 CMLdataSource.InsertParameters.Add("CSCI", CsciTextBox.Text)
22 CMLdataSource.InsertParameters.Add("Description", MediaTextBox.Text)
23 CMLdataSource.InsertParameters.Add("[IDENT NUMBER]", IDTextBox.Text)
24 CMLdataSource.InsertParameters.Add("REV", RevTextBox.Text)
25 CMLdataSource.InsertParameters.Add("PPRChgAbstract", PPRTextBox.Text)
26 CMLdataSource.InsertParameters.Add("SourceCodeChange", SourceCodeTextBox.Text)
27 CMLdataSource.InsertParameters.Add("DocumentChange", DocTitleTextBox.Text)
28 CMLdataSource.InsertParameters.Add("DocChangeRev", RevLetterTextBox.Text)
29 CMLdataSource.InsertParameters.Add("ChangeNoticeNum", ChangeNoticeTextBox.Text)
30 CMLdataSource.InsertParameters.Add("TechInvest", TechInvestTextBox.Text)
31 CMLdataSource.InsertParameters.Add("CDMRep", SwCdmTextBox.Text)
32 CMLdataSource.InsertParameters.Add("TestEngineer", TestEngTextBox.Text)
33 CMLdataSource.InsertParameters.Add("SQE", SqeTextBox.Text)
34 CMLdataSource.InsertParameters.Add("SCCBChair", SccbChairTextBox.Text)
35 CMLdataSource.InsertParameters.Add("CDMLibrarian", CdmLibTextBox.Text)
36 CMLdataSource.InsertParameters.Add("ECPNum", EcpNumTextBox.Text)
37 CMLdataSource.InsertParameters.Add("[Class 1]", Class1TextBox.Text)
38 CMLdataSource.InsertParameters.Add("[Class 2]", Class2TextBox.Text)
39
40 Dim RowsAffected As Integer = 0
41
42 Try
43 RowsAffected = CMLdataSource.Insert()
44 Catch ex As Exception
45 CMLdataSource = Nothing
46 Server.Transfer("dberror.aspx")
47 Finally
48 CMLdataSource = Nothing
49 End Try
50
51
52 If RowsAffected <> 1 Then
53
54 Server.Transfer("dbError.aspx")
55
56 Else
57 Server.Transfer("newConfirm.aspx")
58
59 End If
60
61
62 End Sub
View 16 Replies
View Related
Aug 30, 2007
Could somebody please tell me what is wrong with this SQL Statement. I'm trying to run it in SQL Server 2000, and keep getting the error:
System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'GROUP'
but as far as I can see, there isn't anything wrong near "GROUP"..." SELECT b.ColorID, b.ColorName, " +
" MAX(a.ColorID) AS DesignerProductAvailability_ColorID, " +" MAX(a.Quantity) AS DesignerProductAvailability_Quantity, " +
" MAX(a.ProductID) AS DesignerProductAvailability_ProductID " +" FROM DesignerProductAvailability a " +
" INNER JOIN ColorList b " +" ON b.ColorID = DesignerProductAvailability_ColorID " +
" WHERE DesignerProductAvailability_ProductID = @ProductID AND " +" DesignerProductAvailability_Quantity > 0 " +
" ORDER BY b.ColorName ASC " +
" GROUP BY b.ColorName ";
Any help would be greatly appreciated. Thanks in advance!
View 13 Replies
View Related
Jun 9, 2008
I am passing the values to a class which has a method to insert the date into database. How to retrive this exception thrown in this method and disply to user.
View 10 Replies
View Related
Aug 17, 2000
We have load-balanced sql server mcs and users will be accessing all the time. We are maintaining user profiles in one mc. Here is the problem. We have a sp which reads profile from one particular mc always. If the mc is down, the sp does not fail gracefully. Instead it causes exception. Is there a way to access sql servers alternatively ie if one server is not responding read data from another sql?
View 1 Replies
View Related
Jul 14, 2004
Hi all,
I am using MSSQL Server 8.0 , and the driver jtds.jar to connect the database for SQL operation .
I can do all the sql operation .
But after the creation of a trigger for a table , I used the same java program to insert rows into table .
-------The java code I used ---------------------
String connectionString = "jdbc:jtds:sqlserver://localhost:1433/master";
try {
Class.forName(jdbcDriverClass);
Connection con = DriverManager.getConnection(connectionString,userN ame,password);
Statement st = con.createStatement();
String query = "insert into tabname values('11','ROBERT')";
st.executeUpdate(query);
} catch (Exception e) { e.printStackTrace(); }
-------------------------------------------------
and got the exception
////////////////////////////////////////////////////////
java.sql.SQLException: executeUpdate can't return a result set
at net.sourceforge.jtds.jdbc.TdsStatement.executeUpda te(Unknown Source)
////////////////////////////////////////////////////////
What will be the problem here ?
Is it bcos of any time out ?
Please help !!!
Thanks
View 3 Replies
View Related
Mar 12, 2007
I already added the the COM Component: Microsoft ADO ext. 2.8 for DLL and Security
Dim jro1 As JRO.JetEngine
jro1 = New JRO.JetEngine
jro1.CompactDatabase("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C: estDB.mdb;Jet OLEDB:Database Password=test", _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:Backup estDB.mdb;Jet OLEDB:Engine Type=4;Jet OLEDB:Database Password=test")
Error:
Retrieving the COM class factory for component with CLSID {DE88C160-FF2C-11D1-BB6F-00C04FAE22DA} failed due to the following error: 8007007e.
View 1 Replies
View Related
Apr 16, 2008
Hi there,
Can anyone help me in catching @@error value.
I have a stored procedure which return @@error value, I need to read that in my dataaccesslayer and act according to it.
how do I catch the return value from stored procedure in my dataaccesslayer.
if I am not wrong @@error return a bool value
Thanks in advance.
View 1 Replies
View Related
May 1, 2008
dear friends i am writng a store procedure to insert into a two table .table 1 data inserted but when i inserting into a table2 it have some error at that time table 1 data also want to delete.give suggestions
View 3 Replies
View Related
May 7, 2008
Hi All, Please help me out how to implement the locking in below scenarioReq - There are two tables Table1 & Table2 If I will insert in table1 then related data fields will be auto updated in table2 , similarly based on the data in table2 table1 data needs to be updated. Now the sync of table1 & table2 is working fine.My prob is we are handling the updation/insertion from the UI screens . Two separate screen for each table. When we have multiple user accessing the screens say - User1 updates table1 and User2 updates table2 then we need to implement the locking so that at one time one screen will allow updation in the table1 and hence table2.The other screen shouldnt allow updation in table2 and hence in table1.This is very common locking functionality ...but am not getting any way to implement it , Please advise.Srain.
View 1 Replies
View Related
Mar 25, 2006
Hello to all,
On my webPage I have Used one SQLDataSource to access DataBase. Now whenever some error occures it shows error page by default. I am not able to catch Errors and tackle in my way...
Furthermore in this new structure of accessing DataBase even I do not know where to write Try... Catch...
View 1 Replies
View Related