Duplicate SQL Server database on same server cannot be accessed - sql-server

I am using SQL Server Workgroup Edition on Windows Server 2003 R2
My classic ASP pages access my production database using a system DSN. All working here.
Code like this...
<%
dbName= "ProdDB"
userID = "PublicUser"
pwd = "PublicUserPW"
Set objConn = Server.createObject("ADODB.Connection")
objConn.connectionString = "DSN=MySystemDSN"
objConn.open dbName, userID, pwd
%>
For development and testing, I created a copy of ProdDB in Enterprise Manager by
Backing up ProdDB
Restoring from the ProdDB backup set to a new database called TestDB
My understanding was that the restored database would contain an exact copy of the data as well as users, roles etc. Comparing both databases in Enterprise Manager seemed to back up this assumption.
So... I assumed I can access the test copy using the same credentials and only change the dbName, like so...
<%
dbName= "TestDB"
userID = "PublicUser"
pwd = "PublicUserPW"
Set objConn = Server.createObject("ADODB.Connection")
objConn.connectionString = "DSN=MySystemDSN"
objConn.open dbName, userID, pwd
%>
However, now my page returns
[Microsoft][ODBC Driver Manager] Data
source name not found and no default
driver specified
I have even tried creating a new System DSN, with a default database pointing at TestDB. Still no joy.
I'm sure I'm doing something simple and silly. Any assistance gratefully received.

The documentation for the open method says it's declared:
connection.Open ConnectionString, UserID, Password, Options
So it looks like you're passing in TestDB as the connection string. I usually call open without specifying any arguments. Grab a connection string from connectionstrings dot com, and:
objConn.ConnectionString = "Data Source=localhost;Initial Catalog=testdb;" & _
"User Id=myUsername;Password=myPassword;"
objConn.Open

Related

Remote connection to SQL Server with Windows security and impersonation

