ruby connect SQL server by using Windows authentication - sql-server

I referred this page
http://www.codecapers.com/post/using-ruby-with-sql-server.aspx
my code
DBI.connect('DBI:ADO:Provider=SQLNCLI;Data Source=SQLSERVER001;Integrated Security=True;Initial Catalog=DB001') do | dbh |
# Replace mytable with the name of a table in your database.
dbh.select_all('select top 1000 * from history where type="35" ') do | row |
puts row
end
end
and trying to connect ruby with sql server by Windows authentication . But I got error
Unable to load driver 'ADO' (underlying error: uninitialized constant DBI::DBD::ADO)
Any idea?
Thanks

you don't need TinyTds, my system: ruby 1.9.3, ruby DevKit, sql server 2012, windows 7
install these gems first;
gem install dbi
gem install dbd-odbc
gem install activerecord-sqlserver-adapter
working script below connects, (not sure about the require 'pp')
require 'rubygems'
require 'DBI'
require 'pp'
server = 'XXXXX-LT0XXXX\XXX'
database = 'mydatabase'
conn = DBI.connect("DBI:ODBC:DRIVER={SQL Server};Server=#{server};Database=#{database};Trusted_Connection=yes") #==> sets up the connection
puts conn.connected?
if you pass the sql server instance directly into the connection string with a backslash it error but if passed as a variable it accepts

The page you are refering to is three years old.
Today you should use TinyTds for an easy way accessing
A MS SqlServer ( look at Github for it )

Related

Add SQL 2014 support to activerecord-sqlserver-adapter

We've be using the activerecord-sqlserver-adapter gem with sqlserver 2008 and everything works great. We just tried to deploy our Rails 3 app against a new sqlserver 2014 db and I get an error that says:
Currently, only 2005, 2008, 2010, 2011, and 2012 are supported. We got back Microsoft SQL Server 2014 - 12.0.2000.8 (X64)
A quick look at github shows that a small update was recently made to the sqlserver_adapter.rd to resolve this issue. I tried to update the gem and it turned into a bit of dependency hell and eventually looked as though I'd have to upgrade to rails 4 (which I don't particularly want to do right now) in order to get this fix.
So I thought I make my first attempt at a monkey patch and created an .rd in my initializers folder that incorporates the the changes to add sqlserver 2014 support:
module ConnectionAdapters
class SqlServerAdapter < AbstractAdapter
SUPPORTED_VERSIONS = [2005,2008,2010,2011,2012,2014]
# === SQLServer Specific (DB Reflection) ======================== #
def sqlserver_2014?
#database_year == 2014
end
end
end
My intention was to simply override the several lines of code in sqlserver_adapter.rd with change in the fix on github. However when I try to deploy, I now get an UnitializedConstant Error referring to AbstractAdapter.
How can make this patch work? Or this there a better way to accomplish this task?
I found a much better solution than a monkey patch. Turns out the guys over at activerecord-sqlserver-adapter updated the various releases so I just had to specify the version 3.2 branch with the SQLServer 2014 support fix. The following line in my gem file resolved the entire issue and we are now connecting to SqlServer '14
gem 'activerecord-sqlserver-adapter', :git => "git://github.com/rails-sqlserver/activerecord-sqlserver-adapter.git", :branch => "3-2-stable"
I have also addressed this problem with the Ruby 1.8.6 setup that I inherited.
The solution is not really as high-tech as proposed here.
The adapter interface is located at C:\ruby\lib\ruby\gems\1.8\gems\activerecord-sqlserver-adapter-2.3.4\lib\active_record\connection_adapters and is called sqlserver_adapter.rb.
I modified the following code to appear as such:
class SQLServerAdapter < AbstractAdapter
ADAPTER_NAME = 'SQLServer'.freeze
VERSION = '2.3.4'.freeze
DATABASE_VERSION_REGEXP = /Microsoft SQL Server\s+(\d{4})/
SUPPORTED_VERSIONS = [2000,2005,2008,2012,2016].freeze
LIMITABLE_TYPES = ['string','integer','float','char','nchar','varchar','nvarchar'].freeze
LOST_CONNECTION_EXCEPTIONS = {
:odbc => ['ODBC::Error'],
:ado => []
}
LOST_CONNECTION_MESSAGES = {
:odbc => [/link failure/, /server failed/, /connection was already closed/, /invalid handle/i],
:ado => []
}
The only thing I did to modify the adapter code was change [2000,2005,2008] to [2000,2005,2008,2012,2016].
I then used the ODBC Datasource Administrator (32-bit) to configure to use the "SQL Server Native Client 11.0" for the Sql Server 2016 instance.
This last step is the really important one in the ODBC adapter setup.
The "SQL Server" adapter may default to a 64-bit connection which gives the following error when trying to connect to the database:
#<ODBC::Error: S1090 (0) [Microsoft][ODBC Driver Manager] Invalid string or buffer length>.
I am retrofitting an obsolete 2008R2 server set of legacy Ruby programs running on Apache to a new Windows Server 2016 setup, and don't have the luxury of debugging the legacy Ruby code to make it work with a newer version of Ruby and Ruby on Rails.
This low-tech solution fully meets our operational needs, budget and time constraints.
I did the following with v 4.1.8:
module ActiveRecord
module ConnectionAdapters
class SQLServerAdapter < AbstractAdapter
SUPPORTED_VERSIONS << 2014
# === SQLServer Specific (DB Reflection) ======================== #
def sqlserver_2014?
#database_year = 2014
end
end
end
end

