Best Practice Advice For Efficient SQL Connection Code

Feb 26, 2006

Hi,

I have an application which is similar to the following example

Private Sub Start()
For a as int16 = 1 to 300
lstResults.items.add(GetPriceFromItem(a))
Next
End Sub

Private Function GetPriceFromItem(byval item as int16) as String
'Connect to SQL
'Execute "SELECT Price FROM Table WHERE Item='" & item.tostring & "'"
'Close Database connection
'Return Price
End Function

I want to know if there is a more efficeint way of doing this, i.e. i'm concerned that the routine creates 300 SqlConnection instances, 300 open/closes and 300 queries

Would a better way be to connect to SQL once, get the entire table then do the 300 "lookups" locally somehow, perhaps put it all into a DataTable, but can you query a datatable in this way, or could you suggest another control.

Best Regards

Ben


 

 

View 7 Replies


ADVERTISEMENT

Best Practice Advice

Jan 16, 2008

Need the following question addressed, as it keeps coming up in our development meetings and has been creating a divide. Pease voice your opinion.

To keep it simple, we have Table1 which identifies several questions that are revised on a regular basis. One of it's columns is called "Revision Status". Within revision Status, we would like to identify the possible status of a question such as:

New Questions;
Revised;
Resubmit;
Inactive;
Active;

...as well as several more.

I'm of the mind to have these in a seperate table identified with a unique ID... call it StatusTable.

Such as:

1 New Questions;
2 Revised;
3 Resubmit;
4 Inactive;
5 Active;

However others feel, just use the "Revision Status" column and simply use the numbers "WITHOUT" a table or description. The developer documentation will tell the developer which number equals the description. ie the following would be found in the Revision Status column.

1
2
3
4
5


My mind says the above is ilogical. I would rather join and say in my statement:

WHERE StatusTable.Status = 'Inactive'

Where the other way would be

Where [Revision Status] = 4


I hope i'm not being thick-headed.

Please advise.

View 10 Replies View Related

Best Practice Advice Please

Jul 20, 2007



I'm looking for advice on the best way to stop stored procedures and CLR assemblies from being

copied from their originally installed server to a different server, for the same company or even copied

to another company.



Are there established ways for achieving this level of protection.



Also, I was hoping that encrypting stored procedures would be a 100% reliable way to stop

malicious copying of the code. But I have read that this is not the case. Any advice in this

area would also be appreciated.



Thanks

Steve

View 4 Replies View Related

Advice Needed On Best Practice

Nov 1, 2007



This message is similar to a previous post, but no one seems to have an answer to it so I thought I should try to solve my problem in another way.

I have to use a pass through query to access db2. I cannot get the four-part name to work.

I want to simplify things for the developers. I can't figure out how to make one stored procedure or view to handle all the columns the developers may need to filter by or return. Is the best practice to just make multiple views or stored procedures to in each database to handle each query needed?

View 1 Replies View Related

More Efficient Code

Dec 13, 2007

