i'm trying to make is so my program can have a local database after i have published it. Now i want it to work so i can install in on any computer so i have to change my connection string but i can't seem to figure out to what to change it to this is my connection string i have now
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Barcode\\Application Files\\Barcode Scanning_1_0_0_0\\BarcodeDB.mdf\"; Integrated Security = True";
Before publishing i have went into applicationfiles and made sure that BarcodeDB.mdf is included but from what i've seen it changes to BarcodeDB.mdf.deploy after i've published it.
I've also went into Prerquisites and added
SQL Server 2012 Express LocalDB
When i try to run the published program or the debugger with the code i have now i get the error:
An attempt to attach an auto-named database for file C:\Barcode\Application Files\Barcode Scanning_1_0_0_0\BarcodeDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share
I'm guessing i need to use:
| DataDirectory |
But i'm new to all of this so i can't seem to figure it out how to use it even after searching for it so i would deeply appreciate it if someone could be kind to eiter explain how i chould be using DataDirectory or if i'm wrong and should be using something else.
And also sorry if i structured this question badly trying to get better at it
Best Regards Hannes.
Edit 1: Here is the code where i try to connect and using the database
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"{Application.ExecutablePath.ToString()}\\Application Files\\Barcode Scanning_1_0_0_0\\BarcodeDB.mdf\"; Integrated Security = True";
string Query = "SELECT Name FROM Products ORDER BY EDate;";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString(myReader.GetOrdinal("Name"));
cbxProducts.Items.Add(sName);
cbxProducts.Sorted = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Ok I assume that your project is a Windows Forms or WPF project if it's not please tell me.
Your problem is that you are hard-coding a path to a database file which may not exist or your process can't have access to it's location. What you have found as | DataDirectory | is to use in web projects Web.Config file which will be mapped to App_Data folder.
In your case you have to build the connection string using your own applications executable path. Try this code:
//WPF:
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"{System.Reflection.Assembly.GetExecutingAssembly().Location}\\BarcodeDB.mdf\"; Integrated Security = True";
//Windows Forms:
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"{Application.ExecutablePath.ToString()}\\BarcodeDB.mdf\"; Integrated Security = True";
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" + Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
This fixed it for me
Related
Recently I found a video and managed to code a simple login page with a SQL server involved as I need to hand up this project to my teacher.
I would like to ask is there any way to edit my program so that the database is connected to my program despite whatever computer it is on?
Let me eleborate this is my current code
SqlConnection con = new SqlConnection(#"Data Source(LocalDB)\v11.0;AttachDbFilename=C:\Users\Glenntdy\Desktop\GlennTeo_Project\GlennTeoProject\GlennTeoDB\GlennTeoDB.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From GlennTeoDB where Username='"+txtName.Text + "' and Password = '" +txtPassword.Text + "'",con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Main ss = new Main();
ss.Show();
txtName.Text = "";
txtPassword.Text = "";
}
else
{
MessageBox.Show("Please double check your Username and password");
txtName.Text = "";
txtPassword.Text = "";
}
The program works fine!
But according to the code, if I were to run it in another computer without editing the code,specifically the "#"Data source" it will not run.
As the path "C:\Users\Glenntdy" will most probably not exist. Is there anyway to fix this issue?
This is a link to a screenshot of my code in case the text is not clear enough.
http://i.imgur.com/xzWrkIm.png
While Sachu answer is exactly correct for this question. I can add little bit more suggestion. You are working on desktop application so when you deploy this application as setup, please add that database in application folder.
Now modify you first line on code such as
String connnectionString = #"Data Source = (LocalDB)\v11.0;
AttachDbFilename="+Application.StartupPath+"\SampleDatabase.mdf;
Integrated Security=True;Connect Timeout=30;";
For your development environment if you copy the DB in dubug folder this code will run smoothly.
I hope the .MDF file is with in the project solution. Move the file to \bin\debug folder and use below code for connection string
string dbPath = Application.StartupPath + "\\GlennTeoDB.mdf";
and use this path for the sql connection...
You can give a connection string in web config file
Declaring connection in only one form
When you want to change the connection string then only change in the web config file.
I have a DB2 expresss in my machine and I am able to query from the database using command window (after following two commands):
set DB2INSTANCE=db2inst1
db2 connect to tims user
Now, when I try to connect to the database from a C# console application, I am getting following errors with different connection strings.
Attempt 1
string connectionString = #"Provider = IBMDADB2; Database = TIMS; Hostname = localhost; CurrentSchema=db2inst1; ";
SQL1032N No start database manager command was issued. SQLSTATE=57019
Attempt 2
string connectionString = #"Provider = IBMDADB2; Database = TIMS; CurrentSchema=db2inst1; ";
SQL1031N The database directory cannot be found on the indicated file system. SQLSTATE=58031
What should be the correct connection string for this scenario?
CODE
string connectionString = #"Provider = IBMDADB2; Database = TIMS; Hostname = localhost; CurrentSchema=db2inst1; ";
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = connectionString;
myConnection.Open();
Do you have multiple DB2 instances running on your machine? You can get a list of instances that exist by executing the db2ilist command.
If you have to execute the set DB2INSTANCE=db2inst1 statement when you open a DB2 Command Window in order to connect to the TIMS database with the db2 connect to TIMS command, then you need to ensure that the environment for your C# application is configured the same way.
You can do this in a number of ways:
by setting the DB2INSTANCE environment variable before starting your application
Change the default DB2 instance on your machine by using the command db2set -g DB2INSTDEF=db2inst1 (** see note below)
Use a TCPIP connection string (as described by #Bhaarat) so that your application does not depend on the database catalog for the default instance
Note: Before changing DB2INSTDEF you may want to see what the current value is, by executing the command db2set -all and looking for DB2INSTDEF in the output. Also note that changing the default instance may affect other applications that run on your machine.
refer this url http://www.c-sharpcorner.com/uploadfile/nipuntomar/connection-strings-for-ibm-db2/
your connection string should be something like this
Provider=IBMDADB2;Database=urDataBase;Hostname=urServerAddress;Protocol=TCPIP;Port=50000;
Uid=urUsername;Pwd=urPassword;
in more you can refer this too
http://www.codeproject.com/Articles/4870/Connect-to-DB2-from-Microsoft-NET
My DB2 insatnce name is "db2inst1" and it was working fine when I used DB2 command window.
Now I made following settings and it is working fine now. :-)
Created a port in the C:\Windows\System32\drivers\etc\services file (db2c_db2inst1 50010/tcp)
Set the “TCP/IP Service Name” ( = db2c_db2inst1”) for the instance. Verified using “db2 get dbm cfg” command
Updated the environment variable DB2INSTANCE with the value “db2inst1”
Restarted the machine
Started the instance
ConnectionString
"Provider = IBMDADB2; Database = TIMS; Hostname = localhost; Protocol = TCPIP; Port = 50010; Uid = myUserID; Pwd = myPassword";
CODE
string queryString = "SELECT * FROM DBATABC";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
string companyCode = reader.GetString(0).ToString();
}
}
}
reader.Close();
}
}
Note: Try to create DSN for ODBC and use ODBC connection in a sample SSIS package. This will help in resolving OLEDB connection issues also (that are common to both)
I can successfully log on to the database with this:
MySqlConnection conn = new MySqlConnection();
MySqlConnectionStringBuilder connString = new MySqlConnectionStringBuilder();
connString.Server = textEditServer.Text;
connString.UserID = "root";
connString.Password = textEditServerPassword.Text;
connString.Database = "geysercontrol";
conn.ConnectionString = connString.ConnectionString;
try
{
conn.Open();
Properties.Settings.Default.Properties["ConnectionString"].DefaultValue = conn.ConnectionString;
conn.Close();
}
catch (MySqlException)
{
XtraMessageBox.Show("No connection could be established");
}
But when I try to use the ConnectionString property to reconnect with different class, I get an MySQLException saying
Access denied for user 'root'#'localhost' (using password: NO)
What can be the possible causes to this? The page on possible causes on the MySQL website doesn't include my situation.
The code I use to reconnect is:
connection = new MySqlConnection();
connection.ConnectionString = (String)Properties.Settings.Default.Properties["ConnectionString"].DefaultValue;
connection.Open();
And the connectionString definitely is the same in both cases. It is:
server=localhost;User Id=root;database=geysercontrol;password=password
Add persist security info = true to the connection string I think.
If it were me though I wouldn't put connection string with a password in it in there. If you ever call Save, it will be exposed in the config file.
When I tried to add a connection it is showing the following error as shown in the attachment. “Unable to open the physical file. Access is Denied” .
When I searched about it, it suggest for adding the SQL Server’s account to the folder. Then, using the following query I found that the account is “LocalSystem”. When I tried to add “LocalSystem” to ACL of the folder, such an account is not available. How do we resolve it and add the connection to DBML?
Note: When I used DataReader with the database name in a C# program, it worked well.
Query Used:
declare #sqlser varchar(20)
EXEC master..xp_regread #rootkey='HKEY_LOCAL_MACHINE',
#key='SYSTEM\CurrentControlSet\Services\MSSQLSERVER',
#value_name='objectname', #value=#sqlser OUTPUT
SELECT convert(varchar(30),#sqlser)
Working C# Program:
SqlDataReader rdr = null;
SqlConnection con = null;
SqlCommand cmd = null;
try
{
// Open connection to the database
string ConnectionString = "server=D088DTRV;integrated security=true; database=BankAccount";
con = new SqlConnection(ConnectionString);
con.Open();
string CommandText = "SELECT * FROM Account";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string test = rdr["AccountType"].ToString();
}
}
The problem was related to Data Connections.
In the advanced window, when I checked, it was trying for ./SQLExpress. I modified it with ".".
I restarted the machine. I also stopped the SQLExpress in the services.msc
Data Source=.;AttachDbFilename=C:\DevTEST\Databases\LibraryReservationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True
I have published my website http://www.theyuvaworld.com for my college project but it is showing
Error 26 - Error Locating Server/Instance Specified. Other things are working properly.
You can visit website for detailed Error.
My project is C# ASP.NET 4.0 and built in Sql Server 2008 of Visual Studio 2010.
I am using this connection string in every page.
SqlConnection con = new SqlConnection("data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true");
SqlCommand cmd = new SqlCommand();
I know I can put it in Web.config but I don't know how to use it in aspx pages for queries?
My Question is : What changes should I do in my Connection String to get my website working.
Other details : I have taken my Web Hosting Plan from http://www.hostingfarms.in and it supports Sql Server 2008.
Try to work around this piece of code .Username and password should be supplied in get connection string if you are using sql authentication
private static void OpenSqlConnection()
{
string connectionString = GetConnectionString();
using (SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
}
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=MSSQL1;Initial Catalog=AdventureWorks;"
+ "Integrated Security=true;";
}