Quantcast
Channel: SQL Server Data Access forum
Viewing all 4164 articles
Browse latest View live

ASP code (recordset) too slow on SQL Server 2005

$
0
0
  1. Hi,

    I have recently migrated my MS Access db to SQL Server 2005. I am using classic ASP in my application & facing problems with my code. My code for a drop down box (which populates from a database table from MS SQL Server 2005) is running dead slow. Can anyone please guide what could be the problem. The same code when run with Access database runs faster & the dropdown populates within secs, but on SQL Server 2005 it takes atleast 5 mins to populate.

    <select name="officeItemList" id="officeItemList"><option value=" " selected>Select District</option><% set rs2 = server.createobject("adodb.recordset")
    
    				 sqlgov = "SELECT DISTINCT district FROM tbl_SubDist ORDER BY district;"
    			'Set rs2 = dbConn.Execute(sqlgov)
    			RS2.Open sqlgov, DBConn,3,2
    			if not rs2.eof then
    				rs2.movefirst
    				do while not rs2.eof
    				if not rs2("district")="" then
    				%><optgroup label="<%=rs2("district")%>"><%
    			sql = "SELECT DISTINCT subdistrict FROM tbl_SubDist where subdistrict = '"&rs2("district")&"' ORDER BY subdistrict;"
    			'Set rs = dbConn.Execute(sql)
    			RS.Open sql, DBConn,3,2
    			if not rs.eof then
    				rs.movefirst
    				do while not rs.eof
    					if not rs("subdistrict")="" then
    			%><option value="<%response.Write(rs("subdistrict"))%>"><%response.Write(rs("subdistrict"))%></option><%
    					end if
    				rs.movenext
    				loop
    				rs.close
    			end if
    			%></optgroup><%end if
    				rs2.movenext
    				loop
    				rs2.close
    			end if%></select>
In my DB table, I have 109 districts & 280 sub distrcits ( for the 109 districts). I am really bogged down here & frustrated, since the code on Access db returns values in flash. I have a very limited knowledge of SQL Server 2005 & have to run the code on it. What all is required when you migrate Access db to SQL Server 2005? Thank you for helping me out.

Help with sql client.

$
0
0

I finished my application in visual studio 2013, i used my sql database, i shared the application in the network and i need users to use in different machines from one computer, when i try running it i get this error:

See the end of this message for details on invoking 
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.Data.SqlClient.SqlException (0x80131904): The file "\\RYZA-PC\Debug\Database\LMS-Db.mdf" is on a network path that is not supported for database files.
An attempt to attach an auto-named database for file \\RYZA-PC\Debug\Database\LMS-Db.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
   at New_Dawn._LMS_DbDataSetTableAdapters.StudentsBooksBorrowHistoryTableAdapter.Fill(StudentsBooksBorrowHistoryDataTable dataTable) in C:\Users\Ryza\Dropbox\New Dawn\New Dawn\Database\_LMS_DbDataSet.Designer.vb:line 12788
   at New_Dawn.StudentsIssueForm.StudentsIssueForm_Load(Object sender, EventArgs e) in C:\Users\Ryza\Dropbox\New Dawn\New Dawn\GUI\Circulation\Students\StudentsIssueForm.vb:line 22
   at System.Windows.Forms.Form.OnLoad(EventArgs e)
   at System.Windows.Forms.Form.OnCreateControl()
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.ContainerControl.WndProc(Message& m)
   at System.Windows.Forms.Form.WmShowWindow(Message& m)
   at System.Windows.Forms.Form.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
ClientConnectionId:06665186-49a7-4ca2-8dbb-240e2dc66013


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18444 built by: FX451RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
New Dawn
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.0.0
    CodeBase: file://RYZA-PC/Debug/New%20Dawn.exe
----------------------------------------
Microsoft.VisualBasic
    Assembly Version: 10.0.0.0
    Win32 Version: 11.0.50938.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/Microsoft.VisualBasic/v4.0_10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.dll
