SQL Server ODBC connection failed - sql-server

I am trying to connect SQL server using ODBC.
Could some one help interpreting what this error is and how this can be rectified?
Kindly note that there are no password issues as I use the same credentials to connect to the SQL server using Aqua studio.
dbhandle <- odbcDriverConnect('driver={SQL Server};server=SQLBBAQA;database=bbadb;uid = "aaa_bbb_ccc", pwd = "aaabbbccc123&" ')
Warning messages:
1: In odbcDriverConnect("driver={SQL Server};server=SQLBBAQA;database=bbadb;uid = \"aaa_bbb_ccc\", pwd = \"aaabbbccc123&\" ") :
[RODBC] ERROR: state 08001, code 17, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied.
2: In odbcDriverConnect("driver={SQL Server};server=SQLBBAQA;database=bbadb;uid = \"aaa_bbb_ccc\", pwd = \"aaabbbccc123&\" ") :
[RODBC] ERROR: state 01000, code 2, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).
3: In odbcDriverConnect("driver={SQL Server};server=SQLBBAQA;database=bbadb;uid = \"aaa_bbb_ccc\", pwd = \"aaabbbccc123&\" ") :
[RODBC] ERROR: state 01S00, code 0, message [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute
4: In odbcDriverConnect("driver={SQL Server};server=SQLBBAQA;database=bbadb;uid = \"aaa_bbb_ccc\", pwd = \"aaabbbccc123&\" ") :
ODBC connection failed

I see multiple mistakes in the connection string:
server=SQLRAPQA should be in the form server=MACHINE\INSTANCE. Use server=.\SQLRAPQA if the instance is located on the same machine.
Remove all whitespaces.
Use ; as separator, not ,.
As referenced by zx8754, in RODBC odbcDriverConnect() Connection Error it is shown that a connection string should look like:
'driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456' . Note the double occurences of \, this seems to be rodbc specific.

Related

Using pymssql to connect to SQL Server in Windows

Pymssql -V:2.2.1
Python -V: 3.8
DB: SQL Server 2008 R2
This is my code:
class read_sql(object):
def __init__(self):
# 服务器名
self.server = HOST_24
# 用户名
self.user = SQL_SERVER_USER
# 密码
self.password = SQL_SERVER_PASSWORD
# 数据库名
self.database = PUBMED_DB
# 连接数据库
try:
self.conn = pymssql.connect(self.server, self.user, self.password, self.database)
# 创建cursor缓冲区,用来存放sql语句
self.cursor = self.conn.cursor()
except Exception as e:
print(e)
raise ValueError('数据库链接实例化出错')
def query(self, query_str):
# 输入query_str查询语句,内容返回到cursor缓冲区内
self.cursor.execute(query_str)
# 接收全部的返回结果行.
row = self.cursor.fetchall()
return row
if __name__ == "__main__":
sql_data = read_sql()
row = sql_data.query("SELECT TOP 1 * FROM JinMo_CheckTable order by id desc")
print(row)
This is my first time connecting to SQL Server!
I get this error:
pymssql._mssql.MSSQLDatabaseException: (18456, b"\xe7\x94\xa8\xe6\x88\xb7 'sa' \xe7\x99\xbb\xe5\xbd\x95\xe5\xa4\xb1\xe8\xb4\xa5\xe3\x80\x82DB-Lib error message 20018, severity 14:
General SQL Server error: Check messages from the SQL Server
DB-Lib error message 20002, severity 9:
Adaptive Server connection failed (192.168.0.24)
DB-Lib error message 20002, severity 9:
Adaptive Server connection failed (192.168.0.24)
Please give me some suggestions - thanks !

bcp error ignore delimiters (String data, right truncation)

So I'm using bcp to import a csv file to my SQL database.
This is the command:
bcp table in D:\temp\some_file.csv -T -S serverName -d dbName -F 2 -c -t "," -r "\n"
I'm getting the following error when I try to import the file:
Starting copy...
SQLState = 22001, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]String data, right truncation
SQLState = 22001, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]String data, right truncation
24 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total : 31 Average : (774.19 rows per sec.)
The last 2 columns of the csv file contains User full name ("surname, name"), Customer full name ("surname, name")
SYS Hostname,SYS Domain,User Name,Customer Name
server1,test.com,"surname, name","surname2, name2"
Is it possible to ignore the , between the ""?
Thanks
EDIT:
As #AlwaysLearning said:
You have a Quoted CSV file which is something the bcp.exe process
cannot handle. As per RFC4180 your data row has four fields server1
test.com surname, name and surname2, name2 but bcp.exe only sees the
commas so thinks it is six fields. Consider alternative methods - such
as using a PowerShell script to load the data file into a DataTable
using Import-Csv and then insert the DataTable using an SqlBulkCopy
object over an SQL connection
There is any other option to import a CSV file by command line o SQL script?
Thanks
See this response here. BCP can work so long as the quoted fields are always quoted, on every line of the file. Regardless of whether the name value contains a comma or not. The question below is regarding export, but it works the same on import. You essentially tell BCP that the delimeter is "," and not just ,
SQL Server BCP Export where comma in SQL field