Error when trying to install sonarqube on SQL Server 2008

When I try to install sonarqube database I get some errors and database is not created
ActiveRecord::JDBCError: The driver encountered an unknown error: unable to choose type for timestamp from:
["datetime2", "datetime"]
initialize at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/connection.rb:66
initialize at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:31
jdbc_connection at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/connection_methods.rb:6
send at org/jruby/RubyKernel.java:2227
new_connection at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:223
checkout_new_connection at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:245
checkout at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:188
loop at org/jruby/RubyKernel.java:1519
checkout at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:184
mon_synchronize at jar:file:/C:/sonarqube/web/WEB-INF/lib/jruby-complete-1.7.9.jar!/META-INF/jruby.home/lib/ruby/1.8/monitor.rb:191
checkout at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:183
connection at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:98
retrieve_connection at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:326
retrieve_connection at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/connection_specification.rb:123
connection at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/connection_specification.rb:115
initialize at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:440
up at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401
migrate at C:/sonarqube/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383
upgrade_and_start at C:/sonarqube/web/WEB-INF/config/../lib/database_version.rb:62
automatic_setup at C:/sonarqube/web/WEB-INF/config/../lib/database_version.rb:74
(root) at C:/sonarqube/web/WEB-INF/config/environment.rb:239
load at org/jruby/RubyKernel.java:1094
(root) at file:/C:/sonarqube/web/WEB-INF/lib/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1
load_environment at file:/C:/sonarqube/web/WEB-INF/lib/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25
load_environment at file:/C:/sonarqube/web/WEB-INF/lib/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79
i was reading about and looks like database driver is not working alright
Any clues about how can i get this working on SQL Server?
There might be a problem with the locale settings of the database. In my case it helped to set the language for the sonarqube database user to "English". See here.
After a few tries, I changed the SQL driver (sqljdbc4.jar) to one directly from Microsoft, it looks like my previous driver was third party modified.
http://www.microsoft.com/en-us/download/confirmation.aspx?id=21599 this is the original mssql driver form jdbc.
http://www.sezok.de/sonar/sonar.html this guide was helpful too.
after changing driver, everything works OK

How to Connect R to Oracle?