----------------------------------------
System
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Core
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
System.Windows.Forms
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System.Configuration
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
System.Runtime.Remoting
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Runtime.Remoting/v4.0_4.0.0.0__b77a5c561934e089/System.Runtime.Remoting.dll
----------------------------------------
System.Data
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.Data/v4.0_4.0.0.0__b77a5c561934e089/System.Data.dll
----------------------------------------
System.Data.DataSetExtensions
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Data.DataSetExtensions/v4.0_4.0.0.0__b77a5c561934e089/System.Data.DataSetExtensions.dll
----------------------------------------
System.Numerics
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Numerics/v4.0_4.0.0.0__b77a5c561934e089/System.Numerics.dll
----------------------------------------
System.Transactions
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.Transactions/v4.0_4.0.0.0__b77a5c561934e089/System.Transactions.dll
----------------------------------------
System.EnterpriseServices
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.EnterpriseServices/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.EnterpriseServices.dll
----------------------------------------
Accessibility
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/Accessibility/v4.0_4.0.0.0__b03f5f7f11d50a3a/Accessibility.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.

Please help. RYZA-PC is the main computer. the application is running.

Can't login SQL after changing computer name

$
0
0

We have DPM and VMM running on a Windows 2008 R2. After we changed the computer, we can't logon to the SQL Server Management Studio. The login screen doesn't show the SQL Server name. It doesn't we enter the correct servername or localhost, we get Error 53 or error 2. However both DPM and VMM work fine.  How can we fix this login problem?


Bob Lin, MCSE &amp; CNE Networking, Internet, Routing, VPN Networking, Internet, Routing, VPN Troubleshooting on http://www.ChicagoTech.net How to Install and Configure Windows, VMware, Virtualization and Cisco on http://www.HowToNetworking.com

instance failure, in System.Data in sql 2012

$
0
0

On Win Server 2012 Standard I have a C# app that runs fine with sql 2008 express. When I installed sql 2012 express I get "instance Failure" source: System.data. when the following LYNQ query executes:


//MessageBox.Show("Starting GetInitialPortStatus.");

db =newDataClasses1DataContext();   //establish dataconnection to CALMasterSQL


// 2. Query creation.

var PortsQuery =from portrecord in db.Channels

select portrecord;


// 3. Query execution.

int count = 0;

// MessageBox.Show("Starting >portrecord in PortsQuery<.");

foreach (var portrecord in PortsQuery)           // add rows to the grid for each record in the database Ports table

                {...}

Otherwise the app works fine. The closet fix in the forum I could find was to run

exec sp_configure 'user instances enabled',1.
Go
Reconfigure

Which I did but no change.

How can this be corrected. It seems like it is a known issue but no fix for sql 2012?

Thanks

Morris


   



















Thank you Morris

Can I check if cells are the same?

$
0
0

Hi everyone.

I have a SQL Query that works really well, but have a request that I have not been able to meet.  The query is pulling data from a customer's table as well as the SUM of associated billings in a billings table.

What I want to do is check all of the billings for this customer and IF all of a given column are "Yes", show Yes in the grid, but if one of them is "No", show No.

But I can't figure out how this should be done.  I don't want multiple rows for each invoice from the billing section, just the one.

Does anyone have any suggestions for this?  I would greatly appreciate the help.

Thanks Again,

-Matt-

Retrieving scalar value from one Stored Procedure in another Stored Procedure

$
0
0

For years I've been using the results of one stored procedure in another by inserting those results into a temp table. 

