I want to connect to a database with sys user. Change the schema to a differnt user. Execute a query and write the result into a file.
I am using oralce managed data access .https://www.nuget.org/packages/Oracle.ManagedDataAccess/
I have tried three different ways already.
1.) spool-> does not work since I am not executing sqlplus but connect with managedDataAccess
2.) begin execute immediate'changeschema' execute immediate 'query' end -> no output on the reader because of begin/end
3.) try to change the connection conn.ChangeDatabase(user); does not work with managedDataAccess
This is my connection string:
string oradb = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" + host + ")(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=" + instance + ")));User Id = " + oracleUser + "; Password =" + oraclePassword;
Can I change the schema within the connection string
If you connect as SYS you don't need to change the schema, you can just reference the schema in your from clause, e.g.
select *
from my_user.my_tab
;
Related
I have an application JigSaw that uses a database TopScores.mdf which it is not included in the project. What I want to do is make the application find the database in application's folder. So for example if I move the .exe file and the database file from debug folder to desktop the application should use the database from desktop and not search for it in debug folder.
If I let them in debug folder there is no problem and the connection to database is established, but when I put them on desktop I get this :
Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. Database 'D:\Programing\Projects Visual Studio 2010\JigSaw\JigSaw\bin\Debug\TopScores.mdf' already exists. Choose a different database name. Cannot attach the file 'C:\Users\Addy\Desktop\Jigsaw\TopScores.mdf' as database TopScores.mdf
My connection string is :
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
string connString = #"server =.\sqlexpress; Database=TopScores.mdf; trusted_connection=TRUE; AttachDbFileName= "+#appPath+#"\TopScores.mdf";
conn = new SqlConnection(connString);
Sorry for my bad english :(
This is happening because you don't leverage the User Instance=true; when you connect to it. You literally told SQL Server to attach the database to the running SQL instance from the directory you first loaded it from.
Detach the database by hand from the running SQL instance, change your connection string to use User Instance=true;, run it from the Debug folder, and then run it from the Desktop, and you'll see success.
change setting in your connection string from "Database=TopScores.mdf" to something different, say: "Database=TopScores_brand_new_connection" do not create/delete/rename files in any file/database server. do it in the connection string only. Do not add dots, extensions etc.
just rename ur .mdf file ... eg. from MNGMT.mdf to M_1(something you want). change your contact string...hope so it will help u.. in my case it is executing correctly on other pc as well as in my pc.. just copy your .mdf file into you project ..
string dbPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\M_1.mdf";
string myServer = Environment.MachineName;
DataTable servers = SqlDataSourceEnumerator.Instance.GetDataSources();
for (int i = 0; i < servers.Rows.Count; i++)
{
if (myServer == servers.Rows[i]["ServerName"].ToString()) ///// used to get the servers in the local machine////
{
if ((servers.Rows[i]["InstanceName"] as string) != null)
servername = (servers.Rows[i]["ServerName"] + "\\" + servers.Rows[i]["InstanceName"]);
else
servername = ""+servers.Rows[i]["ServerName"];
}
}
connetionString = "Data Source=" + servername + ";AttachDbFilename=" + dbPath + ";Integrated Security=True;Pooling=False;User Instance=True";
I have the following code to determine a SQL Server database's compatibility level:
Microsoft.SqlServer.Management.Smo.Server server = new Server(myServerName);
if (!server.Databases.Contains(database))
{ throw new ArgumentException("Specified database ('" + myDBName+ "') not found on '" + myServerName + "'"); }
string connstr = string.Format("Data Source={0};" +
"Persist Security Info=False;" +
"User ID={1};" +
"Password={2};Enlist=False;", myServerName, username, password);
server.ConnectionContext.ConnectionString = connstr;
Microsoft.SqlServer.Management.Smo.Database db = server.Databases[myDBName];
DataSet ds = db.ExecuteWithResults(#"select compatibility_level
from sys.databases where name=db_name()");
I have two users, one of which is able to run this code and get the proper value back. Another user runs this code connecting to the same Server/Database with the exact same credentials and the DataSet returned contains no rows.
What could possibly be the difference between the two users that would cause one to get no result back for the same query? Is there a better way to get Database compatibility?
By the way, this code runs/works on SQL Server 2005 through 2012.
Edit: I should have pointed out that myServerName, myDBName, username, and password are always the same--the only difference is the two different Windows users running the code.
I suspect that the user who returns results has the VIEW_ANY_DEFINITON permission granted to his login. Grant this permission to the other user and he should get the results back.
I'm attempting to connect two SQLite databases in a Unity3d project and I am running into some trouble.
My database paths and file names are correct (checked and confirmed), and I am able to query/insert/etc... from each of the databases individually. However, when I run the ATTACH command, it returns an error stating that my SQL logic is invalid. I have looked at many references and examples, all of which indicate that my command should run as anticipated.
Here is some relevant code:
//open TEMP database
DBAccess.OpenOrCreateDB("/Resources/Data/SaveGames/" + GameController.user.username +
"/", GameController.user.username + "_TEMP");
//attach SAVEGAME database and transfer data from TEMP database
DBAccess.NonQuery("ATTACH DATABASE '" + Application.dataPath + "/Resources/GameData/"
+ GameController.user.username + "/" + GameController.user.username + DBAccess.DBEXT
+ "' AS LOAD_DB;");
//copy records from TEMP database to save game database
//(omitted because not relevant to issue)
//detach SAVEGAME database
DBAccess.NonQuery("PRAGMA LOAD_DB.journal_mode=delete; DETACH DATABASE LOAD_DB;");
//close database
DBAccess.CloseDB();
The goal with this is to copy the in-game changes database to the player's save game database file.
My error debugging prints out the following:
DBAccess -- Cannot perform command with statement: <ATTACH '/Users/scottwindsor/ADITL/
Assets/Resources/GameData/New User/New User.db' AS LOAD_DB;>
It would seem that my SQL command should work... Any help would be appreciated.
Tech Specs:
Platform: OSX (Lepoard, I think)
Compiler: Unity3D (game engine)
Language: C#
SQL: SQLite3.dll
Using IDBCommand.ExecuteNonQuery() to send non-query commands to the database.
Using IDBCommand.ExecuteReader() to send all other commands/queries to the database.
Previously I use sql server 2005 as my website database, and everything works well.
now I have changed to MySql server 5.5 database because it is open source.
I used Navicat Premium to transfer my data from sql server to mysql. I use mysql workbench and navicat to manage my database. Problems come when i declare the connection to mysql database. here is my code:
MySqlCommand cmdselect;
MySqlConnection conNDB;
MySqlDataReader Mydtr;
string server = "localhost";
string database = "maindb";
string uid = "root";
string password = "abc123";
string strCon = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
string strSelect = "SELECT * FROM announcement";
conNDB = new MySqlConnection(strCon);
conNDB.Open();
cmdselect = new MySqlCommand(strSelect, conNDB);
Mydtr = cmdselect.ExecuteReader();
rptAnnounce.DataSource = Mydtr;
rptAnnounce.DataBind();
Mydtr.Close();
conNDB.Close();
Reference to MySql.Data already set. Here i got this error message :
Exception Details:
MySql.Data.MySqlClient.MySqlException:
Variable 'character_set_client' can't
be set to the value of 'utf16'
Error message stated this error occurs during connection.Open();
When i keep on refreshing the error page, i got another error sometime. here is it:
Exception Details: MySql.Data.MySqlClient.MySqlException: Expected end of data packet
Error message stated this error occurs during Mydtr = cmdselect.ExecuteReader();
I am new to mysql. i don know what problem is this. i guess this problem comes from database's setting or data, not my source code.
anyone knows the solution? your help is greatly appreciated. i been trying for 4 days but cannot solve.
solved!! Thanks to #Etienne Rached and #jeremi
all the problems come from the character set problem.
solution: download navicat, to change the character set for database and every single table.
there are 2 places you need to check:
1) right-click on database eg. myDb. Then select properties and set the character set
2) right-click on a table and select design table. click every single row to change character set and finally go to "Option" tab and change the character set.
For your info: this is very rare case. I google it almost cannot find the solution. i created this mistake during installation of Mysql, I chose utf16 format ><
by the way, simple connectionstring will work. like
"server=localhost;database=maindb;uid=root;pwd=abc123;CharSet=utf8; port=3306";
Hi to add up to the above points.
As of MySQL 5.5 version, it doesn't support utf16 or utf32 character set encoding.
There are couple of things that need to be looked from both
Client making the connection to DB
DB itself
At client side, it invokes the query to DB with a query encoded in particular format and the server intact have to understand these queries and respond in particular format, that the client can understand in turn.
Point 1: So we need to set the charset at client level, in connection string as
Charset=utf8;
And in turn you have to check with DB and table (to which you are seeking a query transaction) charset and collation
There are four level of encoding charset and collation at MySQL server for flexibility
Charset for whole server server_character_set
Charset for Database
Charset for Table
Charset for Table columns as well
you can check these values using following query
show variables like 'character%';
show variables like '%collation%';
So, the point is DB server read these queries in the encoding specified in connection string.
Point 2 Instead of specifying the character set at connection string, you can also set the charset for client (in which the server interrupts ) at query after opening up connection
set names 'charset';
Ex: set names 'utf8';
There are the 3 server parameters significant in charset specific issues from client to server
character_set_client - Server sets the specified charset for client - queries passed to
character_set_connection - Server sets the specified charset for connection transaction
character_set_results - Server sets the specified charset for returned results, error messages from DB to client
Point 3 Instead of Point 1 and 2, you can set these variables at DB to ensure proper client server transaction
Basically, the client and DB(server, db table, column) encoding and collation type must be similar to avoid data losses during DB transactions.
Hope this helps.....
Could be that you are trying to talk with utf16 but the database only sopports utf8 or some other.
Try adding this to your connection string:
Character Set=utf8
My connection string looks like this:
"server=" + settings.DatabaseHost +
";User Id=" + settings.DatabaseUsername +
";password="+ settings.DatabasePassword +
";database="+ settings.DatabaseName+
";Persist Security Info=True" +
";Connect Timeout=5;Default Command Timeout=10" +
";Character Set=utf8";
If that does't work, try ASCII or latin1
This error "Exception Details: System.Collections.Generic.KeyNotFoundException:" may occur if you have not upgraded your MySql client library after upgrading your connection string character set to utf8mb4
Please update the MySql.data.dll library version to latest 6.6.5.0
Hope this should solve key not found exception.
I'm using following code to restore databases,
void Restore(string ConnectionString, string DatabaseFullPath, string backUpPath)
{
string sRestore =
"USE [master] RESTORE DATABASE [" + DatabaseFullPath + "] FROM DISK = N'" + backUpPath + "' WITH FILE = 1, NOUNLOAD, STATS = 10";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
SqlCommand cmdBackUp = new SqlCommand(sRestore, con);
cmdBackUp.ExecuteNonQuery();
}
}
but I receive below exception
"Exclusive access could not be obtained because the database is in use.
RESTORE DATABASE is terminating abnormally.
Changed database context to 'master'."
How can I fix it ?
A restore can only happen if the database does not have any connections to it (besides yours). The easy way on a MS SQL Server to kick all users off is:
ALTER DATABASE [MyDB] SET Single_User WITH Rollback Immediate
GO
Now, you can perform your restore with impunity. Make sure you set it back to Multi-user mode when you're done with the restore:
ALTER DATABASE [MyDB] SET Multi_User
GO
Thus I've written the below method to restore my database,
Am I in right way ?
void Restore(string ConnectionString, string DatabaseFullPath, string backUpPath)
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
string UseMaster = "USE master";
SqlCommand UseMasterCommand = new SqlCommand(UseMaster, con);
UseMasterCommand.ExecuteNonQuery();
string Alter1 = #"ALTER DATABASE [" + DatabaseFullPath + "] SET Single_User WITH Rollback Immediate";
SqlCommand Alter1Cmd = new SqlCommand(Alter1, con);
Alter1Cmd.ExecuteNonQuery();
string Restore = #"RESTORE DATABASE [" + DatabaseFullPath + "] FROM DISK = N'" + backUpPath + #"' WITH FILE = 1, NOUNLOAD, STATS = 10";
SqlCommand RestoreCmd = new SqlCommand(Restore, con);
RestoreCmd.ExecuteNonQuery();
string Alter2 = #"ALTER DATABASE [" + DatabaseFullPath + "] SET Multi_User";
SqlCommand Alter2Cmd = new SqlCommand(Alter2, con);
Alter2Cmd.ExecuteNonQuery();
labelReport.Text = "Successful";
}
}
The best approach
Alter Database <Db_Name> SET [SINGLE_USER | RESTRICTED_USER]
With ROLLBACK [IMMEDIATE | AFTER 30]
go
--do your job that needs exclusive access
go
--Back to normal mode
Alter Database <Db_Name> SET MULTI_USER
WITH ROLLBACK IMMEDIATE - this option doesn't wait for transactions
to complete it just begins rolling back all open transactions
WITH ROLLBACK AFTER nnn - this option will rollback all open
transactions after waiting nnn seconds for the open transactions to
complete. In our example we are specifying that the process should
wait 30 seconds before rolling back any open transactions.
When RESTRICTED_USER is specified, only members of the db_owner,
dbcreator, or sysadmin roles can use the database. MULTI_USER returns
the database to its normal operating state.
2nd way :using ssms 2008 R2 we can do the same thing
right-click database property
go to options -> last section with header of state
change Restrict Access to SINGLE_USER
answer yes to this helpful question which shows that this kind of action will close all other connections and i guess it is the only thing we are looking for here to by pass the error
To change the database properties, SQL Server must close all other connections to the database. Are you sure you want to change the properties and close all other connections? yes or no
restore your database
do step 1-4 changing Restrict Access back to MULTI_USER
3rd way : the following commands will also close all connections too.
ALTER DATABASE [DbName] SET OFFLINE
go
ALTER DATABASE [DbName] SET ONLINE
now database is ready for restore
More (mssqltips :Getting exclusive access to restore SQL Server databases)
You can use the method on SMO SqlServer object to kiil all processes on a specified database before performing a restore:
sqlServer.KillAllProcesses("databaseName");
The reason for this issue is self-evident (connections to the database currently open/active), but use the following (google it too so you understand it) and it'll be fine:
Alter Database YOURDB
SET SINGLE_USER With ROLLBACK IMMEDIATE
GO
Obviously, replace YOURDDB with the name of your database and run that against the master DB.
Oh, and just incase, if you get it 'stuck' in single user mode, this will undo it:
Alter Database YOURDB
SET MULTI_USER With ROLLBACK IMMEDIATE
GO
Hope this helps.
EDIT:
You can also follow this, to see where the connections are from, and other information:
I tested this while having services
running that would reconnect to the
database. I found you had to set to
Single User Mode, then run sp_who2 to
see where the one connection was
coming from, and note the SPID. You
can run the kill command for that SPID
and the restore in the same
transaction, and it should go through.
Here is the sequence I used:
USE MASTER ALTER DATABASE DATABASENAME
SET SINGLE_USER WITH ROLLBACK
IMMEDIATE GO
-This will make it so only one connection to the database can be
made.
-Run the following command to see where any recurring connections to
database are coming from.
EXEC SP_WHO2
-Check this list, looking under the DBName column. If the database is
listed, check the ProgramName, and
HostName column to see who is
attempting to connect.
-If it is not a service, or other application that would automatically
reconnect which can be shut down, note
the number in the SPID column to kill
the connection, and immediately begin
the backup. Replace SPID below with
just the number.
KILL SPID RESTORE DATABASE
DATABASENAME FROM DISK =
'X:\PATHTO\BACKUP.BAK' GO
-If this completes successfully, we can set the newly restored database
back to multi user mode.
ALTER DATABASE DATABASENAME SET
MULTI_USER WITH ROLLBACK IMMEDIATE GO
only one connection to the database can be made. -Run the following command to see where any recurring connections to database are coming from.
EXEC SP_WHO2
Check this list, looking under the DBName column. If the database is listed, check the ProgramName, and HostName column to see who is attempting to connect.
If it is not a service, or other application that would automatically reconnect which can be shut down, note the number in the SPID column to kill the connection, and immediately begin the backup. Replace SPID below with just the number.
KILL SPID RESTORE DATABASE DATABASENAME FROM DISK = 'X:\PATHTO\BACKUP.BAK' GO
If this completes successfully, we can set the newly restored database back to multi user mode.
ALTER DATABASE DATABASENAME SET MULTI_USER WITH ROLLBACK IMMEDIATE GO