Hi all, I have the code listed below and feel that it could be run much more efficiently.  I run this same code for attrib2, 3, description, etc for a total of 21, so on each postback I am running a total of 21 different connections, i have listed only 3 of them here for the general idea.  I run this same code for update and for insert, so 21 times for each of them as well.  In fact if someone is adding a customer, after they hit the new customer button, it first runs 21 inserts of blanks for each field, then runs 21 updates for anything they put in fields, on the same records.  This is running too slow...  any ideas on how I can combine these??  We have 21 different entries for EVERY customer.  The Pf_property does not change, it is 21 different set entries, the only one that changes is the Pf_Value.
Try                Dim queryString As String = "select Pf_Value from CustomerPOFlexField where [Pf_property] = 'Attrib1' and [Pf_CustomerNo] = @CustomerNo"                Dim connection As New SqlClient.SqlConnection("connectionstring")                Dim command As SqlClient.SqlCommand = New SqlClient.SqlCommand(queryString, connection)                command.Parameters.AddWithValue("@CustomerNo", DropDownlist1.SelectedValue)                Dim reader As SqlClient.SqlDataReader                command.Connection.Open()                reader = command.ExecuteReader                reader.Read()                TextBox2.Text = Convert.ToString(reader("Pf_Value"))                command.Connection.Close()            Catch ex As SystemException                Response.Write(ex.ToString)            End Try
            Try                Dim queryString As String = "select Pf_Value from CustomerPOFlexField where [Pf_property] = 'Attrib1Regex' and [Pf_CustomerNo] = @CustomerNo"                Dim connection As New SqlClient.SqlConnection("connectionstring")                Dim command As SqlClient.SqlCommand = New SqlClient.SqlCommand(queryString, connection)                command.Parameters.AddWithValue("@CustomerNo", DropDownlist1.SelectedValue)                Dim reader As SqlClient.SqlDataReader                command.Connection.Open()                reader = command.ExecuteReader                reader.Read()                TextBox5.Text = Convert.ToString(reader("Pf_Value"))                command.Connection.Close()            Catch ex As SystemException                Response.Write(ex.ToString)            End Try
            Try                Dim queryString As String = "select Pf_Value from CustomerPOFlexField where [Pf_property] = 'Attrib1ValMessage' and [Pf_CustomerNo] = @CustomerNo"                Dim connection As New SqlClient.SqlConnection("connectionstring")                Dim command As SqlClient.SqlCommand = New SqlClient.SqlCommand(queryString, connection)                command.Parameters.AddWithValue("@CustomerNo", DropDownlist1.SelectedValue)                Dim reader As SqlClient.SqlDataReader                command.Connection.Open()                reader = command.ExecuteReader                reader.Read()                TextBox6.Text = Convert.ToString(reader("Pf_Value"))                command.Connection.Close()            Catch ex As SystemException                Response.Write(ex.ToString)            End Try
 Thanks,
Randy

View 2 Replies View Related

In-efficient SQL Code

Sep 7, 2000

Hey people

I'd be really grateful if someone can help me with this. Could someone explain the following:
If the following code is executed, it runs instantly:

declare @SellItemID numeric (8,0)
select @SellItemID = 5296979

SELECT distinct s.sell_itm_id
FROM stor_sell_itm s
WHERE (s.sell_itm_id = @SellItemID )

However, if I use this WHERE clause instead -

WHERE (@SellItemID = 0 OR s.sell_itm_id = @SellItemID)

- it takes 70 micro seconds. When I join a few more tables into the statement, the difference is 4 seconds!

This is an example of a technique I'm using in loads of places - I only want the statement to return all records if the filter is zero, otherwise the matching record only. I think that by using checking the value of the variable in the WHERE clause, a table scan is used instead of an index. This seems nonsensical since the variable is effectively a constant. Wrapping the entire select statement with an IF or CASE works, but when I've got 10 filters I'd have to 100 select statements.
I DON'T GET IT!! There must be a simple answer, HELP!!
Jo

PS this problem seems to occur both in 6.5 and 7.0

View 4 Replies View Related

SELECT. Need Advice. How Should I Code This?

Dec 4, 2006