However, I am working with a stored procedure that returns a result set consisting of a single scalar value.  (It is used in the code somewhere to executeScalar.)  I need to call this same stored procedure to populate a variable in my stored procedure.  (It is not my database so I am not authorized to change anything beyond what i have been specifically tasked to do.)  Currently the way I have this written is to create a single column temp table, insert the results of that execute into the temp table and do a Set @var = (Select field from #Temptable).  This was the way I did it back in SS 7.0.  It seems to me that over the past 17 years and the past 5 versions (we are using SS2008R2) that a better way of doing would have been devised. (If I had full authority to the database I would devise a scalar function that did the same thing.  But "if wishes were fishes, we'd all cast nets".)   I've searched over the web, but all the results I get back talk about either doing it the same old way or using ExecuteScalar in ASP.Net. 

So is there a better way than the way I've been doing it since 1997 I would appreciate hearing about it.


Edward R. Joell MCSD MCDBA

ODBC functions SQLExecDirectW and SQLExecute functions return error:”DIAG [22001] [Microsoft][SQL Server Native Client 10.0]String data, right truncation (0) “

$
0
0

Problem Description:

ODBC functions SQLExecDirectW and SQLExecute functions return error:”DIAG [22001] [Microsoft][SQL Server Native Client 10.0]String data, right truncation (0) “. When we enable tracing in the ODBC administrator, in the SQL.log we see that values for the arguments: ColumnSize, BufferLength, and StrLen_or_IndPtr of ODBC function SQLBindParameter are not being displayed.

Environment Used:

OS: Microsoft Windows Server 2003 R2 Standard x64 Edition.

Complier: Microsoft Visual Studio 2008 SP1 for x64.

Database: Microsoft SQL Server 2008

MDAC: Microsoft Data Access Components SDK 2.8

Note: This problem is seen only in our 64bit application. However, in 32bitSQLExecDirectW and SQLExecute functions return successfully.

As we could not find the values of 6<sup>th</sup>, 9<sup>th</sup> and 10<sup>th</sup> arguments(ColumnSize, BufferLength, and StrLen_or_IndPtr) passed to SQLBindParameter in the ODBC traces for 64bit, we are not sure whether the values for the above mentioned arguments are received correctly by SQLBindParameter or not. This information would help us to debug further. So, could you please let us know why these values are not displayed.

1)Here is the extract of the SQL.log file for 32bit where the values for SQLULEN , SQLLEN and SQLLEN* are displayed properly:

PR0CNFG 1028-15f0 ENTER SQLBindParameter

HSTMT 0x006FBDD8

UWORD 1

SWORD 1 <SQL_PARAM_INPUT>

SWORD -8 <SQL_C_WCHAR>

SWORD -9 <SQL_WVARCHAR>

SQLULEN 23

SWORD 0

PTR 0x0595EBBA

SQLLEN 46

SQLLEN * 0x05A5FB00

2)Here is the extract of the SQL.log file for 64bit where the values for SQLULEN , SQLLEN are not displayed properly andSQLExecDirectW function return error:”DIAG [22001] [Microsoft][SQL Server Native Client 10.0]String data, right truncation (0) “. :

PR0CNFG a78-fe4 ENTER SQLBindParameter

HSTMT 000000000431D2F0

UWORD 1

SWORD 1 <SQL_PARAM_INPUT>

SWORD -8 <SQL_C_WCHAR>

SWORD -9 <SQL_WVARCHAR>

SQLULEN SQLULEN SWORD 0

PTR 0x0000000005364EFA

SQLLEN SQLLENSQLLEN * SQLLEN *

PR0CNFG a78-fe4 EXIT SQLBindParameter with return code 0 (SQL_SUCCESS)

HSTMT 000000000431D2F0

UWORD 1

SWORD 1 <SQL_PARAM_INPUT>

SWORD -8 <SQL_C_WCHAR>

SWORD -9 <SQL_WVARCHAR>

SQLULEN SQLULEN SWORD 0

PTR 0x0000000005364EFA

SQLLEN SQLLEN SQLLEN *

What's the difference between Data Source and Server in connection string? And why the 1st doesn't work and 2nd does?

$
0
0

Hi All,

My colleague and I hit one tricky problem in C#, that when accessing the local SQL Server 2012, the code works fine using "server" in the connection string, while the connection will fail and timeout when we use "Data Source". Below is the sample code:

// server:

SqlConnection sc = new SqlConnection@"user id=sa;password=blabla;server=(local)\sql2012;database=Dummy.Database;connection timeout=30" );

// data source version:

SqlConnection sc = new SqlConnection@"Data Source=(local)\sql2012;Initial Catalog=Dummy.Database;User=sa;Password=blabla;MultiSubnetFailover=true" );

Then the 1st will pass when calling

sc.Open( );

while the 2nd cannot. What could be the root cause of the difference?

I'm using Win7 x64 with VS2013 Premium. Great thanks :-)

By the way, using the exact same settings, and the data source version still fails.

SqlConnection sc = new SqlConnection@"User=sa;Password=blabla;Data Source=(local)\sql2012;Initial Catalog=Dummy.Database;connection timeout=30" );

Just checked the Configuration manager, and named pipe/TCP IP/shared memory are all enabled. Firewall is on, but since I'm using localhost, the packets are looped back without touching the physical network, so should be fine?

Besides, I'm using

