How to connect to Local MS SQL Express Edition using Python 3 - sql-server

I am trying to connect to local MS SQL Express Edition. I am using canopy for Python editing.
Code:
import pymssql
conn = pymssql.connect(server='******\SQLEXPRESS',user = 'MEA\*****',password='*****',database='BSEG')
cursor = conn.cursor()
cursor.execute('SELECT * FROM Table')
print(cursor.fetchone())
conn.close()
Error::
pymssql.pyx in pymssql.connect (pymssql.c:10734)()
_mssql.pyx in _mssql.connect (_mssql.c:21821)()
_mssql.pyx in _mssql.MSSQLConnection.init (_mssql.c:5917)()
ValueError: too many values to unpack (expected 2)

user = 'MEA\*****',password='*****'
MEA\***** seems to be Windows login, in this case you shouldn't pass in any password, your user name is enough, but you also should use Integrated security or Trusted parameter in your connection string
It should be smth like this:
server='******\SQLEXPRESS',Trusted_Connection=yes,database='BSEG'

Related

Connection to different SQL Server databases

I want to create a connection to a SQL Server Database using a python script that you will see below. In fact, I managed to connect to a single database but I want to make a loop on a database list so that every time I point to a database I can connect directly.
My question is how can I make the name of the database as a variable. Could you help me please?! Thank you in advance
from os import listdir
from os.path import isfile, join
import pyodbc
import pandas as pd
mypath = 'C:\\Users\\DataBaseList'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for i in range (len(onlyfiles)) :
print (onlyfiles[i])
connection = pyodbc.connect("Driver={ODBC Driver 11 for SQL Server};"
"Server=FR0010APP31;"
"Database= Base;"
"uid=*****;pwd=*****")
cursor = connection.cursor()
sql='Select * from Activity'
df= pd.read_sql(sql, connection)
df.to_csv('DatabaseFile')

Connect to a Highly-Available SQL Server from R

We've recently upgraded to SQL Server 2012 which is Highly-Available DR enabled. When connecting using SSMS we need to specify MultiSubnetFailover=True additional connection option + increase timeouts.
How can we replicate this in R? Without this, we observe sporadic connectivity/timeout issues.
Related, but for Python
> packageVersion('RODBC')
[1] '1.3.6'
> packageVersion('Base')
[1] '2.15.2'
If you are using a Data Source Name, you can add extra arguments to odbcConnect
odbcConnect(DSN, uid = "user_name", pwd = "password", MultiSubnetFailover = "True")
If you are using a connection string, you just need to add the arguments in your string.
odbcDriverConnect("driver=DRIVER; server=SERVER; database=DATABASE; uid=user_name; pwd=password; MultiSubnetFailover = True")

Cannot connect to Redshift database with a driver even though play.ap.db.DB can do this for the same driver

I am trying to connect to a redshift server and run some sql commands. Here is the code that I have written:
Class.forName("org.postgresql.Driver")
val url: String = s"jdbc:postgres://${user}:${password}#${host}:${port}/${database}"
val connection: Connection = DriverManager.getConnection(url, user, password)
val statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
val setSearchPathQuery: String = s"set search_path to '${schema}';"
statement.execute(setSearchPathQuery)
But I am getting the following error:
java.sql.SQLException: No suitable driver found for jdbc:postgres://user:password#host:port/database
But when I am using play framework's default database library with the same configuration, then I am able to connect to database successfully. Below is the configuration for the default database:
db.default.driver=org.postgresql.Driver
db.default.url="postgres://username:password#hostname:port/database"
db.default.host="hostname"
db.default.port="port"
db.default.dbname = "database"
db.default.user = "username"
db.default.password = "password"
The problem was with the url. The correct format for the url is:
jdbc:postgresql://hostname:port/database

Coldfusion 9 DSN less Connection MSSQL 2008 Windows Authentication