Hello,I need a procedure to return the value of field [ContentHtml] given values for [ContentName] and [ContentCulture].In theory only one record will be found so only one [ContentHtml] value will be returned.If multiple records are found I want to return "#MultipleFound#".If no record is found I want to return "#NotFound#".In my .NET code I am executing a ExecuteScalar:  Dim Html As String = CType(command.ExecuteScalar, String)I believe I should use @@ROWCOUNT to do this.Could somebody explain to me how to integrate @@ROWCOUNT in my procedure code to achieve what I described?And should I do it this way or there is a better solution?My Procedure is as follows:    -- Define the procedure parameters  @ContentName NVARCHAR(100),  @ContentCulture NVARCHAR(5)AS-- Allows @@ROWCOUNT and the return of number of records when ExecuteNonQuery is usedSET NOCOUNT OFF;-- Declare and define ContentIdDECLARE @ContentId UNIQUEIDENTIFIER;SELECT @ContentId = ContentId FROM dbo.by27_Content WHERE ContentName = @ContentName-- Check if ContentId is Not NullIF @ContentId IS NOT NULL  BEGIN        -- Select localized content from by27_ContentLocalized     SELECT dbo.by27_ContentLocalized.ContentHtml    FROM dbo.by27_Content    INNER JOIN dbo.by27_ContentLocalized      ON dbo.by27_Content.ContentId = dbo.by27_ContentLocalized.ContentId      WHERE (dbo.by27_ContentLocalized.ContentCulture = @ContentCulture AND dbo.by27_Content.ContentName = @ContentName);   ENDThanks,Miguel

View 1 Replies View Related

Advice Needed: Where To Put ADO Code

Jan 5, 2007

I need some advice on a project that I am working on...
First, here is what I am trying to achieve:  A Web Form with two controls:  A DropDownList with two items added at design time (Fruits and Vegetables) and an empty ListBox.  When the user chooses a "category" from the DropDownList, the ListBox will be populated with a list of either "Fruits" or "Vegetables" retrieved from a SQL database.  (Note:  Since the data in the SQL database must be converted and formatted programatically, simply databinding the ListBox will not work here.)
I believe that I can do this with the following code (stolen from an MSDN article):'Create ADO.NET objects.
Private myConn As SqlConnection
Private myCmd As SqlCommand
Private myReader As SqlDataReader
Private results As String

'Create a Connection object.
myConn = New SqlConnection("Initial Catalog=Northwind;" & _
"Data Source=localhost;Integrated Security=SSPI;")

'Create a Command object.
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT FirstName, LastName FROM Employees"

'Open the connection.
myConn.Open()

myReader = myCmd.ExecuteReader()

'Concatenate the query result into a string.
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab & _
myReader.GetString(1) & vbLf
Loop
'Display results.
MsgBox(results)

'Close the reader and the database connection.
myReader.Close()
myConn.Close()
  Now here is the part that I am not sure about:  Is the FormLoad event the best place to put this code?  If I do, is this not a lot of overhead (creating, opening and closing a connection) everytime there is a page refresh/PostBack?   Would I be better off putting this code in the DropDownList SelectedIndexChanged event?  Although that seems like it could make the process of selecting a category take a fairly long time.
Finally, if the is a better way of doing this, I am certainly open to suggestions.
All advice is greatly appreciated.

View 1 Replies View Related

Pseudo Code Advice

Jul 20, 2005

My new employer is CMM Level 3. As part of the CMM/Personal SoftwareProcess, I am required to create pseudo code for my stored procedureand UDF design. Has anyone done this? If so, can anyone give me someadvice?

View 1 Replies View Related

Protecting Database From Code Stealing And Installer Advice

Aug 24, 2005

Dear GroupI'd be grateful if you can give me some advice on the following.An application I wrote uses an MSDE backend and I wonder whetherthere's a way (even for the system administrator) of not seeing ortracing stored procedure code, view and table designs?And I also wonder whether you can advise me on an installer thathandles MSDE and database setup during installation without too mucheffort but is still affordable < USD 1000.Any articles, resources, advice hints for these two topics are veryappreciated.Thank you very much for your help & efforts!Martin

View 3 Replies View Related

Advice On Importing Access Data Into MSSQL Table Using Code

Aug 2, 2004

Hi,

I'm about to embark on writing some code in perl or VBscript that automatically synchronises a constantly updated Access database with an MSSQL database.

I know MSSQL has an import tool built into Enterprise manager but I'm wondering if theres a stored procedure that does this?

The way I'm thinking of doing it is to read the all the access tables into separate hash arrays and then INSERTing them into the MSSQL database after checking for any duplicates. This all sounds a bit time consuming (there are a large number of tables) and processor intensive.