I want to tune Windows login to dbmail (for sending attachment), first step is simple open connection to SQL Server where the dbmail configuration is stored.
I have created an account in Windows named dbmail, and then I created a SQL login for it:
CREATE LOGIN [QQQQQQQ\dbmail] FROM WINDOWS
I set needed permission for this SQL login to (SqlAdministrator).
Permission
Then I try to connect to SQL with this connection string:
ATT_tds_STRING = "Data Source=localhost; Database=YYYYY; uid=QQQQQQQQ\dbmail; pwd=xxxxxxxxxxxx; Integrated Security=SSPI;"
My function placed inside COM-object
Public Function DbMailSendMail(CN As String, DbMailProfileName As String, SmSender As String, SmRecptLst As String, SmCCLst As String, SmBCCLst As String, SmSubject As String, SmMsg As String, SmAttach As String) As String Implements IDbMail.DbMailSendMail
Dim SQLCN As New SqlClient.SqlConnection(CN)
SQLCN.Open()
Try
Dim CMD As New SqlClient.SqlCommand($"EXEC msdb.dbo.sp_send_dbmail #body_format = 'HTML', " &
....
When I call my function from ASP page
Dim Mailer1, Res1
Set Mailer1 = Server.CreateObject("TDS.DbMail")
Res1 = Mailer1.DbMailSendMail (ATT_tds_STRING, "ZZZZZZZ", "", Request.Form("Mailto"), "", "", Request.Form("title"), Request.Form("body"), "C:\www\tdsv5\Images\BeOS_Help.gif")
Unfortunately I get a strange result
.Net SqlClient Data Provider error '80131904'
Login failed for user 'NT AUTHORITY\IUSR'.
I expect Windows authentication in SqlClient.SqlConnection(CN) with login QQQQQQQ\dbmail (because I use exactly Windows login and SSPI security), however Windows appears to be using IIS impersonation account NT AUTHORITY\IUSR to connect to SQL Server.
According advice #Charlieface, I have created login
CREATE LOGIN [NT AUTHORITY\IUSR] FROM WINDOWS
and set up to this login special roles in MSDB
DatabasemailUserRole
After that all working fine. Connection string is
ATT_tds_STRING = "Data Source=localhost; Integrated Security=SSPI"

Writing data into SQL Server database - Invalid object name error

I am working with an excel file that holds macros. In these macros, a connection to a SQL Server database is created and data is loaded from the sheets in the Excel file into the tables in the database.
This file is used by multiple users.
Currently, we have an issue where writing data into the db works for some users while other users get the following Run-time error:
[Microsoft][OBDS SQL Server Driver][SQL Server]Invalid object name
"TableName".
The connection to SQL Server in the macro is specified as following:
'Setting the connection
Set oConn = New ADODB.Connection
Set Rs = New ADODB.Recordset
oConn.ConnectionString = "driver={SQL server};" & _
"server=" & ServerName & ";authenticateduser=TRUE;database=" & DatabaseName
oConn.Open
The table definitely exists in the db and as mentioned, other users don't receive that error message.
What could be the issue that makes the connection work for some users while others get the error?

Error when opening ADODB recordset using odbc dsn in MS Access

I have a MS Access application that has been in use for at least 10 years. Recently I moved my work to a new development machine with Office 365 and SQL Server Express 2019 installed. The machine OS is Windows 10 Pro. In my old machine my application would run just fine. There is a query using a stored procedure that retrieves a piece of data from a table in the SQL Server backend. I call this procedure using a ADODB recordset based on the stored procedure output. All my calls use a connection string based on an ODBC DNS. This connection string works fine on the new machine when relinking tables to the SQL Server backend, but when I use it in the ADODB connection I get an error "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified". On the old Windows 7 development machine this ran fine. It also runs on the client's machines which are Windows 10 and Office 365. The code that raises the error follows. The error occurs at the open connection line. The connection string is: ODBC;DSN=VROM;Trusted_Connection=Yes;APP=2019 Microsoft Office system;DATABASE=VROM1.
Set con = New ADODB.Connection
con.ConnectionString = DLookup("Link", "tblLinkData", "Use = True")
con.Open
Set rs = New ADODB.Recordset
My question "Is there a setting in SQL Server that could be causing this error?". As far as I can tell both systems are set up the same, but there is obviously something different between the two. Is there another reason this could be working on one system and not another?
Hum, where to start?
Ok, first up, if you using the ODBC panel to create a ODBC connection, then you NEVER were actually using a ADO connection in that DSN config = ODBC!!!!
That means you been feeing ADO a ODBC connection string. you can do this, but at least lets be aware of what is going on.
Next up:
Are you running the SQL browser service? You MUST do that now!. Don't know if you installed a later version of SQL SERVER, but a few versions ago you will find now that you MUST run the browser service.
This one:
The reason of course is that you can (may) have multiple instances of sql server running, and the default instance (SQLEXPRESS) now MUST BE specified. As noted older instances did NOT have this requirement. And to "resolve" the multiple instances, you now must run the SQL browser service. As noted, this was NOT a requirement in the past - it is now. That browser service is what connects the IP/server name to the instance, and you now in most cases have to run this.
There are exceptions, but you don't want much pain.
Next up:
For a VERY long time, it is recommended for Access linked tables you use a DSN-less connection. that way then at deployment time to all workstations, you don't need to setup a DSN on each workstation.
And if you link Access tables using a FILE dsn (not system or user), then upon the table link process, access BY DEFAULT converts all table links to DSN-less. That means once you linked, then you could even delete the DSN - you do NOT need it anymore.
Again: this ONLY holds true if and when you create a FILE dsn, and use that to link the tables. So, that takes care of the DSN-less linked tables.
Note that if you were to modify the DSN, you would have to link, since I just told you by default access creates + uses dsn-less links (assuming you used a FILE dsn to link).
now, you CAN of course use that SAME dsn for ADO, but that means you are feeding ADO a ODBC driver connection!!!
If you want to create a real ADO connection, then you would/could/should say use this:
Dim strCon As String
strCon = "Provider=SQLOLEDB;;Initial Catalog=TEST4; " & _
"Data Source =.\SQLEXPRESS;Trusted_Connection=yes"
Dim conn As New ADODB.Connection
conn.ConnectionString = strCon
conn.Open
Dim rst As New ADODB.Recordset
rst.Open "SELECT * from tblHotels", conn
Do While rst.EOF = False
Debug.Print rst!HotelName
rst.MoveNext
Loop
Now now how I used a "." for localhost. That could be replaced with (local), or in fact the computer (server) name say like this:
strCon = "Provider=SQLOLEDB;;Initial Catalog=TEST4; " & _
"Data Source =ALBERTKALLAL-PC\SQLEXPRESS;Trusted_Connection=yes"
Next up, make sure you enabled the TC/IP connections.
here:
However, since your case all along you actually been using ODBC driver with ADO, then I would not rock the boat.
But, check your settings as per above.
Since linked tables, and quite much everything else is DAO + odbc?
then I would probably not introduce ADO into that application for JUST calling + using sql server store procedures.
I as a general rule would say use this;
with currentdb.tabledefs("qryPT")
.sql = "exec MyProcName"
.execute
end with
Or, if it is to return data, then I would use this:
dim rst as DAO.RecordSet
with currentdb.tabledefs("qryPT")
.sql = "exec MyProcName"
set rst = .OpenRecordSet()
end with
So, I am hard pressed to find a reason to use ADO. Now of course since you been using ADO, then I guess I would continue to do so.
but, check the browser settings. And if the tables were linked using a FILE dsn, then they are dsn-less.
You could try feeding the ADO connection a existing connection from a existing linked table.
eg:
strCon = CurrentDb.TableDefs("dbo_tblHotels").Connect
strCon = Mid(strCon, 6)
Dim conn As New ADODB.Connection
conn.ConnectionString = strCon
conn.Open
Skipping the first 6 chars skips this part:
ODBC;DRIVER=SQL Server;SERVER=ALBERTKALLAL-PC\SQLEXPRESS;
UID=AlbertKallal;Trusted_Connection=Yes;APP=Microsoft Office 2010;
DATABASE=Test4;Network=DBMSLPCNM
So once again we are feeding ADO ODBC connection string.
(of course above connection string is one line).

How to connect to simple database table?

I don't know much about databases - Sorry if the question seems silly.
I have sql server 2012 on my machine and i create simple database table.
I want to connect to this database table thru C# code.
So, I need to know my ConnectionString.
I don't understand the parameters of the ConnectionString.
I try to google it - but still didn't find any good explanation.
Anyone can please explain the connectionString fields ?
How to define the connectionString that i will be able to connect the local database ?
thanks
Your connection string should be as simple as like below
Data Source=.;Initial Catalog=DB_NAME;Integrated Security=True"
Where
Data Source=. means local database
Initial Catalog=DB_NAME means the database it will connect to
Integrated Security=True means it will use windows authentication (no user name and password needed; it will use logged in credential)
Take a look Here
(OR)
Search in Google with key term sqlconncectionstring which will fetch you many help.
EDIT:
You are getting exception cause Initial Catalog=DB_Name\Table_001. It should be Initial Catalog=DB_Name (only database name). Provide the table name in sql query to execute. Check some online tutorial to get more idea on the same.
You use . in data source only when you are connecting to local machine database and to the default SQL Server instance. Else if you are using different server and named SQL Server instance then your connection string should look like
using(SqlConnection sqlConnection = new SqlConnection())
{
sqlConnection.ConnectionString =
#"Data Source=Actual_server_name\actual_sqlserver_instance_name;
Initial Catalog=actual_database_name_Name;
Integrated Security=True;";
sqlConnection.Open();
}
In case you are using local machine but named SQL Server instance then use
Data Source=.\actual_sqlserver_instance_name;
Initial Catalog=Actual_Database_NAME;Integrated Security=True"
using System.Data.SqlClient;
Then create a SqlConnection and specifying the connection string.
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
Note: line break in connection string is for formatting purposes only
SqlConnection.ConnectionString
The connection string is simply a compilation of options and values to specify how and what to connect to. Upon investigating the Visual Studio .NET help files I discovered that several fields had multiple names that worked the same, like Password and Pwd work interchangeably.
User ID
The User ID is used when you are using SQL Authentication. In my experience this is ignored when using a Trusted_Connection, or Windows Authentication. If the username is associated with a password Password or Pwd will be used.
"user id=userid;"
Password or Pwd
The password field is to be used with the User ID, it just wouldn't make sense to log in without a username, just a password. Both Password and Pwd are completely interchangeable.
"Password=validpassword;"-or-
"Pwd=validpassword;"
Data Source or Server or Address or Addr or Network Address
Upon looking in the MSDN documentation I found that there are several ways to specify the network address. The documentation mentions no differences between them and they appear to be interchangeable. The address is an valid network address, for brevity I am only using the localhost address in the examples.
"Data Source=localhost;"
-or-
"Server=localhost;"
-or-
"Address=localhost;"-or-"Addr=localhost;"
-or-"Network Address=localhost;"
Integrated Sercurity or Trusted_Connection
Integrated Security and Trusted_Connection are used to specify wheter the connnection is secure, such as Windows Authentication or SSPI. The recognized values are true, false, and sspi. According to the MSDN documentation sspi is equivalent to true. Note: I do not know how SSPI works, or affects the connection.
Connect Timeout or Connection Timeout
These specify the time, in seconds, to wait for the server to respond before generating an error. The default value is 15 (seconds).
"Connect Timeout=10;"-or-
"Connection Timeout=10;"
Initial Catalog or Database
Initial Catalog and Database are simply two ways of selecting the database associated with the connection.
"Inital Catalog=main;"
-or-
"Database=main;"

don't see the new database and can't log in

I create a database using ADO.NET SQL queries like this:
create database mydatabase
create login 'loginname' with password='somepassword'
create user 'username' for login loginname
The queries aren't exact, I've typed them as far as I could remember them.
After that I don't see the database in my ms sql server 2008 r2 express management studio.
I also can't log in with the newly created login. The "enable server authentication" is set to true.
What should I do to see that database in the manager?
Why can't I log in with newly created login? I've looked into the logs and it says that the password is incorrect.
I do have 2 sql express instances, but I use the same one when I run my sql
select ##servername when run in management studio returns "BOGDAN".
ADO.NET query returns "BOGDAN\BBF17ECB-69FF-4B" . Code is below:
SqlConnection con = new SqlConnection("Data Source=BOGDAN;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("select ##servername", con);
con.Open();
string s = (string)cmd.ExecuteScalar();
Console.WriteLine("Server name:" + s);
con.Close();
Console.ReadKey(false);
Don't know where BBF17ECB-69FF-4B came from, I explicitly stated server name as "BOGDAN".
the script is:
IF DB_ID('MyDatabase') IS NULL CREATE DATABASE [MyDatabase]
USE MyDatabase
IF NOT EXISTS(SELECT * FROM master.dbo.syslogins WHERE loginname = 'AUsername') CREATE LOGIN AUsername WITH PASSWORD='APassword'
IF NOT EXISTS (SELECT * FROM sys.sysusers WHERE name='AUsername') CREATE USER AUsername FOR LOGIN AUsername
EXEC sp_addrolemember N'db_owner', N'AUsername'
Do you have multiple instances of Sql Server on your box? Maybe an express install, and a developer edition install? It's possible you were pointed at the other instance when you created the db...I have done this before.
Are you sure that the database creation completed without error? Maybe it failed, and the db was never created.
Unfortunately, the details of the query that you would have run are where we would find the evidence for the problem.
The problem was with the connection string: I had to remove "User Instance=true" from it. That fixed the problem!
I thought the problem was with how I configurated the servers or with the SQL requests.

Resources