I am trying to find out what drive a database is on, on the server. To further elaborate, there is a sever "MyServer" and three databases on that server. Databases A and B are on the "C:\" Drive of that server and database C is on the "D:\" Drive. I want to know how I can use the connection string to try and get the drive letter so that when a user selects a database from an application it tells them what drive that database is on.
Currently I am trying the following means and not getting the correct response:
Private void GetDriveLetter()
{
string connectionString = String.Format(DatabaseInfo.CONNECTIONSTRING_TEMPLATE, dbName, server)
try
{
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
cn.Open();
Server srv = new Server(new ServerConnection(cn));
Database database = new Database(srv, dbName);
txtDriveLetter.Text = database.PrimaryFilePath;
cn.Close();
}
}
catch (Exception ex)
{
myException = ex.Message
}
}
DatabaseInfo is just a class we use for reading SQL Servers and database names, and myException is a function that writes exceptions to a log file. The issue I am having is that no matter what I do I get an exception that says PrimaryFilePath is never set. Am I doing something wrong/missing something, or is this just not the correct way to go about this?
EDIT: Sorry never posted the exception
To accomplish this action, set property PrimaryFilePath.
You could always run a query against your sys catalog views inside SQL Server:
SELECT * FROM sys.master_files
This will list your database, it's id, its logical name, and the location of the file on disk.
You should probably access the existing database, rather than constructing a new one:
Database database = srv.Databases[dbName];
(Of course, error handling required if the name doesn't exist).
Also, of course, you should be aware that a database may consist of multiple files, and those files may be on different drives.
If this is SQL Server, then you can use
SELECT * FROM sys.database_files
to get the files of the current database. So, your connection string should connect you to the database that you want and then the above SQL will give you lots of information that you might find useful, including the physical_name. From that you can extract the drive letter.
Related
I am testing various DB connection methods in C#. In particular, I am testing SqlConnection and OdbcConnection classes; my DB is SQLServer Express (.\SQLEXPRESS). Both are working reasonably well, except in listing available databases on the server.
In my test code I use a "generic" DbConnection object and a simple factory to create an instance of specific SqlConnetion and OdbcConnetion subclasses (they both derive from DbConnection):
DbConnection connection;
switch (connection_type)
{
case DbConnectionType.DBCONN_MSSQL:
connection = new SqlConnection(...sql connection string...);
break;
case DbConnectionType.DBCONN_ODBC:
connection = new OdbcConnection(...odbc connection string...);
break;
}
The trick seems to work well except when I try to get the list of databases on the server:
DataTable databases = connection.GetSchema("Databases");
foreach (DataRow database in databases.Rows)
{
String databaseName = database["database_name"] as String;
Console.WriteLine(databaseName);
}
When "connection" is an OdbcConnection (and, note, the database is the same), I get an exception saying that "Databases" key was not found. I listed all the keys exposed by GetSchema(), and the ODBC version returns only a subset of the items exposed by the SQLServer version. I couldn't find any hint about this specific problem. Is it a documented/expected behaviour? Am I doing something wrong?
NOTE: here how I build the ODBC connection string:
OdbcConnectionStringBuilder builder;
builder = new OdbcConnectionStringBuilder();
builder.Driver = "SQL Server";
builder.Add("Server", ".\\SQLEXPRESS");
builder.Add("Uid", "");
builder.Add("Pwd", ""); // Using current user
builder.Add("Integrated Security", "SSPI");
connection = new OdbcConnection(builder.ConnectionString);
Is it a documented/expected behaviour?
Yes. See Retrieving Database Schema Information
Am I doing something wrong?
If your goal is to read SQL Server metadata in a provider-agnostic way, then yes. You should query the SQL Server catalog views directly. sys.databases, sys.tables, etc.
Make sure your "Databases" model has a valid Key. Add the [Key] Data annotation if the key you want to implement for that database doesn't follow the "ClassName"+"ID" entity framework rule.
My Code :
var dbpath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "ot.db3");
Context myContext = null;
try
{
var dbcon = new SQLiteConnection(dbpath);
var db= dbcon.Query<records>("SELECT * FROM records WHERE sno = ? ", "1");
int count = db.Count;
}
catch (IOException ex)
{
var reason = string.Format("The database failed to create - reason {0}", ex.Message);
Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}
I Create a Sqlite Database from my SQL Server Database.
Now I save it to my Phone on this path (Android/Data/Application/File)
Now using Sqlite-net-pcl nugget package for Sqlite Connection the connection works fine showing have no error.
When I try to read a table from database this Give any error that "No Such Table exist in database". And the table exists in the database and is populated with data.
What can I do?
Thanks in advance
Why are you writing the SQL query? You could make it more simple, something like, conn.Get(id);
You will only need to add [PrimaryKey] to your PK in the model.
Also, I suggest you to not use SQLite.SQLiteConnection and use SQLiteAsyncConnection instead, so you will be able to get data using "await conn.GetAsync(id)" and this way it won't block the main thread.
Create a Blank Database – A database reference can be created by passing the file path the SQLiteConnection class constructor. You do not need to check if the file already exists – it will automatically be created if required, otherwise the existing database file will be opened.
var db = new SQLiteConnection (dbPath);
Save Data – Once you have created a SQLiteConnection object, database commands are executed by calling its methods, such as CreateTable and Insert like this:
db.CreateTable<Stock> ();
db.Insert (newStock); // after creating the newStock object
Retrieve Data – To retrieve an object (or a list of objects) use the following syntax:
var stock = db.Get<Stock>(5); // primary key id of 5
var stockList = db.Table<Stock>();
For more info use following link:
https://developer.xamarin.com/guides/android/application_fundamentals/data/part_3_using_sqlite_orm/#Using_SQLite.NET
You need to check in your DB file if the table really exists.
Extract the database from your Android device/simulator with ADB
Example: adb pull //.db .
It will download the DB file to your computer.
Then, use a tool such as "DB Browser for SQLite" (http://sqlitebrowser.org/) to open your DB file and check if your table exists.
Other common mistakes when using SQLite with Android are:
the file is not found (the path in your connectionstring is not good)
the name is not the one your think (maybe in your case, it is "Record" and not "Records")
Hope it will help.
I'm using Visual Studio 2010 to build an ASP.NET web application, I'm working on dynamically populating (part) of the site map from information in a database. Right now I just have a dummy table in my App_Data folder, called DrugTest.mdf. The table is just called DrugTest1, which only has one field, DrugName. Where I'm hitting a wall is actually getting the data out of that table. Part of what I'm confused about is the connection string. I've looked at a lot of different information about connection strings, most notably http://www.connectionstrings.com/ but I'm a little confused as to how to actually apply said information to this project.
EDIT: I'm using SQL Server 2008 RC.
For example: Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Password and User Id are pretty self-explanatory, but as far as I know I didn't get either one of those, I just added a table to the App_Data folder and filled it with dummy data. ServerAddress is a little confusing, because this information isn't really stored on a server, it's just stored locally. And I'm honestly not sure what Initial Catalog means.
Here's the code to populate the sub-tree. You'll notice the connection string is left blank.
string connString = ""; // get the connection string
string commandString = "SELECT drugName FROM DrugTable1";
SqlConnection connection = new SqlConnection(connString); // connect to db
SqlCommand command = new SqlCommand(commandString, connection); // set up the command
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet drugs = new DataSet();
adapter.Fill(drugs);
foreach (DataRow row in drugs.Tables[0].Rows)
{
string drugName = row["Name"] + "";
SiteMapNode node = new SiteMapNode(this, drugName,
"~/PlaceHolderUrl?path=" + drugName,
drugName);
AddNode(node, root);
}
Furthermore, I've got a nagging suspicion that I'm not going about this the right way. I think this will be the proper implementation once the database is up and running, but for right now I just want to get it working so it's ready to go - just slap in the proper connection string and table/field names.
So, finally, my question(s): How would I go about connecting to this local table? What format should my connection string be? I noticed there's a lot of them. Is there a better way to do this/am I doing this wrong?
Another way of getting the right connection string check this out in the ServerExplorer window
On the Menu click on View->Server Explorer
In the Server Explorer window locate DrugTest.mdf
Right click the file and select Properties
You can see the right connection string in the properties
Copy the connection string and use
Note: that the file location was hard-coded. You might need to use |DataDirectory| later
Try replacing the Initial Catalog portion of your connection string with AttachDbFilename=|DataDirectory|DrugTest.mdf.
Also, if you're using SQL Server Express, you might need to include the instance in the Data Source, so might try Data Source=mySeverAddress\SQLExpress, where SQLExpress is the instance name.
BTW, at the http://www.connectionstrings.com site, you can find this information in the SQL Server 2008 page if you scroll down a bit to the section titled "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance."
Right, I have been tasked with developing a new application in MVC3 that unfortunately has to integrate very slightly with a classic asp web site. This won't be forever as the old site will get an update at some point, but not yet. In the mean time however the new MVC3 application will need a little bit of access to the database for the old site, which is a old MS Access .mdb whereas the new app will be using sql server 2008.
I would greatly appreciate it if someone could give me some examples of how to connect to the access db, aswell as how to execute sql queries (i am fine writing the sql, just got no idea how to execute against the database from my mvc3 app).
thanks in advance
EDIT: I've not got much experience with the old site, but it appears to use the JET adaptor if that helps! ;-)
Your question requires an answer too extensive to be given in detail
I will give you a check list of things and class to research
Define the connection string used to reach your database [see
here]
Create and open the OleDbConnection
Define your OleDbCommand and the command text to be executed
Create and use an OleDbDataReader to read your data line by line
Create and use an OleDbDataAdapter to read your data and load a
DataSet or DataTable
Now don't forget to close your connection and use parametrized query
string connectionString = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
public void InsertRow(string connectionString, string insertSQL)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OleDbCommand command = new OleDbCommand(insertSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}
i wanna to attach a Database from a dynamic path to a MSSQL server by coding a project to do this ,,
what is the code i should write and will it be a Windows Application or Console Application ,, or there is no difference ??
You can use any of the two. Just make sure the files are in a place the SQL Server in question can reach and then attach them with an sql statement.
Like this:
CREATE DATABASE [AdventureWorks] ON
( FILENAME = N’C:\Data\AdventureWorks_Data.mdf’ ),
( FILENAME = N’C:\Data\AdventureWorks_Log.ldf’ )
FOR ATTACH
In the connection string you can attach a database if the database has not already been attached. To do this in C# you should be able to do the following (this is untested):
SQLConnection conn;
try
{
conn = new SQLConnection(String.Format("Server={0};AttachDbFilename={1};Database=dbname; Trusted_Connection=Yes;", "Server Address", #"Path To Database"));
conn.Open();
conn.Close();
}
catch (Exception ex)
{
throw;
}
finally
{
conn.Dispose();
}
Let me know how you get on.
Regards,
Stu
Are you talking about using System.Data.SqlConnection class?
You can dynamically build your connectionString when you create your SqlConnection.
If I nderstand your question correctly, you are looking for a way to use a databse which the user will select (not the hard coded one).
Go here and learn about Saving User and Application Settings in WinForms. You will get some ideas.