I've created the simple program that is connected with one database. The connection with SQL db is perfect. I can insert data now. I use Object Explorer SQL Server.
Now my issue: I cannot use the program if the path to the mdf file isn't "C:/folder/repair.mdf". I want my program to be independent from the C disk, because I should send this program (vs files, etc) to other people.
How can I write the correct path and where can I do that?
You can try the following steps to move your db file to other disk and read the correct path.
First, please close all the connection about the database.(Execute the following query in Query Editor window )
ALTER DATABASE School SET SINGLE_USER WITH ROLLBACK IMMEDIATE
Second, you could copy your db file from the C disk to your project.(Include mdf and ldf file)
Finally, we can execute the following c# code to connect to the db file.(I place the db file in project\bin\debug\school.mdf).
private void button1_Click(object sender, EventArgs e)
{
string dbpath = System.AppDomain.CurrentDomain.BaseDirectory+"School.mdf";
string connstr = string.Format("Data Source=yourdatasource;AttachDbFilename={0};Integrated Security=True;", dbpath);
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
string sql = "select * from Student";
SqlCommand command = new SqlCommand(sql,connection);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
Console.WriteLine(reader[0].ToString());
}
connection.Close();
}
Note: The dbpath is a absolute path, which can specify to the corresponding path in different computers.
Related
I'm trying to make a backup to a network shared folder with the following code:
string filePath = ("\\pc-usuario\folder\backup\backup.bak")
string connectionString = String.Format(#"Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=True", server, database);
using (var connection = new SqlConnection(connectionString))
{
var query = String.Format("BACKUP DATABASE [{0}] TO DISK='{1}'", database, filePath);
using (var command = new SqlCommand(query, connection))
{
connection.Open();
command.CommandTimeout = 1800;
command.ExecuteNonQuery();
}
}
Got the following error:
The backup device cannot be opened. Operating system error 5(Access denied.).
If I try it with SQLExpress the same error happens. What am I missing?
You havent given the database backup a file name, only a file path
E.g. the final code should read
backup database wibble to disk = '\\pc-usuario\folder\backup\wibble.bak'
i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}
I am building a inventory based application that can be directly run from any pc without any installation and so i am using SQL CE.. On Start, I am checking if database is present. If Not i am creating new database as :
try
{
string conString = "Data Source='ITM.sdf';LCID=1033;Password=ABCDEF; Encrypt = TRUE;";
SqlCeEngine engine = new SqlCeEngine(conString);
engine.CreateDatabase();
return true;
}
catch (Exception e)
{
//MessageBox.Show("Database Already Present");
}
The database is created properly and i can access the database to create tables as well.. The Problem i am facing is - I am inserting and updating records in windows form on button click with code :
using (SqlCeConnection connection = new SqlCeConnection(DatabaseConnection.connectionstring))
{
connection.Open();
String Name = NameTxt.Text.ToString();
String Phone = PhoneTxt.Text.ToString();
double balance = Double.Parse(BalanceTxt.Text.ToString());
String City = CityTxt.Text.ToString();
string sqlquery = "INSERT INTO Customers (Name,Phone,Balance,City)" + "Values(#name,#phone, #bal, #city)";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, connection);
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#phone", Phone);
cmd.Parameters.AddWithValue("#bal", balance);
cmd.Parameters.AddWithValue("#city", City);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("Data Inserted");
}
else
{
MessageBox.Show("Error Occured. Cannot Insert the data");
}
connection.Close();
}
and Updation Code is
using (SqlCeConnection connection = new SqlCeConnection(DatabaseConnection.connectionstring))
{
connection.Open();
int idtoedit = select_id_edit;
String Name = NameEditTxt.Text.ToString();
String Phone = metroTextBox1.Text.ToString();
String City = CityEditTxt.Text.ToString();
string sqlquery = "Update Customers Set Name = #name, Phone = #phone,City = #city where Id = #id";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, connection);
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#phone", Phone);
cmd.Parameters.AddWithValue("#id", idtoedit);
cmd.Parameters.AddWithValue("#city", City);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("Data Updated");
}
else
{
MessageBox.Show("Error Occured. Cannot Insert the data");
}
loadIntoGrid();
connection.Close();
}
Whenever i execute code for inserting and updating records - Records are reflected in datagrid filled with adapter from database table. But once i restart the application, values do not appear in database. Once in a million, values are reflected in database. I cannot understand the reason behind this issue.
I have reffered to these articles :
C# - ExecuteNonQuery() isn't working with SQL Server CE
Insert, Update, Delete are not applied on SQL Server CE database file for Windows Mobile
But since i am creating database programmatically - It is getting created directly to bin/debug directory and i cannot see it in solution explorer in visual studio for changing copy options
You probably rewrite your database file with a blank copy from your project.
See this answer. You should not store your database in a bin folder, rather you should find a place in user's or public profile in AppData or another folder, depending on your needs.
The connection string would look like this:
<connectionStrings>
<add name="ITMContext" connectionString="data source=|DataDirectory|\ITM.sdf';LCID=1033;Password=ABCDEF; Encrypt = TRUE;" providerName="System.Data.SqlServerCe.4.0">
You shuld deploy your db file with your custom code run at app's starup to a chosen location, see this ErikEJ blog: http://erikej.blogspot.cz/2013/11/entity-framework-6-sql-server-compact-4_25.html
private const string dbFileName = "Chinook.sdf";
private static void CreateIfNotExists(string fileName)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// Set the data directory to the users %AppData% folder
// So the database file will be placed in: C:\\Users\\<Username>\\AppData\\Roaming\\
AppDomain.CurrentDomain.SetData("DataDirectory", path);
// Enure that the database file is present
if (!System.IO.File.Exists(System.IO.Path.Combine(path, fileName)))
{
//Get path to our .exe, which also has a copy of the database file
var exePath = System.IO.Path.GetDirectoryName(
new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
//Copy the file from the .exe location to the %AppData% folder
System.IO.File.Copy(
System.IO.Path.Combine(exePath, fileName),
System.IO.Path.Combine(path, fileName));
}
}
Check also this post.
You have several options to change this behavior. If your sdf file is
part of the content of your project, this will affect how data is
persisted. Remember that when you debug, all output of your project
(including the sdf) if in the bin/debug folder.
You can decide not to include the sdf file as part of your project and manage the file location runtime.
If you are using "copy if newer", and project changes you make to the database will overwrite any runtime/debug changes.
If you are using "Do not copy", you will have to specify the location in code (as two levels above where your program is running).
If you have "Copy always", any changes made during runtime will always be overwritten
The database file in your project can be different when debugging or not. Check also this answer. You might be writting your records to another copy of the database file.
I am trying to rebuild an application that originally used sqlite to now use 'localdb'. (I want an application that can create its own database locally and at runtime without requiring a pre-installed instance of sql server or sql express on the target machine)
I want to move away from using a 'third party' library (sqlite) as experience has told me it can be a pain to get it working from scratch, and towards something supposedly more straightforward to get up and running from scratch.
Using code copied (and slightly modified) from the web I have managed to create an mdf file dynamically/programmatically, but I am puzzled by what happens if I run it more than once, even if I choose a new filename each time. Namely it seems to somehow keep the changes/additions made on each run. Below is the relevant code...
public partial class Form1 : Form
{
SqlConnection conn;
public void CreateSqlDatabase(string filename)
{
string databaseName =
System.IO.Path.GetFileNameWithoutExtension(filename);
conn = new SqlConnection(
String.Format(
#"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True"
));
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText =
String.Format(
"CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')"
, databaseName, filename);
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
CreateSqlDatabase(openFileDialog1.FileName);
}
}
private void button2_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText =
"create table mytable (id int, name nvarchar(100))";
comm.ExecuteNonQuery();
comm.CommandText =
"insert into mytable (id,name) values (10,'testing')";
comm.ExecuteNonQuery();
comm.CommandText = "select * from mytable";
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
textBox1.Text +=
reader["id"].ToString() + ", " + reader["name"].ToString() + "\r\n";
}
conn.Close();
}
}
If I run the app once It runs through fine.
If I run the app a second time, and choose a different filename for the database it tells me 'mytable' already exists.
If I comment out the create table code it runs, but the select query returns multiple rows indicating multiple inserts (one for each time the app runs)
I am just seeking to understand why this happens. Do I need to delete database/table each time if I want the app to behave as if it has created the database/table from scratch on each subsequent run?
You have initial catalog 'master' in your connection string. Are you sure you haven't created the tables in the master database instead of the newly created database?
After the creation & detach of the database file, you could try and change your connection to:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=c:\xxx\xxx\xxx.mdf");
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)