If anyones done anything like this before, I'd love to hear their views......!

Thanks!

View 9 Replies View Related

Windows Services And SQL Connection Best Practice?

Dec 26, 2007

When doing DB tasks from a Windows Service is it better to keep a connection open during the life of the service or is it better to open a connection every time you want to do something on the DB?

--Thanks

--PhB

View 1 Replies View Related

Advice Needed For Connection To DB2

Apr 20, 2006

I am writing a report in RS and my query is supposed to pull transactional records from a certain date (yesterday).

The table I am querying contains roughly 1.5 million records. This is on an AS400 dB2 system. Mostly I use ODBC with no problems, however this query ran for about two hours and was still running before I killed it.

I am thinking of using SSIS to copy the records into SQL. If I go this approach (which should be much faster), is there a way to just copy over differential records each day?

Or does anybody have any other suggestions? What is Linking a Server?

Thanks for the information. I am using SQL 2005

View 1 Replies View Related

Needed: User, Login, Connection Advice.

Mar 12, 2005

HI,
I'm still on the steep side of the learning curve with ASP.NET. I've looked through a number of threads on this forum, and have gotten pieces of the answer, but need help getting past a roadblock.

I haven't been able to get a simple test application to connect to the Pubs database loaded on my system running MSDE. The only control in the application is a WebDataForm created by the Wizard. Everything works well (even the Preview Data form the Data menu loads and displays the correct data), except when the form is viewed in a browser. Click the load button and an error:Login failed for user 'NT AUTHORITYNETWORK SERVICE'.

Similar stories are common on this forum, and I tried to address the problem. I'm quite sure it's a autherization or authentication problem. I have Windows Server 2003 (with IIS 6.0), VS.NET 03 and MSDE as the SQL server on the same box. The MSDE server is using Windows Security mode. I Created a new user called ASPNET on the Windows Server. I added a login to the SQL Server 'WinServerNameASPNET' using windows auth. Still get the same login failed message.

Is there something I'm missing? Do I have to add a new user to IIS?

For the record, what users/settings do I need to have in Windows, SQL-Server and IIS, get past this login problem.

Thanks for answering this basic question - one more time.

View 1 Replies View Related

Kindly Advice On How To Test Faulty Connection To Database?

Jun 2, 2008

Hello,
I have an asp.net application which connects to SQL Server 2005 database.
One out of 15 times (approx) the applicaiton does not make connection to the database and an exception is thrown.
I am not sure how to debug this. Should I write some code which can make connections in a loop to test how much stress the sever can handle?
Kindly suggest some ideas. Thanks.

View 3 Replies View Related

The AcquireConnection Method Call To The Connection Manager &&<Connection Name&&> Failed With Error Code 0xC020200

Feb 14, 2008

Hi All,
I am getting the following error if I am using the package "Transaction Option=Required" while running through Sql Job:
The AcquireConnection method call to the connection manager "<connection name>" failed with error code 0xC0202009.

while I running the SSIS package on BI environment, I am getting the following error:
[Connection manager "<connection name>"] Error: The SSIS Runtime has failed to enlist the OLE DB connection in a distributed transaction with error 0x8004D00A "Unable to enlist in the transaction.".