Pyodbc error in Python How to fix connection

I am trying to Connect to sql server database but I get this error:
File "C:\Python37-32\SqlVersionpr_import.py", line 528, in proceed
with pyodbc.connect('DRIVER={ODBC Driver 17 for SQL
Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) as myDbConn:
pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found
and no default driver specified (0) (SQLDriverConnect)')
My code:
server = '***********'
database = '*****'
username = '***********'
password = '***********'
with pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) as myDbConn:
with myDbConn.cursor(as_dict=True) as cursor:
cursor.execute(''' select * from empInfo where ssn = %s and storeid = %s ;''',(strLastSsn,stono))
emp_rows = cursor.fetchall() or []

[Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '#P1':

[Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax
near '#P1'. The SQL being executed was: call
sp_inX_Test('10105','Test')' in
C:\wamp64\www\Test\vendor\yiisoft\yii2\db\Schema.php:633 Stack trace:
I am getting this issue when I try to call stored procedure with two parameters.
Here is my php code
$sql = "call sp_inX_Test(:route_code,:name)";
$params = [ ':route_code'=> Yii::$app->request->post('RouteCode'),':name'=> Yii::$app->request->post('Name')];
$command = Yii::$app->db->createCommand($sql,$params);
$areaPerformance = $command->queryAll();
I tried this , working only , but getting issue if the parameter has space inside.
$command = Yii::$app->db->createCommand("sp_inX_Test #RouteCode=".Yii::$app->request->post('RouteCode').",
#Name=".Yii::$app->request->post('Name')."");
$areaPerformance = $command->queryAll();
Next exception 'yii\db\Exception' with message
SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL
Server]Incorrect syntax near 'Foil'. The SQL being executed was:
sp_inX_Test #RouteCode=10103, #Name=Aluminium Foil'
in C:\wamp64\www\Mahroos\vendor\yiisoft\yii2\db\Schema.php:633

R connection to MS SQL

Using R I am trying to connect to MS SQL 2014 on an Azure VM (not windows authentication)
library(RODBC)
conn <- odbcDriverConnect(connection = "Driver=SQL Server;Server=someinternetmachine.cloudapp.net;Database=MyDatabase;Uid=MyUsername;Pwd=MyPassword;")
queryResult <- sqlQuery(conn, "SELECT top 10 * FROM sometable")
With RODBC is there anywhere to do this using just a connection string (no DSN)?
Using the above I get the below errors
Warning messages:
1: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
[RODBC] ERROR: state 08001, code 6, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]Specified SQL server not found.
2: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
[RODBC] ERROR: state 01000, code 11001, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).
3: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
ODBC connection failed
Did you choose public provisioning for the VM in Azure? Additionally, you need to open the ports for SQL Server in Windows Firewall (port number depends on default or named instance). Also, in case of named instance if you are using dynamic ports then SQL Browser also needs to be opened up. More information can be found in the link here.
Managed to get this working with
driver.name <- "SQL Server"
db.name <- "master"
host.name <- "someinternetmachine.cloudapp.net"
port <- ""
server.name <- "someinternetmachine.cloudapp.net"
user.name <- "MyUsername"
pwd <- "MyPassword"
# Use a full connection string to connect
con.text <- paste("DRIVER=", driver.name,
";Database=", db.name,
";Server=", server.name,
";Port=", port,
";PROTOCOL=TCPIP",
";UID=", user.name,
";PWD=", pwd, sep = "")
con1 <- odbcDriverConnect(con.text)
res <- sqlQuery(con1, 'select * from information_schema.tables')
odbcCloseAll()

Resources