Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Tuesday, March 27, 2012

Connection Problem

Hi All,
I use the following code lines for connecting to SQL Server 2005 using
JDBC in Java:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl =
"jdbc:sqlserver:// SERVER;user=USER;databaseName=db;Authent
icationMethod=auto
";
but I got the error: Login failed for user 'USER'
I want to use windows authentication and I am pretty sure I use the
correct username. Can you please help me?
Thanks a lot.AuthenticationMethod=auto is correct but you would not
supply a user in the connection string to have the
connection use Windows authentication. If you supply the
user, it will use SQL authentication, not windows.
-Sue
On 9 Oct 2006 00:56:14 -0700, "sara" <sarasara82@.gmail.com>
wrote:

>Hi All,
>I use the following code lines for connecting to SQL Server 2005 using
>JDBC in Java:
>Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
> String connectionUrl =
>"jdbc:sqlserver:// SERVER;user=USER;databaseName=db;Authent
icationMethod=aut
o";
>but I got the error: Login failed for user 'USER'
>I want to use windows authentication and I am pretty sure I use the
>correct username. Can you please help me?
>Thanks a lot.

Sunday, March 25, 2012

Connection Problem

Hi All,
I use the following code lines for connecting to SQL Server 2005 using
JDBC in Java:
Class.forName("com.microsoft.sqlserver.jdbc.SQLSer verDriver");
String connectionUrl =
"jdbc:sqlserver://SERVER;user=USER;databaseName=db;AuthenticationMet hod=auto";
but I got the error: Login failed for user 'USER'
I want to use windows authentication and I am pretty sure I use the
correct username. Can you please help me?
Thanks a lot.
AuthenticationMethod=auto is correct but you would not
supply a user in the connection string to have the
connection use Windows authentication. If you supply the
user, it will use SQL authentication, not windows.
-Sue
On 9 Oct 2006 00:56:14 -0700, "sara" <sarasara82@.gmail.com>
wrote:

>Hi All,
>I use the following code lines for connecting to SQL Server 2005 using
>JDBC in Java:
>Class.forName("com.microsoft.sqlserver.jdbc.SQLSe rverDriver");
> String connectionUrl =
>"jdbc:sqlserver://SERVER;user=USER;databaseName=db;AuthenticationMet hod=auto";
>but I got the error: Login failed for user 'USER'
>I want to use windows authentication and I am pretty sure I use the
>correct username. Can you please help me?
>Thanks a lot.
sqlsql

Connection Pools and Restoring a DB

Hi all...

Is there any way to flush the connection pool through code?

I am trying to restore a DB from within Code and keep running into the fact that the restore cannot exclusively lock the DB.
I believe this is because there are some connections from the application that are pooled.
The app that I am working on accesses the DB to start up, so connections are maintained in the pool to the DB. Then from within the same application I want to suspend all users.. which I can do.. then restore a backup of the DB over the existing DB.
However even though there is no activity.. the connections are not released.. and I can find no way to force them to release...
Is it possible to force release??

I am using SQL server 2000.

Any and all suggestions or ideas are welcomed..

Thanks in advance,
Simon.Have you tried keeping database in DBO-Use only and make sure those connections have any ADMIN privilege on DB.

Tuesday, March 20, 2012

Connection Mystery

I am having trouble connecting to an SQL Server from an ASP.NET pagewritten in C#. I have reduced the code in my page to this:
public void Page_Load( object s, EventArgs e ) {
SqlConnection conn = new SqlConnection( "Server=server;User ID=user;Password=pass;" );
conn.Open();
}
and I get the following error:
System.Data.SqlClient.SqlException: SQL Server does not exist or access denied.

Thisworks for other server/user/pass except the one I am having troublewith. The SQL Server is using SQL & Windows Authentication. I amable to connect from the machine that is running the webserver viaosql, ODBC, and MS Access using the same arguments (server, user, andpass), so I know that the SQL server does exist, and the User/Passwordshould give me access.
Does anyone have any ideas why thisisn't working or what ASP.NET is does differently from the other accessmethods? Any ideas are greatly appreciated.
Thanks,
Mark Daneyou havent specified what database to connect to..check out thiswebsite for connection strings|||I have tried it with and without using a database name in theconnection string. It does not work either way.
I have tried a variety of connection strings options but none of thecombonations seem to work. However they work connecting to adifferent SQL Server, which makes me think that it is something withthis specific SQL Server. However I am able to connect to theserver through osql, ODBC, or MS Access all without a problem, so Idon't belive it is a problem with the SQL Server accepting the login.Since it doesn't seem to be a problem with the connection stringattributes, or the server, I am not sure what could be causing it.
|||are you sure you have the values properly like the server name, database name uid, pwd all correct ? and can you connect to the sql server from query analyzer using the same credentials ?|||

Try this url for the database permissions setup, if no money transactions passes through the site. Hope this helps.

http://duhnetnuke.net/DesktopDefault.aspx?tabid=40

Kind regards,

Gift Peddie

|||

The info in this link uses the Master as the default database for your Asp.net account permissions. If you are still having problems with that, then it could be a bug. Hope this helps.

http://duhnetnuke2.net/Default.aspx?tabid=64

|||I found out what the problem was. The SQL Server I was trying toconnect to didn't have the latest service pack installed. Iupgraded the SQL Server to SP3a and now it works fine.

Sunday, March 11, 2012

Connection is busy ...

Hi all,

I use VC++ 6 and MFC, with SQL Express 2005.

source code sample :

CRecordset *rec1 = new CRecordset(machine->pDB);
rec1->Open(...,szSQL,...);
while(!rec1->IsEOF())
{
CDBVariant var1,var2;
rec1->GetFieldValue("COL1",var1);
rec1->GetFieldValue("COL2",var2);

int val1 = GET_INDEX(var1);
int val2 = GET_INDEX(var2);
var1.Clear();
var2.Clear();

CRecordset *rec2 = new CRecordset(machine->pDB);
szSQL.Format("SELECT COL3,COL4 FROM TB1 WHERE COL3 = %i AND COL4 = %i",val1,val2);
rec2->Open(...,szSQL,...);
while(rec2->IsEOF())
{
//Something
rec2->MoveNext();
}
rec2->Close();
delete rec2;
rec1->MoveNext();
}
rec1->Close();
delete rec1;
On the red line, i catch a CBDException "Connection is busy with results for another command"

I think, I can't use the same database connection with severals Recordset simultaneous but why and it's normal, what is wrong in my source code or in the database server configuration ?

Please help me ...

By default, the connection you made to server doesn't support MARS(Multiple Active ResultSet). Which means, that you can only open one result set against server per connection. You need to close one result set before you open another result set.

But you can make this work my turning on MARS. You can refer to the following blog for information on how to turn on MARS in your connection string. Please note that you need to use SNAC to be able to use MARS feature.

http://blogs.msdn.com/dataaccess/archive/2005/08/02/446894.aspx

Please let me know if you need more help on this.

Connection is busy ...

Hi all,

I use VC++ 6 and MFC, with SQL Express 2005.

source code sample :

CRecordset *rec1 = new CRecordset(machine->pDB);
rec1->Open(...,szSQL,...);
while(!rec1->IsEOF())
{
CDBVariant var1,var2;
rec1->GetFieldValue("COL1",var1);
rec1->GetFieldValue("COL2",var2);

int val1 = GET_INDEX(var1);
int val2 = GET_INDEX(var2);
var1.Clear();
var2.Clear();

CRecordset *rec2 = new CRecordset(machine->pDB);
szSQL.Format("SELECT COL3,COL4 FROM TB1 WHERE COL3 = %i AND COL4 = %i",val1,val2);
rec2->Open(...,szSQL,...);
while(rec2->IsEOF())
{
//Something
rec2->MoveNext();
}
rec2->Close();
delete rec2;
rec1->MoveNext();
}
rec1->Close();
delete rec1;
On the red line, i catch a CBDException "Connection is busy with results for another command"

I think, I can't use the same database connection with severals Recordset simultaneous but why and it's normal, what is wrong in my source code or in the database server configuration ?

Please help me ...

By default, the connection you made to server doesn't support MARS(Multiple Active ResultSet). Which means, that you can only open one result set against server per connection. You need to close one result set before you open another result set.

But you can make this work my turning on MARS. You can refer to the following blog for information on how to turn on MARS in your connection string. Please note that you need to use SNAC to be able to use MARS feature.

http://blogs.msdn.com/dataaccess/archive/2005/08/02/446894.aspx

Please let me know if you need more help on this.

connection help

hey im 2006 passed out.,im a trainee in asp platform.,

ive been provided windows authentication and i have a code showing error. could u please help me and i got this code from net only else u giv me a correct code to connect asp and sql2005

my code

<%

set con=server.CreateObject("ADODB.connection")

con.Open dsn="dsn_uma"

set rs=server.CreateObject("ADODB.recordset")

rs.Open "select * from xxtable",con,1,3

while(not rs.EOF)

for i=0 to rs.RecordCount

Response.Write rs(i) & ":"

next

Response.Write "<br>"

rs.MoveNext()

wend

%>

Please check this link http://www.frontpages-web-hosting.net/support/asp.access.database.connection.htm

Make sure your DSN is configured correctly and tell us the exact error msg if you still see errors.

Thursday, March 8, 2012

Connection failed!

Hi guys,

I have problem with this code:

TCHAR szCurrentDir[250];

TCHAR szDataDir[250];

lstrcpy(szDataDir,

TEXT("DRIVER={SQL Native Client};SERVER=.\\sqlexpress;Trusted_Connection=Yes;DATABASE=MyDic;AttachDBFileName="));

GetCurrentDirectory(sizeof(szCurrentDir), szCurrentDir);

lstrcat(szCurrentDir, TEXT("\\Database\\Data.mdf;"));

lstrcat(szDataDir, szCurrentDir);

SQLDriverConnect(hdbc, hWnd, szDataDir, SQL_NTS, szConnStrOut, sizeof(szConnStrOut), &cbConnStrOut, SQL_DRIVER_COMPLETE);

When I run my program, I get this message:


Microsoft SQL Server Login
Connection failed:
SQLState: '42000'
SQL Server Error: 5133
[Microsoft][SQL Native Client][SQL Server]Directory lookup for the file "C:\Program Files\MyDic\Database\Data.mdf" failed with the operating system error 5(Access is denied.).
Connection failed:
SQLState: '42000'
SQL Server Error: 1832
[Microsoft][SQL Native Client][SQL Server]Could not attach file 'C:\Program Files\MyDic\Database\Data.mdf' as database 'MyDic'.


OK

I have to mention that:

SQL Server: SQL Server (2005) Express

Operating System: Windows XP SP2

and I'm Local Admin.

I wanna deploy this program with data.mdf file that contains program data.

So, How can I fix it?

Regards

Curious issue. It looks like your connection string is correct. Can you check to see if your detached database's assocated .LDF file is read-only? (I had that issue before.) If it doesn't have one, then ignore this suggestion.

Another thing you might try is to see if putting your detached database into the SQL Server's 'Data' folder. Something along the lines of 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data'. Again, probably not the issue since you're getting an 'access denied' error, not one about 'file not found'.

Did you detach with same version SQL server? This could be a compatibility issue.

It almost sounds like you're trying to attach a database that already exists. Could this be possible?

Try to debug your issue with the following steps:

1) Create a database, with tables, etc...

2) Detach the database

3) drop the database

4) try to re-attach the database using a connection string like the one above.

If you can get this to work then you should be okay.

If you're still stuck, re-activate this issue and I'll try to think of something else.

~Warren

|||Does C:\Program Files\MyDic\Database\Data.mdf exist? Does the service account for your sqlexpress has permissions to read/write this file? You must have at least read permission to the file to logon to the server. (You cannot relay on sqlexpress create the file for you.)|||

Dear Warren,

I have checked all things you mentioned, but it doesn't work

I think this issue is concerned with the service account for my SQLEXPRESS as Xinwei Hong mentioned.

Well, Do you know how I can change this account programmatically so that I could get rid this issue?

Best

|||

Dear Xinwei,

I think you are right. But how can I change the service account programmatically in order to have read and write permission?

Thanks,

|||

I don't think you need to change the service account programmatically. You can just give the read/write permission to the service account. Do you have any special reason that you don't want to give the permission to the SQL service account on your computer?

Thanks.

|||

That's a tough one. I guess the easiest way would be to create an 'sa' login on your SQL Server installation, and then replace 'Trusted_Connection' with 'User=sa;Pwd=<<WhateverPasswordYouCreated>>;'.

This would guarantee you have admin rights to attach/detach databases.

Second easiest would be to log onto machine as admin, and add your user name as a machine admin. (I’m afraid I’m not too good at showing how to do that on an XP machine, since I only use W2K3 Server.)

The more difficult method to do this programmatically would be to use “Runas”. I’m not positive it would work, but you could try running your application from the command line via ‘Runas admin’ which would give it admin rights, and it should work. Please see http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/runas.mspx?mfr=true for more documentation on how to use this.

If anyone else has suggestions, please speak up!

Good luck!

~Warren

|||

Hi Xinwei,

As I said before, I just wanna deploy my program containing data.mdf file. I made installation and I tested but I got this problem. I read some technique to deploy MDF files such az Xcopy, but it didn't work.

sincerely.

|||

Hi Warren,

Thank you for your comments.

By the way, I read this article:

"How to verify and change the system administrator password in MSDE or SQL Server"

http://support.microsoft.com/Default.aspx?scid=kb;en-us;322336&spid=2855&sid=global

But when I created sa, sqlcmd said that sa account disabled. Do you know how I can enable it?

Thanks.

|||

Look here:

http://msdn2.microsoft.com/en-us/library/ms188670.aspx

|||

Dear Markus,

Thank you so much. I got that.

Regards.

Wednesday, March 7, 2012

Connection error while already running code

I am using Access 2002 as a front end and SQL Server 2000 as a back end.
I am using an ODBC connection and TCP/IP
After I have connected, I use ADO to run a process that gets ten different
sum queries from various SQL Server tables and writes the results to local
Access table. This loops thru 300 to 800 records.
The second time thru this process, at any of the queries, I will almost
always get this error:
-2147467259, Sql Server does not exist or access denied. Now I am already
connected and I have run this same query many times.
If I debug and force the same line, it runs.
Why is it hanging occasionally, and more importantly, what can I do to fix
this?
TIA,
MikeCould be that the problem is timing related. What happens if you insert a
timer event to wait a few seconds prior to establishing a new connection?
What is the connection timeout setting? How many concurrent connections
are on the server when this happens?
Thanks,
Kevin McDonnell
Microsoft Corporation
This posting is provided AS IS with no warranties, and confers no rights.|||Kevin,
I am not establishing a new connection, I am using one that is already open.
The connection timeout is the default, 30 seconds.
The concurrent connection fluctuates between 159 and 175.
Hope this helps.
Mike
"Kevin McDonnell [MSFT]" <kevmc@.online.microsoft.com> wrote in message
news:dzu1LfLVEHA.2764@.cpmsftngxa10.phx.gbl...
> Could be that the problem is timing related. What happens if you insert a
> timer event to wait a few seconds prior to establishing a new connection?
> What is the connection timeout setting? How many concurrent connections
> are on the server when this happens?
> Thanks,
> Kevin McDonnell
> Microsoft Corporation
> This posting is provided AS IS with no warranties, and confers no rights.
>
>

Connection error while already running code

I am using Access 2002 as a front end and SQL Server 2000 as a back end.
I am using an ODBC connection and TCP/IP
After I have connected, I use ADO to run a process that gets ten different
sum queries from various SQL Server tables and writes the results to local
Access table. This loops thru 300 to 800 records.
The second time thru this process, at any of the queries, I will almost
always get this error:
-2147467259, Sql Server does not exist or access denied. Now I am already
connected and I have run this same query many times.
If I debug and force the same line, it runs.
Why is it hanging occasionally, and more importantly, what can I do to fix
this?
TIA,
Mike
Could be that the problem is timing related. What happens if you insert a
timer event to wait a few seconds prior to establishing a new connection?
What is the connection timeout setting? How many concurrent connections
are on the server when this happens?
Thanks,
Kevin McDonnell
Microsoft Corporation
This posting is provided AS IS with no warranties, and confers no rights.
|||Kevin,
I am not establishing a new connection, I am using one that is already open.
The connection timeout is the default, 30 seconds.
The concurrent connection fluctuates between 159 and 175.
Hope this helps.
Mike
"Kevin McDonnell [MSFT]" <kevmc@.online.microsoft.com> wrote in message
news:dzu1LfLVEHA.2764@.cpmsftngxa10.phx.gbl...
> Could be that the problem is timing related. What happens if you insert a
> timer event to wait a few seconds prior to establishing a new connection?
> What is the connection timeout setting? How many concurrent connections
> are on the server when this happens?
> Thanks,
> Kevin McDonnell
> Microsoft Corporation
> This posting is provided AS IS with no warranties, and confers no rights.
>
>

Saturday, February 25, 2012

Connection Error from ASP.Net under IIS: provider: Named Pipes Provider, error: 40

We experience the 40 error when our Asp.net code runs under IIS and uses named pipes to a sql server 2005 named instance.

We've tried all suggestions found on blogs and KB articles such as making sure the named pipes protocol is enabled, making sure the Browser service is started, making sure Allow Remote Connections is enabled, making sure we're not using Asp.Net 2.0 membership providers, and the list goes on and on.

We boiled it down to a simple test scenario. We open a SqlConnection to the sql 2005 box in the code with the intention of binding a datareader to a gridview, but it never gets that far because the connection.Open() fails.

If we run this test application as a virtual directory in IIS and Asp.Net 2.0, the connection.Open() fails.

If we run this test application from Visual Studio .Net using Cassini (PWS), the connection.Open() succeeds and binds to the gridview.

What could be causing the connection to fail under IIS but succeed under Cassini? We've tried setting IIS to run as a domain user and with digest authentication enabled. That made no difference.

Any help or insight is appreciated!

Could you try to answer the following questions though some of them may be already implied by your post?

(1) Is this remote connection or local connection?

(2) Is the account that runing your visual studio.net the the same as your IIS. Do you impersonate client connection in IIS?

(3) Can you make direct connection to your backend sqlserver from your virtual studio or sql server management studio?

(4) Can you try connecting using TCP instead? If not, what is the error code?

|||

(1) Is this remote connection or local connection?

-Remote connection

(2) Is the account that runing your visual studio.net the the same as your IIS. Do you impersonate client connection in IIS?

-Same account, windows authentication. No impersonation

(3) Can you make direct connection to your backend sqlserver from your virtual studio or sql server management studio?

-Management Studio works, Cassini works.. IIS does not

(4) Can you try connecting using TCP instead? If not, what is the error code?

TCP gives "server actively refused connection" error

|||

Does your connection string like "servername\instancename" or something else?

The TCP failure indicates either the server TCP listener is not up or client uses different TCP port to connect. So please check whether the TCP is enabled or not. Restart the server after the configuration change. Then check if the connection string has instancename specified. Once you find out which port the server is listening on, you can also use "tcpTongue Tiedervername,port" to connection to the server.

Connection Error

What the problem of this error. For information, please check code as below,

ProtectedConst SQL_CONNECTION_STRINGAsString = "workstation id=LOCALHOST; size=4096;integrated security=SSPI;initial catalog=VIVAM;persist security info=False;User ID=sa"

below is the error command

Login failed for user 'BST-FAIROZ\ASPNET'.

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: Login failed for user 'BST-FAIROZ\ASPNET'.

As you set integrated security to SSPI in connection string, you're using Windows Authentication to connnect to SQL. So when the application is deployed to IIS5.0, IIS will use'BST-FAIROZ\ASPNET'account to connect to SQL. So what you need to do is add the account in SQL logins: open Management Studio (or Enterprise Manager)-> locate local SQL instance->Security->Logins->New Login. And give sufficient permissions to the account so that your application can perform query to SQL as you like.

Connection Error

I have an asp page that opens up a crystal report...however; randomly
I either get the report or I get this error:

ADO Error Code: 0x80004005 Source: Microsoft OLE DB Provider for SQL
Server Description: Connection failure SQL State: 08S01

and its happening alot...

Where should I begin looking to solve this..I dont see anything
particular in the event log in both client or server...

thanks

-JimJim (jim.ferris@.motorola.com) writes:
> I have an asp page that opens up a crystal report...however; randomly
> I either get the report or I get this error:
> ADO Error Code: 0x80004005 Source: Microsoft OLE DB Provider for SQL
> Server Description: Connection failure SQL State: 08S01
> and its happening alot...
> Where should I begin looking to solve this..I dont see anything
> particular in the event log in both client or server...

08S01 - Communication Link Failure. Often indicates that some accident
happened on the SQL Server, which forced SQL Server to sever the
connection. Usually accompanied by stack dumps in the SQL Server error log.
(That is not the eventlog.) Such crashes are due to bugs in SQL Server, and
should not occur in an ideal world.

But a flaky network could also be the cause.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Sunday, February 19, 2012

Connection and Logon Code Problem

Hi...

I am having problem with my Crystal Report XI Connection and Logon Code. I am using VB.NET 2003

1. I made a non-embedded report document named AccountReport.rpt and save it in "D:\Report\AccountReport.rpt"

2. AccountReport.rpt connection properties

a. I used an odbc(RDO) connection string

Provider=MSDataShape;Driver={Microsoft Access Driver (*.mdb)};Dbq=D:\Account.mdb;Uid=admin;Pwd=userxxx;

3. In My VB.NET code:

a. VB.NET Code:

Dim AccountRPT As New ReportDocument
'Instantiate my report document

AccountRPT.Load(Path.GetFullPath(".") & "D:\Report\AccountReport.rpt")
'Load the report

AccountRPT.DataSourceConnections(0).SetConnection("Account", "F:\Business\Grocerry\Account.mdb", "admin", "userxxx")
'You can see here that I change my database location from "D:\Account.mdb" to "F:\Business\Grocerry\Account.mdb".

AccountRPT.SetParameterValue("BALANCE", 2000)
'Passed a value into a parameter list

frmGraph.crvReport.ReportSource = AccountRPT
'Set my report document as a report source for viewing

4. The Problem.

a. The connection of my Report Document "AccountRPT" does not change from "D:\Account.mdb" to "F:\Business\Grocerry\Account.mdb".

If anybody can help please do...

Sincerely...Check with this link :

http://support.businessobjects.com/library/kbase/articles/c2010371.asp

It may help you to solve your problem.

Thanks,
Vidu.

connection

Hello,

I'm getting the error below...

The connection was not closed. The connection's current state is open.

And heres the code thats casung the problem,...

publicstaticvoid JoinGroup(string GroupID,string User_ID)

{

SqlCommand cmd =newSqlCommand("insert into User_Joined_Groups (GroupID, User_ID) values (@.GroupID, @.User_ID)", conn);

conn.Open();

cmd.Parameters.Add(newSqlParameter("@.GroupID", GroupID));cmd.Parameters.Add(newSqlParameter("@.User_ID", User_ID));

cmd.ExecuteNonQuery();

conn.Close();

}

The method is called on a button click

anyone know what I've done wrong?

Thank you

Open your connection before using it when establishing your command. Also, make sure you have created your connection with the proper connection string before opening it:

public static void JoinGroup(string GroupID,string User_ID) {
conn =new SqlConnection(connStr);
conn.Open();SqlCommand cmd =new SqlCommand("insert into User_Joined_Groups (GroupID, User_ID) values (@.GroupID, @.User_ID)", conn); cmd.Parameters.Add(new SqlParameter("@.GroupID", GroupID));cmd.Parameters.Add(new SqlParameter("@.User_ID", User_ID)); cmd.ExecuteNonQuery();conn.Close();}

|||

champion!

Tuesday, February 14, 2012

Connecting to the SQL Database

Hi all,

I am new to this field. I am trying to Connect to the database using the following code. The code does not give an error but gives an empty grid view.

Can somebody figure out the mistake?

protectedvoid Page_Load(object sender,EventArgs e)

{

if (!IsPostBack)

BindGridView();

}

void BindGridView()

{

System.Data.SqlClient.SqlConnection sqlconnect =new System.Data.SqlClient.SqlConnection("");//added connection string here

String command ="SELECT * from table";

System.Data.SqlClient.SqlCommand sqlcommand =new System.Data.SqlClient.SqlCommand();

sqlcommand.CommandText = command;

sqlcommand.Connection = sqlconnect;

System.Data.SqlClient.SqlDataAdapter da =new System.Data.SqlClient.SqlDataAdapter();

da.SelectCommand = sqlcommand;

DataSet ds =newDataSet();

sqlconnect.Open();

sqlcommand.ExecuteNonQuery();

da.Fill(ds);

GridView1.DataSource = ds;

GridView1.DataBind();

sqlconnect.Close();

}

First, make sure the SQL does return data by executing it like it query analyser or management studio.

Try this code in stead

System.Data.SqlClient.SqlConnection sqlconnect =new System.Data.SqlClient.SqlConnection("");//added connection string hereString command ="SELECT * from table";System.Data.SqlClient.SqlCommand sqlcommand =new System.Data.SqlClient.SqlCommand();sqlcommand.CommandText = command;sqlcommand.Connection = sqlconnect;System.Data.SqlClient.SqlDataAdapter da =new System.Data.SqlClient.SqlDataAdapter();da.SelectCommand = sqlcommand;DataSet ds =new DataSet();da.Fill(ds);GridView1.DataSource = ds;GridView1.DataBind();

|||

hi,

I have already checked the query in query builder and it works absolutely fine. The connection also works when i use the SQLDataSource control from the toolbox. However, it does not work with the code. Also, the code that you suggested gives the same output as before.

|||

Hi,

are you mapping the columns in dataview by manually or allow auto generated Columns.

System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(" ");
System.Data.DataSet ds = new System.Data.DataSet();
System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter();
conn.Open();
adapter.SelectCommand = new System.Data.SqlClient.SqlCommand("Select * From Table", conn);
adapter.Fill(ds, "Authors");
conn.Close();

GridView1.DataSource = ds;
GridView1.DataBind();

Hope this Work

|||

sjm:

I have already checked the query in query builder and it works absolutely fine. The connection also works when i use the SQLDataSource control from the toolbox. However, it does not work with the code. Also, the code that you suggested gives the same output as before.

The code should execute fine and as you say there are no errors.

Can you just break through and step over all the code just to make sure no exceptions are being thrown, and also inspect the dataset object after it has been filled to see if datatables/datarows exist in it.

|||

Hey

This does not work either. I've tried mapping the columns manually as well as Allowing auto generate, both don't give the required output.

Do i need to create a new table manually for allowing display of grid view?

if yes, how should i do that?

|||

sjm:

Do i need to create a new table manually for allowing display of grid view?

There is no need. The gridview can be bound to a dataset and it will auto generate the bound fields based on the datatable in the dataset.

Did you step through the code to make sure no errors and thrown and can inspect the dataset?

|||

place ur code in try catch block.

and also check ds.tables[0].rows.count by debug. is should return > 0.

|||

Thanks to all of you who replied...

I could solve the Problem...

The problem with the code was that the columns in the grid were not binded to the data.

I did that nd the code worked..

thank you.

Connecting to the database in SQL Server 2000

I am developing a system using VS 2003 with database SQL Server 2000.

In web.config, I have added the following code in it

<sessionState

mode="InProc"

stateConnectionString="tcpip=127.0.0.1:42424"

sqlConnectionString="data source=127.0.0.1;Database=grandb;Trusted_Connection=yes"

cookieless="false"

timeout="60"

/>

Actually I don't know if the above code is correct. My database is stored in the SQL Server 2000 and named as grandb.

Thank you.

Hi,

You should modify the <sessionState> tag only when you are using OutProc mode. It seems you want to place you connection string in the web.config file, use this sample setting instead:

<

configuration>
<appSettings><addkey="connectionString"value="Data Source=127.0.0.1;uid=xxxx;pwd=xxx;database=grandb"/>

</

appSettings>

In case you are using windows based authentication in your Sql server, then use the Trusted =yes connection instead of username and password.

You can access this connection string in your source files as:

string

strConn = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];

Hope this helps,

Vivek

|||

I add this between appSettings

<add key="DBConnr" value="Data Source=localhost;database=grandb;Trusted=yes" />

However, it still not works...

Any error for that?

Thank you

|||

thtang:

I add this between appSettings

<add key="DBConnr" value="Data Source=localhost;database=grandb;Trusted=yes" />

However, it still not works...

What is the error message are you getting? Are you using Windows authentication in SQL Server or Mixed mode?

Vivek

Friday, February 10, 2012

Connecting to Sql Server from Application

What is actually happening behind the scenes when you open a connection
to sql server in code such as C# or vb.net.(jw56578@.gmail.com) writes:
> What is actually happening behind the scenes when you open a connection
> to sql server in code such as C# or vb.net.

There is some communication taking place over TCP or some other network.
The communication is carried out over a protocol known as TDS, Tabular
Data Stream. This protocol is proprietary to Microsoft (and Sybase have
their version). On the server side, a server process is created, and some
memory structures are allocated for the connection.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||To add to Erland's response, connection pooling also affects open behavior.
When you close a connection with pooling enabled, the connection isn't
actually closed but rather reset and placed in an available connection pool.
These pooled connections can then be used for subsequent open requests
without the overhead of establishing a new SQL Server connection. A new
connection will be obtained when an available one doesn't exist in the pool.

--
Hope this helps.

Dan Guzman
SQL Server MVP

<jw56578@.gmail.com> wrote in message
news:1106925442.453159.25140@.f14g2000cwb.googlegro ups.com...
> What is actually happening behind the scenes when you open a connection
> to sql server in code such as C# or vb.net.