I am creating a winform application which connects to a ms-access database. The problem is with my connection string as i can access the database locally but if i run from my usb stick or from any other pc it would give me error. How can i modify my connection string so that i can run my application on other pc without any trouble.
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Aakash\Documents\Visual Studio 2013\Projects\Industrial Foundry\record.accdb";
using (OleDbConnection con = new OleDbConnection(strConnect))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("select * from Industry ", con))
{
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Perhaps this would be a good start:
http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx
Since your title indicates you have a WinForms application, you may also want to consider adding a "Browse" button to locate the database and then using a connection string builder to build your connection.
I hope this can help you.
Create a winform where you can input parameters like "server", "password", etc., etc
After that, update your connection string with the parameters:
Friend Principal As New SqlClient.SqlConnection("data source=" & My.Settings.Server & ";INITIAL CATALOG=" & My.Settings.DB & ";UID=" & My.Settings.User & ";PWD=" & My.Settings.Password & ";workstation id=" & My.Settings.PC & ";packet size=4096")
Your connection string points directly to a path on your C: drive.
There are a number of ways that you could fix it; you could just prompt the user for the file location, and/or store it in a user configurable settings file.
I think simple way for you would be use App.Config file (Application Configuration File), you can add your database key in config file, when app launch you can check if key value is null than you should force user to choose database path, and you can set that database path to your config file. You can read your key value something using..
Code for Read Key
System.Configuration.ConfigurationSettings.AppSettings["DBKey"];
Code for Write Key
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("DBKey", "DBPath");
config.Save(ConfigurationSaveMode.Modified)
Thanks
Suresh
Related
I have two computers. One is running SQL Server, and I can access the server using SQL authentication from the 2nd PC using SSMS.
I have created a C# Windows Forms application that connects to the database. However, I couldn't access my server from the application.
I disabled the firewall, allowed remote control, and allowed mixed mode authentication. I also forwarded required ports to my IP in my router settings.
I tried both these connecting strings, but they didn't help:
"Persist Security Info = False; User ID = gues; Password=gues;Initial Catalog = CoronaNurse; Server=" + server;
"Data Source=" + server + ";Initial Catalog=CoronaNurse;Integrated Security=false;UID=gues;Password=gues";
(server is a string that have IP of my server)
(gues is a login in my Server)
The weird thing is when I login as gues in SSMS from my 2nd computer I can access the server in the first computer.
The question is, how do I access my server from a computer that doesn't have SSMS or any specific Login?
I need my application to be able to connect to my server without anything else installed, but I can't find where my problem is.
Adding from comments:
Im using the connecting to get a con string from my DB depends on the table i get with my gue.login function SqlDataAdapter
adapter = new SqlDataAdapter("select * from gue.login('" + textBox1.Text.Trim() + "', '" + textBox2.Text.Trim() + "', '" + server + "')", conn);
SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
DataSet ds = new DataSet();
adapter.Fill(ds);
string connection;
connection = ds.Tables[0].Rows[0][0].ToString();
Unless you haven't posted up all of your code, you don't appear to be controlling your SQL connection and I would strongly suggest that you use a parameterised call to protect against SQL injection from using direct text entry field values e.g.:
var dataset = new DataSet();
using (var connection = new SqlConnection(SqlConnectionString))
{
connection.Open();
var command = new SqlCommand("GetAll", connection);
command.CommandType = CommandType.StoredProcedure;
var adapter = new SqlDataAdapter(command);
adapter.Fill(dataset);
...
}
The SQL is wrong, and the connection strings look a little off. You might also need an instance name as part of the server. For example, instead of just localhost or 192.168.0.20, you might need localhost\SQLExpress or 192.168.0.20\..
One way you can find the connection string for sure is to use Visual Studio instead of SSMS to connect to the database. The Visual Studio Database Tools has a similar connection window as SSMS, and you can use it to show you the actual connection string it used.
When you've figured that out, try something more like this:
var connString = $"Server={server};Database=CoronaNurse;User Id=gues;Password=gues";
var sql = "select * from gue.login WHERE username = #username AND pHash = #pHash";
var ds = new DataSet();
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(sql, conn))
using (var adapter = new SqlDataAdapter(cmd))
{
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 50).Value = textBox1.Text.Trim();
cmd.Parameters.Add("#pHash", SqlDbType.Char, 60).Value = BCrypt.Net.BCrypt.HashPassword(textBox2.Text.Trim());
adapter.Fill(ds);
var connection = ds.Tables[0].Rows[0].Items[0].ToString();
}
Note the use of both parameterized queries and BCrypt (you can add BCrypt via NuGet). There are a few things in database development that are too important to do wrong, even for proof-of-concept and learning projects. One of these is SQL Injection. Another is password handling. What I posted still isn't quite right for password handling (you should instead retrieve the stored hash and use the Verify() method), but it's close enough to set you on the right path.
Someone has told me that I can't access my online SQL Server DB from a client PC that doesn't have a Local DB.
I guess that explains my problem perfectly!
I never knew that, in my case, that is my problem right?
I googled for half a day how to set the path of my database so if I put it on an other computer it will work. I would keep googling but I really need the answer really fast... I'll have to use it to a competition in few hours.
string path = Path.Combine(Application.StartupPath, "Database1.mdf");
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + path + ";");
conn.Open();
SqlCommand command = new SqlCommand("SELECT NAME FROM DATA", conn);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string text = reader.GetString(0);
MessageBox.Show(text);
}
SqlCommand c = new SqlCommand("INSERT INTO DATA (id, name) VALUES(i, v)", conn);
c.Parameters.AddWithValue("#i", 1);
c.Parameters.AddWithValue("#v", "Jack");
c.ExecuteNonQuery();
conn.Dispose();
This code is working for selection but not for insertion. Then I hardcoded the path into:
String s = #"C:\Users\Radu\Documents\Visual Studio 2013\Projects\WindowsFormsApplication7\WindowsFormsApplication7\Database1.mdf";
and it works for both so it's not the SQL statement that is wrong.
So my question is: what is the path I should put into my SqlConnection object so that when they get my source code on my competition and test it on another pc it will work.
LocalDB is meant exclusively for development. You cannot use it in production. In your case, 'production' means the competition. Unless the competition organizer specifies that they support a SQL Server instance for you to connect to, and give out the connection parameters (ie. very unlikely), you shouldn't use use SQL Server in your project.
You can put the MDF file on any file share that your computer has access to. Just alter the path variable to point at the correct file share.
See answers to your question here Can SQL Server Express LocalDB be connected to remotely?
I have made a sample c# application (First project ive done) Its quite a simple application which uses a database to store data and edit data.
The problem i am having is the program works perfectly fine on my computer but if i publish the application and put it on another computer it cannot use the database as it is not part of the project.
I used connection string
private SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\Ryan\\Documents\\Visual Studio 2015\\Projects\\youtubeLoginTut\\youtubeLoginTut\\data.mdf\"; Integrated Security = True; Connect Timeout = 30");
Which is obviously the path to the database on my computer and will not be the same on the next computer. Is there anyway i could include the database in the package so its referenced from where ever the application sits.
Ive tried shortening the path to for example ..\data.mdf but to no avail and i cant find anything on google so im all out of ideas.
Go easy im very new to c#
Cheers
Ryan
There is a way to get the location of your project in every computer : (inside the bin/debug/)
string path = AppDomain.CurrentDomain.BaseDirectory //example : C:/Users/Ryan/Documents/Visual Studio 2015/Projects/Youtubetut/bin/debug
you just need add the location of the database inside of the project's folder to this path. path will replace your "C:\Users\Ryan\Documents\Visual Studio 2015\Projects\youtubeLoginTut" and make sure to move your database inside the debug folder.
Afeter publiching your database with your project you get the Installtion Path From Deployment byuse :
string sourcePath =System.Reflection.Assembly.GetExecutingAssembly().Location
sourcePath =sourcePath +"\data.mdf";
If it's a simple application you can try to use embeded DB like SQLite. I use it in my application and it works fine.
If you want to use SQLite, let's go step by step.
download the dynamic library System.Data.SQLite.dll for your version of the .NET Framework
link System.Data.SQLite.dll to your project
write a code something like this
Create a table
SQLiteConnection con = new SQLiteConnection(String.Format(#"Data Source={0};Version=3;New=True;", "./db/mydatabase.sdb"));
con.Open();
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandText = #"CREATE TABLE Books (BookId int, BookName varchar(255), PRIMARY KEY (BookId));";
cmd.ExecuteNonQuery();
con.Close();
Read the data
using(SQLiteConnection con = new SQLiteConnection(String.Format(#"Data Source={0};Version=3;New=False;", "./db/mydatabase.sdb")) {
con.Open();
using (SQLiteCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT BookName FROM Books WHERE BookId=1 LIMIT 1;";
using (SQLiteDataReader reader = cmd.ExecuteReader()) {
if (reader.HasRows && reader.Read()) {
oResult = Convert.ToString(reader["BookName"]);
}
reader.Close();
}
}
con.Close();
}
I want to make a login page with an Access database for a school project with asp.net. I dont have really experience with C# so im doing different tutorials.
protected void Login1_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=http://tmti-16.ict-lab.nl/database/ek2012.mdb";
string query = "Select Count(*) From users Where username = ? And userpassword = ?";
int result = 0;
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", UserName.Text);
cmd.Parameters.AddWithValue("", Password.Text);
conn.Open();
Session["User"] = UserName.Text;
result = (int)cmd.ExecuteScalar();
}
}
if (result > 0)
{
Response.Redirect("index.aspx");
}
else
{
Literal1.Text = "Invalid credentials";
}
}
In Access I have the table 'users' with the 'username' and 'userpassword' rows.
The problem you are encountering is almost certainly to do with the data source segment of your connection string:
string connect = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=http://tmti-16.ict-lab.nl/database/ek2012.mdb"
The Access mdb file should be on a local path. This can be anywhere on your local file system that the account your web application is running as has permission to access, but, usefully, ASP.Net actually has a better place to put these files, the App_Data folder.
If you place your mdb file in this folder, your connection string would then become:
string connect = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|ek2012.mdb"
The contents of the App_Data folder will not be served to clients so this is a secure place to put your data. It's also a good idea to use it as it keeps the data with the project; often, people will put data related files in a file system folder outside of the web root, which means you then have to remember this dependency when moving the site to another computer.
A common issue you might have with accessing files in App_Data is usually related to permissioning; the user you are running the code as will need read and write permissions in this directory in order to modify the mdb file. This is covered in the section "Configuring Permissions for an Access Database" in this MSDN Article.
I'm using the windows forms aplication with an ms access database. And i would like to know if there is a way to show the directory of the database file (to save data in it)excpet like this:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=save.mdb";
OleDbConnection empConnection = new OleDbConnection(conString);
string insertStatement = "INSERT INTO zivila "
+ "([naziv],[kalorij],[beljakovin],[oh],[mascob]) "
+ "VALUES (#naziv,#kalorij,#beljakovin,#oh,#mascob)";
or this:
"Data Source=D:\Simonova aktovka na namizju\matura\test5\save.mdb";
couse if i use the first one the aplication undos the changes i've made when i close it(the aplication)
the second one makes me have to change the path everytime i bring the aplication to another computer(cous the direktory is different of coars)
So... is there another way?
Try this:
Data Source=|DataDirectory|\save.mdb