· 9 years ago · Apr 11, 2017, 11:26 PM
1require 'tiny_tds'
2@client = TinyTds::Client.new username: 'sa', password: 'Yukon900',
3 host: 'localhost', port: 1433
4puts 'Connecting to SQL Server'
5
6if @client.active? == true then puts 'Done' end
7
8def execute(sql)
9 @client.execute(sql).do
10 true
11end
12
13# create database
14puts "Dropping and creating database 'SampleDB'"
15execute("DROP DATABASE IF EXISTS [SampleDB]; CREATE DATABASE [SampleDB];")
16
17# create sample table with data
18puts "Creating sample table with data"
19puts ("USE SampleDB; CREATE TABLE Employees (Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY, Name NVARCHAR(50), Location NVARCHAR(50))
20 INSERT INTO Employees (Name, Location) VALUES (N'Jared', N'Australia'), (N'Nikita', N'India'), (N'Tom', N'Germany')")
21
22# insert new employee
23puts "Inserting new employee Jake into Employees table"
24execute("INSERT INTO Employees (Name, Location) VALUES (N'Jake', N'United States')")
25
26
27# update location for employee
28puts "Updating Location for Nikita"
29execute("UPDATE Employees SET Location = N'United States' WHERE NAME = N'Nikita'")
30
31# delete employee
32puts "Deleting employee Jared"
33execute("DELETE FROM Employees WHERE NAME = N'Jared'")
34
35# read all employees
36puts "Reading data from table"
37@client.execute("SELECT * FROM Employees").each do |row|
38 puts row
39end
40
41puts "All done."
42
43@client.close