I need to connect R to oracle and I have been unsuccessful so far. I downloaded two packages: RODBC & RODM.
This is the statement that I've been using:
DB <- odbcDriverConnect("DBIORES1",uid="mhala",pwd="XXXXXXX")
But I get this error:
Error in odbcDriverConnect("DBIORES1", uid = "mhalagan", pwd = "XXXXXXX") :
unused argument(s) (uid = "mhalagan", pwd = "XXXXXXX")
What information do I need to be able to connect to an oracle database? Am I using the correct package?
See the help page for odbcDriverConnect(). odbcDriverConnect() does not accept uid or pwd arguments. You probably meant to use odbcConnect() instead:
odbcConnect(dsn = "DBIORES1", uid = "mhala", pwd = "XXXXXXX")
In addition to the RODBC package, there is the RODM package, which I believe is specifically designed for Oracle databases and is further described here: http://www.oracle.com/technetwork/articles/datawarehouse/saternos-r-161569.html . I do not use Oracle databases, so cannot comment on advantages of the two packages.
RJDBC worked just fine for me. You just need to have Oracle-thin driver jar file and configure the connection like:
> install.packages("RJDBC")
> library(RJDBC)
> drv <- JDBC("oracle.jdbc.driver.OracleDriver","/path/to/driver/com/oracle/oracle-thin/11.2.0.1.0/oracle-thin-11.2.0.1.0.jar”)
> conn <- dbConnect(drv, "jdbc:oracle:thin:#database:port:schema”, “user”, “passwd”)
and then is ready to perform some queries.
JA.
I've had success in the past connecting to Oracle databases from R with RJDBC. I found it easier to get going as I just grabbed the connection string that I'd used successfully inside the java based GUI I was using at the time and like magic it "just works"(tm).
Did you install the oracle ODBC client/driver? You will need that if you are going to use the ODBC R package. Go to oracle instant client download get the client for your OS. install them and then proceed to configure the ODBC and test the connection outside of R then install the R and RODBC and test inside R.

Reading data from Microsoft SQL Server into R

Is it possible to read the data stored in MS SQL server from R interface?
If it is I would be also thankful if anyone could show the way to do it.
Tried the RODBC package already?
http://cran.r-project.org/web/packages/RODBC/index.html
There's also the RJDBC package : http://www.rforge.net/RJDBC/
See also :
http://www.r-bloggers.com/connecting-to-sql-server-from-r-using-rjdbc/
I've applied RODBC function suggested by other users. LinkSQL Server RODBC Connection
library(RODBC)
dbhandle <- odbcDriverConnect('driver={SQL
Server};server=mysqlhost;database=mydbname;trusted_connection=true')
res <- sqlQuery(dbhandle, 'select * from information_schema.tables')
change two variables based on your Data table. 'server=mysqlhost;database=mydbname'
Niko, What operating system are you running? The answer to your question varies, depending on the platform you are using.
If you are using Windows (of any stripe), connecting to MSSQL Server via ODBC (RODBC) makes the most sense. When I connect to a MSSQL Server on Linux, I use JDBC as suggested by Joris. I would assume that JDBC is also the best solution for Macs, but I could very well be wrong.
There another option that seems to outperform RODBC and RJDBC
rsqlserver package written by agstudy.
Installation:
require(devtools)
install_github("rClr", 'jmp75')
install_github('rsqlserver', 'agstudy',args='--no-multiarch')
The latest library that allows you to connect to MSSQL databases is RSQLServer.
It can be found on GitHub and CRAN.
You can connect to SQL server using DBI package, which I think works better than RODBC. DBI is a database interface package for relational databases. for SQL I use it along with odbc package as in the example below.
Visit this page for full details: Database Queries with R
An example would be as follows
library(DBI)
library(odbc)
con <- dbConnect(odbc::odbc(), .connection_string = "driver={SQL Server}; server= ServerName; database=DatabaseName; trusted_conncetion=true"))
dbGetQuery(con,'Select * from Table')
library("RODBC")
dbhandle <- odbcDriverConnect('driver={SQL Server};server=;database=;trusted_connection=true')
currTableSQL<-paste("SELECT *
FROM ",sep="")
currTableDF<-sqlQuery(dbhandle,currTableSQL)

How can I determine installed SQL Server instances and their versions?

I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.
At a command line:
SQLCMD -L
or
OSQL -L
(Note: must be a capital L)
This will list all the sql servers installed on your network. There are configuration options you can set to prevent a SQL Server from showing in the list. To do this...
At command line:
svrnetcn
In the enabled protocols list, select 'TCP/IP', then click properties. There is a check box for 'Hide server'.
You could query this registry value to get the SQL version directly:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\90\Tools\ClientSetup\CurrentVersion
Alternatively you can query your instance name and then use sqlcmd with your instance name that you would like:
To see your instance name:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names
Then execute this:
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
If you are using C++ you can use this code to get the registry information.
All of the instances installed should show up in the Services Snap-In in the Microsoft Management Console. To get the instance names, go to Start | Run | type Services.msc and look for all entries with "Sql Server (Instance Name)".
-- T-SQL Query to find list of Instances Installed on a machine
DECLARE #GetInstances TABLE
( Value nvarchar(100),
InstanceNames nvarchar(100),
Data nvarchar(100))
Insert into #GetInstances
EXECUTE xp_regread
#rootkey = 'HKEY_LOCAL_MACHINE',
#key = 'SOFTWARE\Microsoft\Microsoft SQL Server',
#value_name = 'InstalledInstances'
Select InstanceNames from #GetInstances
I know this thread is a bit old, but I came across this thread before I found the answer I was looking for and thought I'd share. If you are using SQLExpress (or localdb) there is a simpler way to find your instance names.
At a command line type:
> sqllocaldb i
This will list the instance names you have installed locally. So your full server name should include (localdb)\ in front of the instance name to connect. Also, sqllocaldb allows you to create new instances or delete them as well as configure them. See: SqlLocalDB Utility.
If you just want to see what's installed on the machine you're currently logged in to, I think the most straightforward manual process is to just open the SQL Server Configuration Manager (from the Start menu), which displays all the SQL Services (and only SQL services) on that hardware (running or not). This assumes SQL Server 2005, or greater; dotnetengineer's recommendation to use the Services Management Console will show you all services, and should always be available (if you're running earlier versions of SQL Server, for example).
If you're looking for a broader discovery process, however, you might consider third party tools such as SQLRecon and SQLPing, which will scan your network and build a report of all SQL Service instances found on any server to which they have access. It's been a while since I've used tools like this, but I was surprised at what they found (namely, a handful of instances that I didn't know existed). YMMV. You might Google for details, but I believe this page has the relevant downloads: http://www.sqlsecurity.com/Tools/FreeTools/tabid/65/Default.aspx
SQL Server permits applications to find SQL Server instances within the current network. The SqlDataSourceEnumerator class exposes this information to the application developer, providing a DataTable containing information about all the visible servers. This returned table contains a list of server instances available on the network that matches the list provided when a user attempts to create a new connection, and expands the drop-down list containing all the available servers on the Connection Properties dialog box. The results displayed are not always complete.
In order to retrieve the table containing information about the available SQL Server instances, you must first retrieve an enumerator, using the shared/static Instance property:
using System.Data.Sql;
class Program
{
static void Main()
{
// Retrieve the enumerator instance and then the data.
SqlDataSourceEnumerator instance =
SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();
// Display the contents of the table.
DisplayData(table);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
private static void DisplayData(System.Data.DataTable table)
{
foreach (System.Data.DataRow row in table.Rows)
{
foreach (System.Data.DataColumn col in table.Columns)
{
Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
}
Console.WriteLine("============================");
}
}
}
from msdn http://msdn.microsoft.com/en-us/library/a6t1z9x2(v=vs.80).aspx
One more option would be to run SQLSERVER discovery report..go to installation media of sqlserver and double click setup.exe
and in the next screen,go to tools and click discovery report as shown below
This will show you all the instances present along with entire features..below is a snapshot on my pc
SQL Server Browser Service http://msdn.microsoft.com/en-us/library/ms181087.aspx
This query should get you the server name and instance name :
SELECT ##SERVERNAME, ##SERVICENAME
If you are interested in determining this in a script, you can try the following:
sc \\server_name query | grep MSSQL
Note: grep is part of gnuwin32 tools
From Windows command-line, type:
SC \\server_name query | find /I "SQL Server ("
Where "server_name" is the name of any remote server on which you wish to display the SQL instances.
This requires enough permissions of course.
I had the same problem. The "osql -L" command displayed only a list of servers but without instance names (only the instance of my local SQL Sever was displayed).
With Wireshark, sqlbrowser.exe (which can by found in the shared folder of your SQL installation) I found a solution for my problem.
The local instance is resolved by registry entry. The remote instances are resolved by UDP broadcast (port 1434) and SMB.
Use "sqlbrowser.exe -c" to list the requests.
My configuration uses 1 physical and 3 virtual network adapters.
If I used the "osql -L" command the sqlbrowser displayed a request from one of the virtual adaptors (which is in another network segment), instead of the physical one.
osql selects the adpater by its metric. You can see the metric with command "route print".
For my configuration the routing table showed a lower metric for teh virtual adapter then for the physical. So I changed the interface metric in the network properties by deselecting automatic metric in the advanced network settings.
osql now uses the physical adapter.
The commands OSQL -L and SQLCMD -L will show you all instances on the network.
If you want to have a list of all instances on the server and doesn't feel like doing scripting or programming, do this:
Start Windows Task Manager
Tick the checkbox "Show processes from all users" or equivalent
Sort the processes by "Image Name"
Locate all sqlsrvr.exe images
The instances should be listed in the "User Name" column as MSSQL$INSTANCE_NAME.
And I went from thinking the poor server was running 63 instances to realizing it was running three (out of which one was behaving like a total bully with the CPU load...)
I just installed Sql server 2008, but i was unable to connect to any database instances.
The commands #G Mastros posted listed no active instances.
So i looked in services and found that the SQL server agent was disabled. I fixed it by setting it to automatic and then starting it.
I had this same issue when I was assessing 100+ servers, I had a script written in C# to browse the service names consist of SQL. When instances installed on the server, SQL Server adds a service for each instance with service name. It may vary for different versions like 2000 to 2008 but for sure there is a service with instance name.
I take the service name and obtain instance name from the service name. Here is the sample code used with WMI Query Result:
if (ServiceData.DisplayName == "MSSQLSERVER" || ServiceData.DisplayName == "SQL Server (MSSQLSERVER)")
{
InstanceData.Name = "DEFAULT";
InstanceData.ConnectionName = CurrentMachine.Name;
CurrentMachine.ListOfInstances.Add(InstanceData);
}
else
if (ServiceData.DisplayName.Contains("SQL Server (") == true)
{
InstanceData.Name = ServiceData.DisplayName.Substring(
ServiceData.DisplayName.IndexOf("(") + 1,
ServiceData.DisplayName.IndexOf(")") - ServiceData.DisplayName.IndexOf("(") - 1
);
InstanceData.ConnectionName = CurrentMachine.Name + "\\" + InstanceData.Name;
CurrentMachine.ListOfInstances.Add(InstanceData);
}
else
if (ServiceData.DisplayName.Contains("MSSQL$") == true)
{
InstanceData.Name = ServiceData.DisplayName.Substring(
ServiceData.DisplayName.IndexOf("$") + 1,
ServiceData.DisplayName.Length - ServiceData.DisplayName.IndexOf("$") - 1
);
InstanceData.ConnectionName = CurrentMachine.Name + "\\" + InstanceData.Name;
CurrentMachine.ListOfInstances.Add(InstanceData);
}
Will get the instances of SQL server
reg query "HKLM\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL"
or Use
SQLCMD -L
Here is a simple method:
go to
Start then
Programs then
Microsoft SQL Server 2005 then
Configuration Tools then
SQL Server Configuration Manager then
SQL Server 2005 Network Configuration then
Here you can locate all the instance installed onto your machine.
I know its an old post but I found a nice solution with PoweShell where you can find SQL instances installed on local or a remote machine including the version and also be extend get other properties.
$MachineName = ‘.’ # Default local computer Replace . with server name for a remote computer
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(‘LocalMachine’, $MachineName)
$regKey= $reg.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL" )
$values = $regkey.GetValueNames()
$values | ForEach-Object {$value = $_ ; $inst = $regKey.GetValue($value);
$path = "SOFTWARE\\Microsoft\\Microsoft SQL Server\\"+$inst+"\\MSSQLServer\\"+"CurrentVersion";
#write-host $path;
$version = $reg.OpenSubKey($path).GetValue("CurrentVersion");
write-host "Instance" $value;
write-host "Version" $version}
If your within SSMS you might find it easier to use:
SELECT ##Version

Resources