Update:
Though the original question asked about windows authentication, any connection method would be fine. As long as it does not require creating a DSN.
I'm trying to connect my database with Windows Authentication. Here is the code.
Please advise. Thanks.
<cfscript>
classLoader = createObject("java", "java.lang.Class");
classLoader.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dm = createObject("java","java.sql.DriverManager");
dburl = "jdbc:sqlserver://192.168.3.150:1433;databasename=RsDB;integratedSecurity=true";
con = dm.getConnection(dburl,"", "");
st = con.createStatement();
rs = st.ExecuteQuery("SELECT top 10 * FROM pa (nolock)");
q = createObject("java", "coldfusion.sql.QueryTable").init(rs);
</cfscript>
<cfoutput query="q">
email = #email#<br />
</cfoutput>
ERROR :
Error Occurred While Processing Request
This driver is not configured for integrated authentication.
(Ignoring your question for a moment, ... )
While it is possible to do it with a manual connection, is there a specific reason you cannot just use a standard DSN? That would be far more efficient and require a lot less code/cleanup. Not to mention that it avoids some of the common pitfalls of manual connections.
AFAIK, you can set the DSN to use windows authentication, by entering AuthenticationMethod=Type2 under "Show Advanced Settings > Connection String". Leave the "username" and "password" fields blank.
<cfquery name="qTest" datasource="YourDSN">
SELECT SYSTEM_USER AS LoginName, DB_NAME() AS DatabaseName
</cfquery>
<cfdump var="#qTest#" label="Show Connection Settings">
*NB: The DSN will use the CF Service user account, so adjust as needed
Update:
If you absolutely must use a manual connection, try using the built in driver instead of the JDBCODBC bridge. However, be sure to always close the database objects. Otherwise, open connections will start to pile up and bad things will happen.
Keep in mind, opening database connections is expensive. By not using a DSN, you lose out on the benefits of connection pooling. So overall this method will be less efficient than simply using a DSN.
<cfscript>
classLoader = createObject("java", "java.lang.Class");
classLoader.forName("macromedia.jdbc.MacromediaDriver");
dm = createObject("java","java.sql.DriverManager");
dburl = "jdbc:macromedia:sqlserver://127.0.0.1:1433;databasename=RsDB;AuthenticationMethod=Type2";
con = dm.getConnection(dburl);
st = con.createStatement();
rs = st.ExecuteQuery("SELECT getDate() AS TestValue");
q = createObject("java", "coldfusion.sql.QueryTable").init(rs);
// ALWAYS close all objects!
rs.close();
st.close();
con.close();
writeDump(q);
</cfscript>
You could also use the SQL Server JDBC Driver instead. See also Connecting with Integrated Authentication On Windows. However, that requires adding the driver jars and a DLL (sqljdbc_auth.dll) to the server, which it sounds like you cannot do.
Driver Class: com.microsoft.sqlserver.jdbc.SQLServerDriver
URL: jdbc:sqlserver://localhost:1433;integratedSecurity=true;
Found an example here that shows the username and password in the URL.
<cfset connection = driverManager
.getConnection("jdbc:mysql://localhost:3306/demodb?user=demouser&password=demopass")>
Your URL for SQL Server doesn't pass in any credentials, give that a try.

How to connect to Microsoft SQL Server 2008 (MSSQL) from Matlab?

This is probably a simple question:
How do I connect to Microsoft SQL Server 2008 R2 from Matlab?
How do I read a table into a matrix given some SQL query?
Update
I'd prefer a method that doesn't require use of manual setup using ODBC.
I present below a review of the different approaches for accessing databases in MATLAB. Here is a list of Stack Overflow questions where some of them were discussed:
How can I access a postgresql database from matlab with without matlabs database toolbox?
connection of MATLAB 7.0 and MYSQL
communicate MATLAB SQL Server
Getting names of Access database tables with Matlab
Invoking ADO.NET from MATLAB
Java
MATLAB have an embedded Java JVM, allowing you to directly call the JDBC drivers from MATLAB. You first need to make them available on the Java classpth in MATLAB:
javaclasspath('sqljdbc4.jar');
%# load driver and create connection
driver = com.microsoft.sqlserver.jdbc.SQLServerDriver;
conn = driver.connect('jdbc:sqlserver://<HOST>:<PORT>;databaseName=<DB>');
%# query database
q = conn.prepareStatement('select * from <TABLE>');
rs = q.executeQuery();
while rs.next()
char(rs.getString(0))
end
rs.close();
conn.close();
Database Toolbox
If you have access to the Database Toolbox, it can simplify the above as it acts as a wrapper around JDBC/ODBC stuff:
conn = database('<DB>', '<USER>','<PASS>', ...
'com.microsoft.sqlserver.jdbc.SQLServerDriver', ...
'jdbc:sqlserver://<HOST>:<PORT>;database=<DB>');
curs = exec(conn, 'select * from <TABLE>');
curs = fetch(curs);
curs.Data
close(curs)
close(conn)
You can also access the database through ODBC. First create a DSN to MSSQL Server (Control Panel > ODBC Data Sources), then use it from the Database Toolbox:
conn = database('myDB', '', ''); %# User/System DSN
%...
close(conn)
COM
You can directly use the ADO OLEDB component from MATLAB. One way is to specify a connection string (DNS-less):
conn = actxserver('ADODB.Connection');
conn.Open('Provider=sqloledb;Data Source=<HOST>;Initial Catalog=<DB>;User Id=<USER>;Password=<PASS>;');
conn.Execute('select * from <TABLE>').GetRows
conn.Close()
.NET
Finally, recent versions of MATLAB added the ability to call .NET from MATLAB. So you can use the ADO.NET data providers:
import System.Data.SqlClient.*
NET.addAssembly('System.Data');
conn = SqlConnection('Data Source=<HOST>;Initial Catalog=<DB>');
conn.Open();
q = SqlCommand('select * from <TABLE>', conn);
r = q.ExecuteReader();
while r.Read()
char(r.GetString(0))
end
r.Close()
conn.Close()

Resources