Check ip and dns name - tsql

T-sql
Is it possible to check if ip-address and dns name is the same ?

Resolving the hostname to an IP address is something that can be easily done within a CLR stored procedure.
If you are new to CLR, you may want to start from the following articles:
Writing Your First CLR Stored Procedure
MSDN - Introduction to SQL Server CLR Integration
As for the code to resolve the hostname, this can be easily done in C# as follows:
string hostname = "stackoverflow.com";
IPAddress[] ipList = Dns.GetHostAddresses(hostname);
foreach (IPAddress ip in ipList)
{
// ... check each ip with an IP address you pass
// as a parameter.
}
If you are wondering why you receive a list of IP addresses, you may be interested in checking out the following Stack Overflow post:
Dns.GetHostEntry returns multiple IP addresses

HOST_NAME() returns the client's computer name.
This code resolves its ip address using ping and xp_cmdshell:
set nocount on
declare #ip varchar(255), #cmd varchar(100)
set #cmd = 'ping -n 1 ' + HOST_NAME()
create table #temptb (grabfield varchar(255))
insert into #temptb exec master.dbo.xp_cmdshell #cmd
select #ip = substring(grabfield, charindex('[',grabfield)+1,
charindex(']',grabfield)-charindex('[',grabfield)-1) from #temptb where left(grabfield,7) = 'Pinging'
print #ip
drop table #temptb
set nocount off
Source: http://www.sqlservercentral.com/Forums/Topic150196-8-1.aspx

you can use this query to get a lot of info about the connection:
SELECT
c.*,s.*
FROM sys.dm_exec_sessions s
INNER JOIN sys.dm_exec_connections c ON s.session_id=c.session_id
WHERE s.session_id = ##SPID
sys.dm_exec_connections.client_net_address = Host address of the client connecting to this server.
sys.dm_exec_connections.local_net_address = Represents the IP address on the server that this connection targeted. Available only for connections using the TCP transport provider.
you can try to see if there are duplicates IPs using a query like this:
SELECT
c.client_net_address, COUNT(*) AS CountOf
FROM sys.dm_exec_connections c
GROUP BY c.client_net_address
HAVING count(*)>1

Related

Postgres dblink: Getting "[2F003] ERROR: password is required Detail: Non-superusers must provide a password in the connection string."

When I try to run the following query, I get the following error message, and so my dblink queries are failing. All the hosts, roles, network connections and usernames have been set up correctly, yet it is not working.
select abc from dblink(
'port=5439 host=some_dbhost.mycompany.com dbname=my_db username=my_user password=<...>',
'select 1 as x') as t1 (abc int);
[2F003] ERROR: password is required Detail: Non-superusers must provide a password in the connection string.
No, there IS a password. What's going on?
This error message is TOTALLY misleading.
The REAL error is that the username was incorrectly specified as username.
The correct form specified as user (while the db is specified as dbname, so annoying!)
The fix is:
select abc from dblink(
'port=5439 host=some_dbhost.mycompany.com dbname=my_db user=my_user password=<...>',
'select 1 as x') as t1 (abc int);
So the error probably should have read as one of:
argument user missing
unknown argument username specified
instead of this stay up until 3am screaming to the heavens thing.

'h' format requires -32768 <= number <= 32767

I am trying to write a dataframe into postgreSQL database table.
When i write it into heroku's postgres SQL database, everything works fine. No problems.
For heroku postgresql, I use the connection string
connection_string = "postgresql+psycopg2://%s:%s#%s/%s" % (
conn_params['user'],
conn_params['password'],
conn_params['host'],
conn_params['dbname'])
However, when i try to write the dataframe into GCP's cloud sql table, i get the following error...
struct.error: 'h' format requires -32768 <= number <= 32767
The connection string i use for gcp cloud sql is as follows.
connection_string = \
f"postgresql+pg8000://{conn_params['user']}:{conn_params['password']}#{conn_params['host']}/{conn_params['dbname']}"
the command i use to write to the database is the same for both gcp and heroku
df_Output.to_sql(sql_tablename, con=conn, schema='public', index=False, if_exists=if_exists, method='multi')
I'd recommend using the Cloud SQL Python Connector to manage your connections and take care of the connection string for you. It supports the pg8000 driver and should help resolve your troubles.
from google.cloud.sql.connector import connector
import sqlalchemy
# configure Cloud SQL Python Connector properties
def getconn():
conn = connector.connect(
"project:region:instance",
"pg8000",
user="YOUR_USER",
password="YOUR_PASSWORD",
db="YOUR_DB"
)
return conn
# create connection pool to re-use connections
pool = sqlalchemy.create_engine(
"postgresql+pg8000://",
creator=getconn,
)
# query or insert into Cloud SQL database
with pool.connect() as db_conn:
# query database
result = db_conn.execute("SELECT * from my_table").fetchall()
# Do something with the results
for row in result:
print(row)
For more detailed examples refer to the README of the repository.