Microsoft SQL Server 2012 - 11.0.2100.60 (X64) Feb 10 2012 19:39:15 Developer Edition (64-bit) on Windows NT 6.1 (Build 7601: Service Pack 1)




Sql Server 2008 side effect after Windows 8.1 upgrade

$
0
0

Hi

After installing Windows 8.1 upgrade, I can't see a SQL SERVER instance.

I had Windows 8.0 Enterprise and SQL Server 2008 R2 installed and an instance named SVR12/SIMBD

All Windows 8.1 upgrade worked fine, no crashes no creepy messages

But now I can't to connect to the instance, nevertheless SQL Server Management Studio detects the instance  SVR12/SIMBD

Looking at services runnings there are a Service named SQL Server instead SQL Server (SIMDB)as before the OS upgrade

Thanks in advance for any help, I'm stuck


Saludos David


How to Update only a few duplicates in my table

$
0
0

Hi All,

I have a requirement to be met like this:

There is a table which has data like shown:

ID Name Key
a1 temp k1
a2 temp k1
a3 temp k1
a4 temp2 k1
a5 temp3 k2
a6 temp4 k3

As you can see , the names which are same should have same key. But by mistake, there is one other name ("temp2") with same key as "temp". I wan to change the key of this "temp2" to something else.

Similary there can be multiple entries like this. I want to update the key column with different value when I find that the name is not same but their key is different. Also need to make sure that the key for any of the "temp" entries are not changed.

How can I achieve this. Please help!

Thanks,

Vidya


Vidya Suryanarayana

SQL[native client] login timeout expired

$
0
0

Hi

I am the only one in my work that cannot login into SBO because of an error message that i get.

THE ERROR reads as follows:

SQL native client login timeout expired

SQL server error: '258'

SQL state: '08001'

[microsoft][SQL native client]

Unable to complete login process due to delay in prelogin response

Kindly assist as am the auditor and need to get into SAP business One.

'not exists' and 'not in' returning different results.

$
0
0

Hi,

 i have two queries - one works and the other one doesn't work.

select od.order_num from orders od

where od.order_num not in

         (select cu.order_num from customers cu) doesn't work

the other query:

select od.order_num from orders od

 where not exists

          (select cu.order_num from customers cu where cu.order_num = od.order_num) this works.

why?

borh cu.order_num and od.order_num are varchars.

Hot to join 5 more table

$
0
0

Please look at this tables. How to get the data like in "Result" Table.


table 1: Invoice


Warm Regards,


Log In failed for user error 18456

$
0
0

I have two servers. Both of the servers have two different database that will be joined together using SQL Server Agent. However, during this activity SQL Server is throwing a Log In Failed Error. The error shows:

1. The job failed. The job was invoked by User somedomain\someuser. The last step to run was step 2 [somedatabasename]. The job was requested to start at step 1 [somejobstepname].

2. Executed as user: NT SERVICE\SQLSERVERAGENT. Login failed for user 'somedomainname\servername'. [SQLSTATE 28000] [Error 18456]. The step failed.

Can anyone help me with this?

PS: One thing I forgot to mention. I can normally run a query using both the database in separate server. However whenever try to use server job agent, this connection problem is showing.

regards,

Sadat

Need help changing from SQL dbo to mdf file

$
0
0
My project was started using dbo is there a way to change this to an mdf without changing out the database.

An appliation seems to not connect to SQL Database

$
0
0

I have an application connecting to a back-end SQL server, last time my SQL database was destroyed, after restoring it, the application can't be opened, and I get below error, please suggest how to fix it!?

Cannot add data to existing table

$
0
0

Hello All,

I have a very trivial issue.  I have an existing test table in SQL and I use DBVisualizer client to connect to the server.

I have only six records in the table that I am testing.  I have a field called "SITE".  Within this field I have the following data:

Site:

NYC

LA

BOS

I am trying to import a csv file with 6 row of records, where I have records in there where 'site' = "BOS".

But when  I try to import, I get the following error:

"Violation of Unique Key constraint 'ix1_test'. Cannot insert duplicate key in object 'dbo.test'."

When I try to add the records manually, SQL allows me to add all data into the row, except when I try to add "BOS" into the site field.  Then the error happens.

What I do not understand is, I imported a previous csv with nine (9) records with multiple rows of records with "BOS" in the site field and had no issues.