I know the alternative solution is to make the "Transaction Option=Supported", but in my case I have run the whole flow in a single transaction. I came to know that this has been fixed in the service pack1(ref. to http://support.microsoft.com/kb/914375). FYI.. some time it was running successful.

I have taken all the necessary step to run the SSIS package in a distributed transaction(like the steps for MSDTC) and also created the package flow in a sequence.

I was going through the link - http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=160340&SiteID=1 but all those didn't solve my problem.

If anyone can help me it will be great. or it is a bug in SSIS?

Thanks.
Jena

View 5 Replies View Related

SSPI Handshake Failed With Error Code 0x8009030c While Establishing A Connection With Integrated Security; The Connection Has Be

Mar 7, 2006

Hello, I have a sql 2005 server, and I am a developer, with the database on my own machine. It alwayws works for me but after some minutes the other developer cant work in the application

He got this error

Login failed for user ''. The user is not associated with a trusted SQL Server connection. [CLIENT: 192.168.1.140]

and When I see the log event after that error, it comes with another error.

SSPI handshake failed with error code 0x8009030c while establishing a connection with integrated security; the connection has been closed. [CLIENT: 192.168.1.140]

He has IIS5 and me too.

I created a user on the domain called ASPSYS with password, then in the IIS on anonymous authentication I put that user with that password, and it works, on both machines.



and in the connection string I have.

<add key="sqlconn" value="Data Source=ESTACION15;Initial Catalog=GescomDefinitiva;Integrated Security=SSPI; Trusted_Connection=true"/>

I go to the profiler, and I see that when he browses a page, the database is accesed with user ASPSYS, but when I browse a page, the database is accesed with user SElevalencia.

Thats strange.

The only way that the other developer can work again on the project is to restart the whole machine. He has windows xp profession, I have windows 2000.

If you want me to send logs please tellme



View 20 Replies View Related

The AcquireConnection Method Call To The Connection Manager Excel Connection Manager Failed With Error Code 0xC0202009

Mar 24, 2008

I am using SSIS 2005 on Windows 2003 server. Using Excel Source to dump the data for staging database.
I am getting following error while I execute it through BI studio's execute button.

Please help.

- Sachin

View 2 Replies View Related

The AcquireConnection Method Call To The Connection Manager Excel Connection Manager Failed With Error Code 0xC0202009

Mar 11, 2008

I have deployed my packages into Sql Server and I am using Configuration File. As my Data Source is Excel, I have changed the connection string during deployment with Server Path. But I am getting the following errors. Actually the File Exist in Path. May I know What is cause of the issue? Do I need to give any permission to execute the package.



SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "Excel Connection Manager" failed with error code 0xC0202009. There may be error messages posted before this with more information on why the AcquireConnection method call failed.



component "Excel Source Service Contract Upload" (1) failed validation and returned error code 0xC020801C.

One or more component failed validation.



There were errors during task validation.

DTS_E_OLEDBERROR, Error Code: 0x80004005 Source: "MS JET DB Engine" Description : Path is not valid


View 27 Replies View Related

Error: The AcquireConnection Method Call To The Connection Manager Excel Connection Manager Failed With Error Code 0xC0202009.

Dec 27, 2007

Hi,

I am working on SQL Server 2005 (x64) with Windows Server 2003 (x64) operating system. I am having a major issue in SSIS. Here is the detailed explanation of the issue :

I have an EXCEL file in 2003 / 2007 version. It contains some data. I want to import the data using SSIS into SQL Server 2005 (x64) database table. I have taken "EXCEL FILE SOURCE" and "SQL Server DESTINATION". It was failed on importing data. Surprisingly it works fine in SQL Server 2005 (x32). Can you please explain why it is NOT woking on (x64) ?

Here is the error code i am getting:

[Excel Source [1]] Error: The AcquireConnection method call to the connection manager "Excel Connection Manager" failed with error code 0xC0202009.

Appreciate your time and patience !!

Thanks

View 3 Replies View Related

How To Write The Code For Connection In C#.net

Jan 4, 2008

 what is the simple way of writing code for the connection  with sql server  in c# .net
could any one provideme with the code for the same ism not been able to understand the funda  of using class for the connection purpose
if any one knows plz let me know i am waiting

View 3 Replies View Related

What Wrong With My Connection Code?

Apr 19, 2005

Below is my connection code..
Public Class clsConnect
Public Shared Function getConnection () AS SQLConnection
Dim strConn As String = "Data Source=PPS_SERVER;" & _
"Initial Catalog=eCommunity;User ID=sa;Password=pps"
Dim DBConn As SqlConnection
DBConn = New SqlConnection(strConn)
DBConn.Open()
Return DBConn
End Function
 
However when i run the web this error was appeared. what possibility of this problem?
SQL Server does not exist or access denied.
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: SQL Server does not exist or access denied.Source Error:



Line 12: DBConn = New SqlConnection(strConn)
Line 13:
Line 14: DBConn.Open()
Line 15:
Line 16: return DBConn

View 2 Replies View Related

Code For GPRS Connection

May 4, 2008



can anyone please guide me how i can check whether the GPRS connection is active or not on windows mobile based application? whats the code for it? because i need to synchronize my data based on the status of GPRS connection.
thanks and regards
dhruvi

View 1 Replies View Related

Connection String Designer Code

May 2, 2008

I currently have the following code in my designer file
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="select Site_name, system_id, ASP_Archive, sitetimes,HPOV_ROC, UPPER(CircuitType) as CircuitType, QwestCircuit_ID, SiteConfig,Site_Nat, PVC_VCI from tblASPCustomerWan order by Asp_Archive asc"
UpdateCommand="UPDATE tblASPCustomerWan SET [Site_name] = @Site_name, [system_id] = @system_id, [ASP_Archive] = @ASP_Archive, [sitetimes] = @sitetimes, [HPOV_ROC] = @HPOV_ROC, [CircuitType] = @CircuitType, [QwestCircuit_ID] = @QwestCircuit_ID, [SiteConfig]= @SiteConfig, [Site_Nat]=@Site_Nat,[PVC_VCI]=@PVC_VCI"
ConnectionString="server=localhost;Trusted_Connection=yes;uid=portal_user;pwd=Cr@zyP@55w0rd;database=CusPortal_Staging" />
I would like the change the connection so it takes it value from System.Configuration.ConfigurationManager.AppSettings("appStrConnection"), how can i do that??

View 1 Replies View Related

How To Copy Connection String Code

Apr 19, 2008



hi,

i was able to succesfully configure my remote server over the internet and tried using express edition to connect to my remote server and everything when successful.

is there a way to copy that connection string used to connect to my remote server so as i wanted to create a project in vb using that connection string..

where can i find the connection string code used for my connection remotely ..

i am using express to connect to my sql server

thanks

View 4 Replies View Related

Referring To Sql Connection String In Web.config From Code Behind

May 15, 2007

Every time I move my project from my computer to the testing server I have to change the connection string references in the aspx side and in my code behind.
For the code behind I declared the SqlConnection string at the top of the code-behind page for both connection strings and comment out the one not in use. Obviously I then comment out the string not in use in the WebConfig as well.
Being superlatively lazy I always look for the easiest and quickest way to do most anything - connection strings included. Having to comment out strings twice brought rise to the question of whether I can refer to the connection string in the web.config file from the code-behind page. I'm sure it can be done, and I did a good amount of hunting around, but I couldn't find any examples of code that would do that.
Currently, as I said above, I have two connection strings declared at the top of my code-behind. Here's an example of one:Private sqlConn As New SqlConnection("Data Source=DATABASESERVER;Initial Catalog=DATABASE;User ID=USER;Password=PASSWORD")
 Then, I just use sqlConn as usual in my binding without having to "dim" it in every sub:sdaPersonnel = New SqlDataAdapter(strSqlPersonnel, sqlConn)
 Then there's the SqlConnections set up by the wizard on the aspx side:<asp:SqlDataSource ID="sqlDataSourcePayrollCompany" Runat="Server" ConnectionString="<%$ ConnectionStrings:DATABASECONNECTIONSTRING %>" ...>
 And for the connection in the web.config:<add name="DATABASECONNECTIONSTRING" connectionString="Data Source=DATABASESERVER;Initial Catalog=DATABASE;User ID=USER;Password=PASSWORD" providerName="System.Data.SqlClient" />
 So, what would be the code in the code-behind page to refer to the connection string in the web.config file?
Thanks!

View 2 Replies View Related

Using Web.config Connection Strings In Code Behind Files

Jul 2, 2007

in asp usually i have code behind files those .aspx.vb file.can i make use of connection strings in there? i am not really familiar with connection strings. actually shouldn't code behind files "simulate" code being in the .aspx file themselves? i seem to not able to share variables between them? 

View 2 Replies View Related

Error Code 0xC0202009 + Connection Password

Dec 15, 2005

Hi,

I have developed a .dtsx package than runs normally from my computer. When I import it on the server and assign it to a job it always fails.

I tried also to run it directly from the server (remote desktop) and also faild. I exported the dtsx file on server and refresh the db connections and after that workd fine from the server.

Another work-around was to use windows authentication. Then runs normally from the server.

It seems that connection password is lost when importing the report on server. (The import is done in MSDB not in the filesystem)

But I can not design all the jobs on the server (work-around A) or use windows authentication (work-around B)

What is the problem and what can I do?

I have also played around with "save sensitive information" but with no results.

Thanks

View 10 Replies View Related

Connection.close Returns A 91 Error Code...

Nov 22, 2006

I have the next code in my proyect:

If CurrentProject.IsConnected Then
MsgBox "Base ya Conectada.Procedemos a cerrarla primero", vbOKOnly
If SQLConexion.State = adStateOpen Then SQLConexion.Close
SQLConexion.Close
End If
SQLConexion.Open SQLSentencia
AbreConexionSQLSERVER = 0

If I detect that the connection is opened while I am initializazing varriables, I want to close always the connection and then begins my aplicattion always opening the connection, but it always returns a error 91..

suggestions?

View 1 Replies View Related

Connection String And Permission Errors In The CLR Code

Feb 28, 2008

I have written a CLR function in C# to access a sql server different from the current server where I have deplyed the assembly.


DataSet ds = new DataSet();





SqlCommand sqlCmd = new SqlCommand();

sqlCmd.CommandType = CommandType.StoredProcedure;

string connString = "Data Source=SQLSERVER;Initial Catalog=DATABASE;User ID=userid;Password=password;";

SqlConnection sqlConn = new SqlConnection(connString);

sqlCmd.Connection = sqlConn;

sqlConn.Open();

try

{

SqlDataAdapter sda = new SqlDataAdapter();

sqlCmd.CommandText = "StoredProcedureName";

sqlCmd.Parameters.Add("@Param1", SqlDbType.VarChar);

sqlCmd.Parameters["@Param1"].Value = sParam1;

sda.SelectCommand = sqlCmd;

sda.Fill(ds);

}

finally

{

sqlConn.Close();

}

return ds;

I was getting the following error

"Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."

so I tried doing the following


SqlClientPermission pSql = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);

