Async Database Access On Single SqlConnection
Mar 14, 2008
Hi,
I'm currently writing an windows application where a LOT of threads connect to database and send small amount of data.
I'd like to ask you for the best approach to do it.
The way it's implemented now:
Each therad uses it's own SqlConnection sends few bytes of data and closes the SqlConnection. Each thread has to send initliazation data which i guess is few times bigger then accual data and then it has to close connestion even more bytes that could be avoided are sent.
The way i'd like it to be:
There is only one SqlConnection all therads share it. It's opened when the applications starts and closed when it's application is closed. This way i send initialization data only once and by doing this i can save some bandwidth.
Does SqlConnection operations has to be in critical area? Can it be used pararelly by many threads? Maby there is better way to do it? Is it recomended to close SqlConnection as soon as possible after query? If so why?
Thanks in advance,
Erxar
View 1 Replies
ADVERTISEMENT
Apr 4, 2014
I have a small project for educational institutuin online examination. But 500 students has to login and save their answers.. Is it possible to have in sql server 2008 for 500 login can access a single database & can save?
View 4 Replies
View Related
Aug 23, 2004
Dear All,
I want my SQL database to be accessed always in a single user mode through my application. How can I do this ?
Thanks in advance.
Sushma
View 5 Replies
View Related
Feb 21, 2006
Hi,I have a SqlConnection object with connection string, "Data Source=server1;Initial Catalog=CDCollection;User Id=joe;Password=11111."For User ID, I created a new user "joe" in the Management Studio.I tried to use this user, but sqlconnection threw an exception stating access was denied.I noticed that SQL Server 2005 has user accounts that you can create for the server and for the database, but I am confused by this. How can a create a non-sa user account that I can give to the SQLConnection object that will work? Do I need to create a user for the server and the same user for the database CDCollection? I am not all familiar with SQL Server administration.Any help or leads would be appreciated.
View 3 Replies
View Related
Feb 14, 2008
Hi all,
In the VB 2005 Express, I can get the SqlConnection and ConnectionString of a Database "shcDB" in the Object Explorer of SQL Server Management Studio Express (SSMSE) by the following set of code:
///--CallshcSpAdoNetVB2005.vb--////
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Public Class Form1
Public Sub InsertNewFriend()
Dim connectionString As String = "Data Source=.SQLEXPRESS;Initial Catalog=shcDB;Integrated Security=SSPI;"
Dim connection As SqlConnection = New SqlConnection(connectionString)
Try
connection.Open()
Dim command As SqlCommand = New SqlCommand("sp_insertNewRecord", connection)
command.CommandType = CommandType.StoredProcedure
.......................................
etc.
///////////////////////////////////////////////////////
If the Database "shcDB" and the Stored Procedure "sp_inertNewRecord" are in the Database Explorer of VB 2005 Express, I plan to use "Data Source=local" in the following code statements to get the SqlConnection and ConnectionString:
.........................
........................
Dim connectionString As String = "Data Source=local;Initial Catalog=shcDB;Integrated Security=SSPI;"
Dim connection As SqlConnection = New SqlConnection(connectionString)
Try
connection.Open()
Dim command As SqlCommand = New SqlCommand("sp_insertNewRecord", connection)
command.CommandType = CommandType.StoredProcedure
........................
etc.
Is the "Data Source=local" statement right for this case? If not, what is the right code statement for my case?
Please help and advise.
Thanks,
Scott Chang
View 6 Replies
View Related
Oct 18, 2007
Hi all,
In the Object Explorer of my SQL Server 2005 Management Studio Express, I do not have €˜Northwind€™ Database installed yet. I executed the following source code (that was copied from a book) in my VB 2005 Express:
/////////////////////----Form9.vb----//////////////////////////
Imports System.Data.SqlClient
Imports System.Data
Public Class Form9
Dim cnn1 As New SqlConnection
Private Sub Form5_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Compute top-level project folder and use it as a prefix for
'the primary data file
Dim int1 As Integer = InStr(My.Application.Info.DirectoryPath, "bin")
Dim strPath As String = Microsoft.VisualBasic.Left(My.Application.Info.DirectoryPath, int1 - 1)
Dim pdbfph As String = strPath & "northwnd.mdf"
Dim cst As String = "Data Source=.sqlexpress;" & _
"Integrated Security=SSPI;" & _
"AttachDBFileName=" & pdbfph
cnn1.ConnectionString = cst
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Create a command to create a table
Dim cmd1 As New SqlCommand
cmd1.CommandText = "CREATE TABLE FromExcel (" & _
"FirstName nvarchar(15), " & _
"LastName nvarchar(20), " & _
"PersonID int Not Null)"
cmd1.Connection = cnn1
'Invoke the command
Try
cnn1.Open()
cmd1.ExecuteNonQuery()
MessageBox.Show("Command succeeded.", "Outcome", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
cnn1.Close()
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'Create a command to drop a table
Dim cmd1 As New SqlCommand
cmd1.CommandText = "DROP TABLE FromExcel"
cmd1.Connection = cnn1
'Invoke the command
Try
cnn1.Open()
cmd1.ExecuteNonQuery()
MessageBox.Show("Command succeeded.", "Outcome", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
cnn1.Close()
End Try
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
'Declare FromExcel Data Table and RowForExcel DataRow
Dim FromExcel As New DataTable
Dim RowForExcel As DataRow
FromExcel.Columns.Add("FirstName", GetType(SqlTypes.SqlString))
FromExcel.Columns.Add("LastName", GetType(SqlTypes.SqlString))
FromExcel.Columns.Add("PersonID", GetType(SqlTypes.SqlInt32))
'Create TextFieldParser for CSV file from spreadsheet
Dim crd1 As Microsoft.VisualBasic.FileIO.TextFieldParser
Dim strPath As String = _
Microsoft.VisualBasic.Left( _
My.Application.Info.DirectoryPath, _
InStr(My.Application.Info.DirectoryPath, "bin") - 1)
crd1 = My.Computer.FileSystem.OpenTextFieldParser _
(My.Computer.FileSystem.CombinePath(strPath, "Book1.csv"))
crd1.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
crd1.Delimiters = New String() {","}
'Loop through rows of CSV file and populate
'RowForExcel DataRow for adding to FromExcel
'Rows collection
Dim currentRow As String()
Do Until crd1.EndOfData
Try
currentRow = crd1.ReadFields()
Dim currentField As String
Dim int1 As Integer = 1
RowForExcel = FromExcel.NewRow
For Each currentField In currentRow
Select Case int1
Case 1
RowForExcel("FirstName") = currentField
Case 2
RowForExcel("LastName") = currentField
Case 3
RowForExcel("PersonID") = CInt(currentField)
End Select
int1 += 1
Next
int1 = 1
FromExcel.Rows.Add(RowForExcel)
RowForExcel = FromExcel.NewRow
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
Loop
Try
cnn1.Open()
Using sqc1 As SqlBulkCopy = New SqlBulkCopy(cnn1)
sqc1.DestinationTableName = "dbo.FromExcel"
sqc1.WriteToServer(FromExcel)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
cnn1.Close()
End Try
'Read the FromExcel table and display results in
'a message box
Dim strQuery As String = "SELECT * " & _
"FROM dbo.FromExcel "
Dim str1 As String = ""
Dim cmd1 As New SqlCommand(strQuery, cnn1)
cnn1.Open()
Dim rdr1 As SqlDataReader
rdr1 = cmd1.ExecuteReader()
Try
While rdr1.Read()
str1 += rdr1.GetString(0) & ", " & _
rdr1.GetString(1) & ", " & _
rdr1.GetSqlInt32(2).ToString & ControlChars.CrLf
End While
Finally
rdr1.Close()
cnn1.Close()
End Try
MessageBox.Show(str1, "FromExcel")
End Sub
End Class
///////////////////////////////////////////////////////////////////////
This is Part 1 (The length of input exceeds 50000 characters). Part 2 will be posted in this site shortly.
View 4 Replies
View Related
Apr 23, 2008
hello my friend.
could i unbound sqlconnection than database name(Initial Catalog)?
please help me in ADO.NET.
thanks.
View 1 Replies
View Related
Dec 8, 2003
I'm hoping someone can explain to me exactly what the SQLConnection.Open() method does, especially when the database is stopped. I'm trying to include some error processing in my program, specifically to ensure the database is up and running. But even with the database stopped, the Open() statement works fine. Later, when I try to read from the database, I get the error. I'd like to stop it before it gets any further. Why is the Open() statement "working" even with the database stopped?
View 6 Replies
View Related
Jan 25, 2001
In SQL Server 7.0 there was option that allows you to set 'MAX async io', but it no longer available in SQL 2000.
Does anyone know why this option is not available or did Microsoft replace this function with something else?
Thank You,
John
View 1 Replies
View Related
Jan 25, 2001
In SQL Server 7.0 there was option that allows you to set 'MAX async io', but it no longer available in SQL 2000.
Does anyone know why this option is not available or did Microsoft replace this function with something else?
Thank You,
John
View 1 Replies
View Related
Feb 10, 2000
SQL7 SP1 NT4 SP5
Hi.
Very long story and I will not bore you with it. What I need to do is call a stored procedure and from within that stored procedure, initiate other sp and get out before those other sp are finished running.
I know I can execute a job but my volume would be about 1 job per second with a life of 2-5 seconds. So in a very short period of time, I can stack up a large volume of jobs.
Anyone have any better ideas ?
Help Please !@!!
Craig Somberg
csomberg@stageone.com
View 2 Replies
View Related
Nov 21, 2006
Hello Everybody,
In the past few days I try to work with SQL Mobil and Replication.
And now I have a big problem.
When the replication ist running in my little application the pda-user wants not stop there working. So I try to implement some routines of code that I find in this onlinearticle: http://msdn2.microsoft.com/en-us/library/2ysxae29.aspx
The codes workes fine as long I don't start another SQL Task. When I start either (Select, Insert, Update or Delete) Statement the Database crash with errormessage: "The database file may be corrupted. Run the repair utility...
Can anyone give me a tip what I must do to fix this problem.
Many Thanks
Markus
View 1 Replies
View Related
Sep 1, 2006
Hi Folks,
I've found a pretty good code example on http://www.dotnetfun.com for a Asynchronous Trigger.
I've parsed through the Code, to understand how to wirte my own Async Trigger with a Service Broker, but the Code isn't working! It seems that the stored procedure don't receive the messages in the queue, but the queue get's filled.
MessageType
CREATE MESSAGE TYPE myMsgXML
VALIDATION = WELL_FORMED_XML;
Contract
CREATE CONTRACT myContractANY
(myMsgXML SENT BY ANY)
Queue
CREATE QUEUE myQueue
WITH STATUS = ON,
RETENTION = ON,
ACTIVATION
(
STATUS = ON,
PROCEDURE_NAME = sp_myServiceProgram,
MAX_QUEUE_READERS = 5,
EXECUTE AS SELF
)
Service
CREATE SERVICE myService ON QUEUE myQueue (myContractANY)
Procedure (greped from http://www.dotnetfun.com/)
CREATE PROC sp_myServiceProgram
AS
-- This procedure will get triggered automatically
-- when a message arrives at the
-- Let's retrieve any messages sent to us here:
DECLARE @XML XML,
@MessageBody VARBINARY(MAX),
@MessageTypeName SYSNAME,
@ID INT,
@COL2 VARCHAR(MAX);
DECLARE @Queue TABLE (
MessageBody VARBINARY(MAX),
MessageTypeName SYSNAME);
WHILE (1 = 1)
BEGIN
WAITFOR (
RECEIVE message_body, message_type_name
FROM myQueue INTO @Queue
), TIMEOUT 5000;
-- If no messages exist, then break out of the loop:
IF NOT EXISTS(SELECT * FROM @Queue) BREAK;
DECLARE c_Test CURSOR FAST_FORWARD
FOR SELECT * FROM @Queue;
OPEN c_Test;
FETCH NEXT FROM c_Test
INTO @MessageBody, @MessageTypeName;
WHILE @@FETCH_STATUS = 0
BEGIN
-- Let's only deal with messages of Message Type
-- myMsgXML:
IF @MessageTypeName = 'myMsgXML'
BEGIN
SET @XML = CAST(@MessageBody AS XML);
-- Now let's save the XML records into the
-- historical table:
INSERT INTO tblDotNetFunTriggerTestHistory
SELECT tbl.rows.value('@ID', 'INT') AS ID,
tbl.rows.value('@COL2', 'VARCHAR(MAX)') AS COL2,
GETDATE() AS UPDATED
FROM @XML.nodes('/inserted') tbl(rows);
END
FETCH NEXT FROM c_Test
INTO @MessageBody, @MessageTypeName;
END
CLOSE c_Test;
DEALLOCATE c_Test;
-- Purge the temporary in-proc table:
DELETE FROM @Queue;
END
Send Message in a Update Trigger
SELECT @XML = (SELECT * FROM inserted FOR XML AUTO);
-- Send the XML records to the Service Broker queue:
DECLARE @DialogHandle UNIQUEIDENTIFIER,
@ConversationID UNIQUEIDENTIFIER;
/*
The target Service Broker service is the same
service as the initiating service; however, you
can set up this type of trigger to send messages
to a remote server or another database.
*/
BEGIN DIALOG CONVERSATION @DialogHandle
FROM SERVICE myService
TO SERVICE 'myService'
ON CONTRACT myContractANY;
SEND ON CONVERSATION @DialogHandle
MESSAGE TYPE myMsgXML
(@XML);
-- Let's detect an error state for this dialog
-- and rollback the entire transaction if one is
-- detected:
IF EXISTS(SELECT * FROM sys.conversation_endpoints
WHERE conversation_handle = @DialogHandle
AND state = 'ER')
RAISERROR('Dialog in error state.', 18, 127);
ELSE
BEGIN
--I want to list the queue after the trigger so I disabled
--END CONVERSATION @DialogHandle;
COMMIT TRAN;
END
The Problem is, that the Procedure doesn't even get started! So I tried to receive the Queues manually
WAITFOR (
RECEIVE message_body, message_type_name
FROM myQueue INTO @Queue
), TIMEOUT 5000;
and I run always into the timeout and get nothing back. A Select * FROM myQueue gives me some results back. Why I can't recevie?
Would be grateful for help, or at least a good tutorial, I haven't found one yet....
thx and greez
Karsten
View 1 Replies
View Related
Mar 27, 2006
Is it possible to have an ID that can access 2 databases? If it's possible, I have to create the same ID and password under each database?
View 6 Replies
View Related
Aug 19, 2014
After failing over to the DR replica. All databases are out of sync. DR replicas were setup as async the other 2 are set up as sync. Is this by design. No data has been updated to any of these as they are test dbs. So all dbs should be the same, no data loss.
View 0 Replies
View Related
Jul 20, 2005
I have a table which contains approx 3,00,000 records. I need toimport this data into another table by executing a stored procedure.This stored procedure accepts the values from the table as params. Mycurrent solution is reading the table in cursor and executing thestored procedure. This takes tooooooo long. approx 5-6 hrs. I need tomake it better.Can anyone help ?Samir
View 2 Replies
View Related
Oct 1, 2007
So here's the situation: I'm creating a front-end application to an SQL Server 2000 database and I need to create a new login to the database for the app.
Is it possible (or even; is it a good idea...) to create a logon that only has access to a single table?
Actually, I know it's possible - but I don't want to have to go through the hundreds of tables and deny access to them all! So I guess the question is;
Is there a quick and easy way of granting a login permissions to a single table only?
View 5 Replies
View Related
Jun 3, 2007
hi everyone,
is that possible to access a table if the table is doing an insert command? im trying to insert data into a data while another function calling select statement on that same table. will the table be lock when its doing an insertion? or its free? sorry about the question structure.
cheers,
delete469
View 2 Replies
View Related
Sep 29, 2015
if for any reason AG fails over to async node, how replication behaves? As data will not be in sync with previous primary replica, how replication will work? I think that we have to reset replication from scratch as there's a high chance subscribers might be more updated than current primary replica as failover to this node causes data loss. How to keep replication in sync without resetting up? Can we achieve this?
View 5 Replies
View Related
Oct 27, 2015
I have a 2 node cluster having 4 cores each wherein having 3 instances of SQL 2008 R2 enterprise comprising of 60 databases, 20 on each instance. I need to setup mirroring for each of the databases to a secondary server having 4 cores and 3 instances.
What i understand is that in this case the mirror server will be providing max of 512 worker threads and the 60 mirror databases would consume 240 threads.
What all needs to be checked for looking into the feasibility of going ahead with a async mirror setup as mentioned above.
View 4 Replies
View Related
Feb 14, 2008
Hello:
Having an extremely frustrating issue trying to connect to SQL once I've done the NET START MSSQL$SQL_DEV /c /m /T3608.
Briefly: SQL 2K and 2K5 named instances running on same DEV box. Can't open admin:<serverinstance> in SSMS, I get the following error:
"Login failed for user 'sa'. Reason: Server is in single user mode. Only one administrator can connect at this time. (Microsoft SQL Server, Error: 18461)
This happens regardless of credentials supplied (my AD acct (local admin on box), AD acct running SQL services or sa). Object Explorer is closed, remote connections disabled in SS Surface Area Config. I open SSMS and make no attempt to connect to server. Choose File >New > Query with Current Connection. In dialogue box, I attemp to utilize DAC and get the above error.
In DOS prompt where I issued the single user mode startup cmd, try to use sqlcmd to grab DAC session and receive the following error:
SQL Network Interfaces: An error occurred while obtaining the dedicated administrator connection (DAC) port. Make sure that SQL Browser is running, or check the error log for the port number [xFFFFFFFF]. Sqlcmd: Error: Microsoft SQL Native Client : 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..
So, no matter what method I use, I've managed to disable ALL access to the instance, despite the tips I've seen here and on Google.
I need to move the system databases to new disk volume, but cannot do so until I can open a connection to the instance once I've put it in single user mode. Looking in the SQL Srvr log following startup in single user mode I see the following:
Message
Server is listening on [ 'any' <ipv4> 3560].
Message
Dedicated admin connection support was established for listening remotely on port 3560.
Do I need to call the port# specifically when using SSMS or sqlcmd?
I can include screenshots of the failures and mssgs if necessary.
More disturbing is in a DR situation, I CAN'T OPEN A SESSION TO THE INSTANCE, which would be a very bad thing...
Please Help!
View 21 Replies
View Related
Aug 31, 2007
I get this error when I look at the state of my SQLresults object. Have I coded something wrong?Item = In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user. conn.Open()
Dim strSql As String
strSql = "INSERT INTO contacts (companyId, sourceId, firstName, lastName, middleName, birthday, dateCreated)" _
& "VALUES ('" & companyId & "', '" & sourceId & "', '" & firstName & "', '" & lastName & "', '" & middleName & "', '" & birthday & "', '" & now & "') SELECT @@IDENTITY AS 'contactId'"
Dim objCmd As SqlCommand
objCmd = New SqlCommand(strSql, conn)
Dim aSyncResult As IAsyncResult = objCmd.BeginExecuteReader()
If aSyncResult.AsyncWaitHandle.WaitOne() = True Then
Dim sqlResults As SqlClient.SqlDataReader
sqlResults = objCmd.EndExecuteReader(aSyncResult)
Dim cid As Integer
cid = sqlResults.Item("contactId")
Me.id = cid
conn.Close()
Return cid
Else
Return "failed"
End If
View 3 Replies
View Related
Jan 5, 2007
Hi,
I have Windows XP Home Workgroup LAN.
I am treating one of the XP Home system as 'Server' and installed SQL Express 2005 SP1. Enabled remote connections access.
I have total 4 XP Home systems, out of which one i am treating as Server, from the rest 3 computers, 2 are successfully connected to the Server and able to access SQL Express without any problems. But the 3rd system is unable to communicate with the Server. I disabled all firewalls in this 3rd system but still unable to connect to the server. I am able to ping the server, browse for shared folders on the server. Except SQL Express remote connection, everything else in the network is accessible from this 3rd computer.
Can anyone help me on how to troubleshoot this 3rd computer sql express connection problem to the server.
I don't have any error message to provide here. It just says, unable to connect to sql server, verify username/password etc.
Is there any limitation on SQL Express remote connections ?
View 1 Replies
View Related
Aug 17, 2000
We have been asked to look into using stored procedures with SQL Server 7.0 as a way to speed up a clients site. 99% of all the articles I have read along with all the books all say Stored Procedure should be used whenever possible as opposed to putting the SQL in your ASP script. However one of my colleagues has been speaking to Microsoft and they said that that they were surprised that our client wanted to use Stored Procedures as this was the old method of database access and that now he should really consider using COM objects for data access as itis much faster. Has anyone got any views on this or know of any good aticles regarding this matter ?
View 1 Replies
View Related
Nov 1, 2001
Hi all,
I have to change the date format for one database in a group of databases in my sql server 2000,Can you please tell me how to change the date format.
thanks in advance
View 1 Replies
View Related
May 9, 2012
I'm taking a database(read-only) backup from one server and restoring it on other server. As soon as restore is done it is bringing database into single-user read-only mode.
why it is bringing the database into single user mode ?
View 1 Replies
View Related
Apr 12, 2007
Hello:
My client has a db with the following structure:
Online US Searchable Map of the 50 US States. Users search criteria is the following: Query records by selecting state, county, then record. Each County table has 10-20 tables. All databases combined = 500MB and TLogs = 100MB.
How would you re-design a relational DB where users could query data by state-county-record. Currenty the DB's are created by the County of each state which creates hundreds of DB's in SQLServer with no realtionship to each US state. What would be the best design to ensure good performance, data integrity and maintenance? Would you create 1 DB with all 50 states, create 4 DB's and divide by region(N,S,E,W), 50 DB's of each state or leave it as is with each county it's on DB? Any suggestions would be appreciated.
thx
rob
View 7 Replies
View Related
Jun 10, 2015
I have recently upgraded to SQL2014 on Win2012. The Access front end program works fine.
But, previously created Excel reports with built in MS Queries now fail with the above error for users with MS 2013. The queries still work for users still using MS 2007.Â
I also cannot create any new queries and get the same error message. If I log on as myself on the domain to another PC with 2007 installed it works fine, so I don't think it is anything to do with AD groups or permissions.
View 6 Replies
View Related
Mar 25, 2008
I need to determine the following about the current authenticated Windows domain user who is trying to access a SQL Server via a trusted connection.
1 Has the current user been granted login access to the trusted SQL Server?
2 Has the current user been granted access to a specific database?
3 Is the current user a member of a specific database role such as (DB_ROLE_ADMINISTRATORS)?
Thanks,
Sean
View 6 Replies
View Related
Nov 25, 2015
I have a view that give me the data of all the batched. Now I am using a query on view to get a single batched data. when I am using direct query it was taking 0 sec but when I am using Through view "select * from myView where batched=2" then its taking 30 mnt.
View 3 Replies
View Related
Feb 5, 2007
I developed a database with Access 2003 and everything was working good until my tech came in and reformated my hard drive and install a new Ghost image that met our company standards.
Now I cannot go in and make any changes to any of the tables, queries and forms. All of this started when a new Ghost image was installed on my pc.
The message I get when I try to open my database is "You do not have permission to run "tblSwitchboard." I get the same error message when I try to do anything at all on the database.
I am at a loss as to what to do. Please help.
View 1 Replies
View Related
Feb 7, 2007
I would like to get single values from a huge sql server and put it into a table. let's say 4 by 4. How do I do that?
I have a connection string with a select statement that will only return a value. But, I do not know how to put that value into a table.
Thank you.
View 4 Replies
View Related