Why is this occurring now?

Any help would be great!

Thanks everyone!

i m using vb10 ultimate sql-2008 on window8.1 my project is on run mode and i update window8 to 8.1.An error occurred while connecting to the database. The database might be unavailable. An exception of type 'System.Data.SqlClient.SqlException' occurred.

error when trying to connect to jdbc

$
0
0

I got this kind of error when I' trying to connect to jdbc:
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Error establishing socket.

I have checked the server by ping and there is no problem with the server. But why I can't connect. Here is my code:

import java.*;
public class Connect{
     private java.sql.Connection  con = null;
     private final String url = "jdbc:microsoft:sqlserver://";
     private final String serverName= "localhost";
     private final String portNumber = "1433";
     private final String databaseName= "VideoRental";
     private final String userName = "sa";
     private final String password = "sa";
     // Informs the driver to use server a side-cursor,
     // which permits more than one active statement
     // on a connection.
     private final String selectMethod = "cursor";

     // Constructor
     public Connect(){}

     private String getConnectionUrl(){
          return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
     }

     private java.sql.Connection getConnection(){
          try{
               Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
               con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
               if(con!=null) System.out.println("Connection Successful!");
          }catch(Exception e){
               e.printStackTrace();
               System.out.println("Error Trace in getConnection() : " + e.getMessage());
         }
          return con;
      }

     /*
          Display the driver properties, database details
     */

     public void displayDbProperties(){
          java.sql.DatabaseMetaData dm = null;
          java.sql.ResultSet rs = null;
          try{
               con= this.getConnection();
               if(con!=null){
                    dm = con.getMetaData();
                    System.out.println("Driver Information");
                    System.out.println("\tDriver Name: "+ dm.getDriverName());
                    System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
                    System.out.println("\nDatabase Information ");
                    System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
                    System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
                    System.out.println("Avalilable Catalogs ");
                    rs = dm.getCatalogs();
                    while(rs.next()){
                         System.out.println("\tcatalog: "+ rs.getString(1));
                    }
                    rs.close();
                    rs = null;
                    closeConnection();
               }else System.out.println("Error: No active Connection");
          }catch(Exception e){
               e.printStackTrace();
          }
          dm=null;
     }

     private void closeConnection(){
          try{
               if(con!=null)
                    con.close();
               con=null;
          }catch(Exception e){
               e.printStackTrace();
          }
     }
     public static void main(String[] args) throws Exception
       {
          Connect myDbTest = new Connect();
          myDbTest.displayDbProperties();
       }
}

The complete error message:

java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Error establis
hing socket.
        at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source
)
        at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
        at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
        at com.microsoft.jdbc.sqlserver.tds.TDSConnection.<init>(Unknown Source)

        at com.microsoft.jdbc.sqlserver.SQLServerImplConnection.open(Unknown Sou
rce)
        at com.microsoft.jdbc.base.BaseConnection.getNewImplConnection(Unknown S
ource)
        at com.microsoft.jdbc.base.BaseConnection.open(Unknown Source)
        at com.microsoft.jdbc.base.BaseDriver.connect(Unknown Source)
        at java.sql.DriverManager.getConnection(DriverManager.java:512)
        at java.sql.DriverManager.getConnection(DriverManager.java:171)
        at Connect.getConnection(Connect.java:25)
        at Connect.displayDbProperties(Connect.java:42)
        at Connect.main(Connect.java:78)
Error Trace in getConnection() : [Microsoft][SQLServer 2000 Driver for JDBC]Erro
r establishing socket.
Error: No active Connection
Press any key to continue . . . 

Connection with password to attached database

$
0
0

Hi all,

I have created a database (.mdf) with SQL Server Management Studio 2008R2. The only way I know how to connect it is with the 'attach' method and all is working. My understanding is that when the database is attached you don't have to attach it again, but that is the method I am using. Correct me if I am wrong but the .mdf file could be deleted when the database is attached (so I have been told). I have looked around but it is abracadabra to a newbie like me, don't know what to look for. What is the correct connection string after the database has been attached?

Another thing is that I don't know how to password protect this database. Looked around for this bit as well, but apparently it can not be done with a .mdf?

BTW I have created this database in the Express version and I have SBS-Std 2011 as well.

You time in this is much appreciated


Viewing all 4164 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>