Full-text search using Windows Search Service and SQL Server 2008 R2

Currently I'm trying to query the Windows Search Service from a SQL Server 2008 R2 instance (also tested on SQL Server 2012) . Windows Search is being exposed as an OLE DB datasource, giving me several options to query the search index. When configuring a new Linked Server in SQL Server, Management Studio gives me the option to select the Microsoft OLE DB Provider for Search, implying that I should be able to connect to it from SQL Server. It turns out to be a challenge to get this up and running however. Below you'll find the error message I stumbled upon.
OLE DB provider "Search.CollatorDSO" for linked server "TESTSERVER" returned message "Command was not prepared.".
Msg 7399, Level 16, State 1, Line 2
The OLE DB provider "Search.CollatorDSO" for linked server "TESTSERVER" reported an error. Command was not prepared.
Msg 7350, Level 16, State 2, Line 2
Cannot get the column information from OLE DB provider "Search.CollatorDSO" for linked server "TESTSERVER".
Things get even more interesting. Although the Linked Server solution isn't working, I'm able to wrap code that queries Windows Search in a CLR Function (using MSDN: Querying the Index Programmatically) and use if successfully within SQL Server. This is however less desirable, because of the steps needed to set it up (deploying the library, configuring permissions, etc.). I've tried several parameter settings, without any luck. I've also tried enabling some of the Search.CollatorDSO provider options, like allowing the provider to be instantiated as an in-process server. I'm currently using the settings below. For security I'm using the login's current security context.
Provider: Microsoft OLE DB Provider for Search
Data source: (local)
Provider string: Provider=Search.CollatorDSO.1;EXTENDED?PROPERTIES="Application=Windows"
Location: -
Additionally I need to search network drives, can this be done using shared Windows libraries?
I'm aware more people have been struggling with this problem over the last few years. I'm wondering if someone has been able to get this up and running, or could point me in the right direction.
OLEDB Works
Normal ADO/OLEDB components can query the Windows Search service with the connection string:
provider=Search.CollatorDSO.1;EXTENDED PROPERTIES="Application=Windows"
And an example query:
SELECT TOP 100000 "System.ItemName",
"System.ItemNameDisplay",
"System.ItemType",
"System.ItemTypeText",
"System.Search.EntryID",
"System.Search.GatherTime",
"System.Search.HitCount",
"System.Search.Store",
"System.ItemUrl",
"System.Filename",
"System.FileExtension",
"System.ItemFolderPathDisplay",
"System.ItemPathDisplay",
"System.DateModified",
"System.ContentType",
"System.ApplicationName",
"System.KindText",
"System.ParsingName",
"System.SFGAOFlags",
"System.Size",
"System.ThumbnailCacheId"
FROM "SystemIndex"
WHERE CONTAINS(*,'"Contoso*"',1033)
You can try the query directly on SQL Server in SQL Server Management Studio by attempting to run:
SELECT *
FROM OPENROWSET(
'Search.CollatorDSO',
'Application=Windows',
'SELECT TOP 100 "System.ItemName", "System.FileName" FROM SystemIndex');
Which gives the errors:
OLE DB provider "Search.CollatorDSO" for linked server "(null)" returned message "Command was not prepared.".
Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "Search.CollatorDSO" for linked server "(null)" reported an error. Command was not prepared.
Msg 7350, Level 16, State 2, Line 1
Cannot get the column information from OLE DB provider "Search.CollatorDSO" for linked server "(null)".
Bonus Reading
Connect to Windows Search from SQL Server using Linked Server (January 2011)
Link with SQL Server (May 2008 - December 2012)
Trying to access Windows Search from SQL Server: An Appeal (July 2007)
Calling Windows Search from SQL Server 2008 (March 2011)
OLE DB provider "Search.CollatorDSO" returns "Command was not prepared" (April 2014 - Suggests CLR workaround)
Linked Server to Windows Search (February 2011)
MSDN Blogs: Query to the SYSTEMINDEX to read the Microsoft search results fails when using Search.CollatorDSO provider (August 2009 - suggests CLR workaround)
Vista Search (February 2007)
Have a look at this code..It may help
USE [YourDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROC [dbo].[SearchAllTables]
#SearchStr nvarchar(100)
AS
BEGIN
DECLARE #dml nvarchar(max) = N''
IF OBJECT_ID('tempdb.dbo.#Results') IS NOT NULL DROP TABLE dbo.#Results
CREATE TABLE dbo.#Results
([tablename] nvarchar(100),
[ColumnName] nvarchar(100),
[Value] nvarchar(max))
SELECT #dml += ' SELECT ''' + s.name + '.' + t.name + ''' AS [tablename], ''' +
c.name + ''' AS [ColumnName], CAST(' + QUOTENAME(c.name) +
' AS nvarchar(max)) AS [Value] FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) +
' (NOLOCK) WHERE CAST(' + QUOTENAME(c.name) + ' AS nvarchar(max)) LIKE ' + '''%' + #SearchStr + '%'''
FROM sys.schemas s JOIN sys.tables t ON s.schema_id = t.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
JOIN sys.types ty ON c.system_type_id = ty.system_type_id AND c .user_type_id = ty .user_type_id
WHERE t.is_ms_shipped = 0 AND ty.name NOT IN ('timestamp', 'image', 'sql_variant')
INSERT dbo.#Results
EXEC sp_executesql #dml
SELECT *
FROM dbo.#Results
END

How can I read bytes of file in tsql with server connection?

I use this code to read .mp3 file bytes in sql server. When I use local connection, It works correctly. But when I change connection to server(for example : 192.168.1.1 and windows authentication mode) and run it I get error.
DECLARE #Table1 TABLE(ID INT, AudioFileName VARCHAR(50),AudioFileColumn VARBINARY(MAX))
INSERT INTO #Table1 (ID, AudioFileName, AudioFileColumn)
SELECT 1, 'Name1', BulkColumn FROM
OPENROWSET (BULK N'\\fs1\Projects\Data\DATABASE\FAQ\File1.mp3', SINGLE_BLOB) AS x
SELECT * FROM #Table1
error :
Msg 4861, Level 16, State 1, Line 2 Cannot bulk load because the file
"\fs1\Projects\Data\DATABASE\FAQ\File1.mp3" could not be opened.
Operating system error code 5(failed to retrieve text for this error.
Reason: 15105).
How can I solve it ?
I guess SQL Server can't use BULK operations from non-local places. You passed a network address and it's not true. Maybe first of all you should upload your file on your server

"[NoHostAvailableException: All host(s) tried for query failed" exception occurs in connecting with cassandra cluster

var cluster: Cluster = null
var session: Session = null
cluster = Cluster.builder().addContactPoints("192.168.1.3","192.168.1.2").build()
val metadata = cluster.getMetadata()
printf("Connected to cluster: %s\n",
metadata.getClusterName())
metadata.getAllHosts() map {
case host =>
printf("Datatacenter: %s; Host: %s; Rack: %s\n",
host.getDatacenter(), host.getAddress(), host.getRack())
}
i am not able to connect to cassandra cluster using this code . It is giving me error that-
[NoHostAvailableException: All host(s) tried for query failed (tried: /192.168.1.3 ([/192.168.1.3] Cannot connect), /192.168.1.2 ([/192.168.1.2] Cannot connect))]
What is my mistake in above code.
Your code looks ok on first blush. The error suggests that Cassandra is not actually running on port 9042 (the default) on IPs "192.168.1.3","192.168.1.2"
If Cassandra is running on those IPs but it's another port you will need to use
int port = 19042; // Put the correct port here
cluster = Cluster.builder().addContactPoints("192.168.1.3","192.168.1.2").withPort(port).build()
Remote access to Cassandra is via its thrift port (although note that the JMX port can be used to perform some limited operations).
The thrift port is defined in cassandra.yaml by the rpc_port parameter, which defaults to 9160. Your cassandra node should be bound to the IP address of your server's network card - it shouldn't be 127.0.0.1 or localhost which is the loopback interface's IP, binding to this will prevent direct remote access. You configure the bound address with the rpc_address parameter in cassandra.yaml. Setting this to 0.0.0.0 says "listen on all network interfaces" which may or may not be suitable for you.
To make a connection you can use:
The cassandra-cli in the cassandra distribution's bin directory provides simple get / set / list operations and depends on Java
The cqlsh shell which provides CQL access to cassandra, this depends on Python
A higher level interface such as Apollo
you can use port 9042 and try to connect with ip local host or other machine as follows:
public String serverIP = "127.0.0.1"; //change ip with yours
//public String serverIP = "52.10.160.197"; //for prod
public String keyspace = "database name"; //for prod
//public String keyspace = "dbname_test"; //for staging
Cluster cluster = Cluster.builder().addContactPoint(serverIP).build();
Session session = cluster.connect(keyspace);