pSql.Assert();



and then I get this error


"Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."


Any idea how to remedy this ?

Thanks in advance
- Kan

View 4 Replies View Related

Code For Connection String Using Sql Server 2000 As Backend With Asp.net 1.1 Along With Vb.net

Apr 15, 2008

Hi all,
Please help me for the code of connectivity
it was working fine,but,when i hav written code for validation for id n password,its showing error as
Violation of PRIMARY KEY constraint 'PK_Login'. Cannot insert duplicate key in object 'login_detail'. The statement has been terminated.
 Here is my code given below.
 Please help me
Imports System
Imports System.IO
Imports System.Xml
Imports System.Text
Imports System.Security.Cryptography
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Data
Imports System.Data.SqlClientPublic Class WebForm1
Inherits System.Web.UI.Page#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End SubProtected WithEvents txtUser As System.Web.UI.WebControls.TextBox
Protected WithEvents txtPwd As System.Web.UI.WebControls.TextBoxProtected WithEvents btnSubmit As System.Web.UI.WebControls.Button
Protected WithEvents lblError As System.Web.UI.WebControls.Label
'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End RegionPrivate Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
 Dim objConn As SqlClient.SqlConnection
Dim ds As New DataSetDim m_strConnection As String = "server=172.16.152.17;Database=Trial;UID=abhi_Asset4;PWD=L!nux001;Connect Timeout=100"objConn = New SqlClient.SqlConnection
objConn.ConnectionString = m_strConnection
objConn.Open()
Dim strSQL As String
strSQL = "insert into login_detail(UserID,Password) values('" + txtUser.Text + "','" + txtPwd.Text + "')"Dim objCommand As SqlClient.SqlCommandobjCommand = New SqlClient.SqlCommand(strSQL, objConn)
objCommand.CommandText = strSQL
objCommand.ExecuteNonQuery()
objConn.Close()
 
 
 
 
End SubPrivate Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
If (txtUser.Text.Trim() = "") Then
lblError.Text = "UserID should not be blank"
ElseIf (Convert.ToInt32(txtUser.Text.Length) < 5) Then
lblError.Text = "UserID length must be more than 5"
ElseIf (Convert.ToInt32(txtUser.Text.Length) > 20) Then
lblError.Text = "UserID length must not be greater than 20"
ElseIf (txtPwd.Text.Trim() = "") Then
lblError.Text = "Password should not be blank"
ElseIf (Convert.ToInt32(txtPwd.Text.Length) < 5) Then
lblError.Text = "Password length must be more than 5"
ElseIf (Convert.ToInt32(txtPwd.Text.Length) > 20) Then
lblError.Text = "Password length must not be greater than 20"
Else
Server.Transfer("Success.aspx")
End IfEnd Sub
End Class
 
 

View 1 Replies View Related

Ssis Oledb Connection Error Code: 0x80040E21.

Jan 25, 2007

howdy,
i have a sqlserver2005 ssis package which connects to a mysql webserver to upload data. i am connecting via mysql oledb connection and am able to test connect ok through the oledb connection manager. However in my ole db destination editor i get an 0x80040E21 error when trying to preview a table . The full error is :

Error at Data Flow Task [Destination - Query [70]]: An OLE DB error has occurred. Error code: 0x80040E21.

Error at Data Flow Task [Destination - Query [70]]: Opening a rowset for "INFORMATION_SCHEMA.address_book" failed. Check that the object exists in the database.
------------------------------
ADDITIONAL INFORMATION:

Exception from HRESULT: 0xC02020E8 (Microsoft.SqlServer.DTSPipelineWrap)

I can see all the tables in the drop down box in connection manager. This has been driving me nuts for the last 3 days! I have tried changing some of the security connection settings to no avail, (although i am not sure on what these do).I have also tried setting up as an odbc connection using script components but had memory errors after copying several hundred records and the package just hangs. I can go into this in more detail however i dont think they are related issues and i would prefer oledb as i dont have to script my data transfer.

any help much much appreciated.

thanks

View 3 Replies View Related

Loosing Database Connection When Device Power-off (native Oledb Code)

Jul 12, 2006

Hi,

I experienced this problems on both Windows Mobile 2003 SE and Windows Mobile 5.0.

Its native development (c++, oledb, atl and mfc).



It's quite simple to reproduce...

1. open a database

2. open a rowset on table A (whatever, valid of course and with both IOpenRowset and ICommandText), read datas and close rowset

3. power off

4. power on

5. try step 2 with another table (failed on openrowset with error 0x80004005) or try table A (sometimes working because of cached memory, sometims failed on Read Datas).

6. being stuck ;-)



Our work-around was, in case we loose our connection (identified by error 0x80004005 on openrowset), we close it and re-open database... ugly for sure, but working.



What I'm looking now is to use some kind of "detection method" like what people in .Net develoment are using "if ConnectionState.Open <> ...) for reopening my database only on demand...



Thanks in advance for any hints,
Fabien.

View 5 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved