How to connect to local SQL database? - c#

As of now I've been given a piece of software that reads XML files and presents these graphically, to give the user some overview to the events these files describe.
The crux as of now is that one of the engineers using the software has requested that all the data you load into the program should be possible to save to a database.
My pickle is as follows:
public void addToDBO(List<List<EventElement>> insertList)
{
SqlConnection s1 = new SqlConnection();
s1.ConnectionString = filePath;
s1.Open();
SqlCommand command = new SqlCommand();
command.Connection = s1;
foreach (List<EventElement> item in insertList)
---------------------SNIP----------------------------
//Adding-data-to-database logic
I mean to write the loaded data into a database deployed localy, but the the problem is that it does not accept my hamhanded methods of simply adding the database's filepath as the filepath string.
So, to summarize:
How do I correctly connect to a database situated on my C:/?
Thank you in advance.

You do not simply pass a file path. The connection string needs to follow a certain convention. For example
Provider=SQLNCLI10;Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;
Database=dbname;Trusted_Connection=Yes;
See http://www.connectionstrings.com/sql-server/ for more

Related

How to create the SQlite database when the application is deployed/installed?

I am new to c#/.NET and developing an application with SQlite datbase and entity framework and it is all working fine during testing. I am specifying the below for the filepath to the .db file.
var path = AppDomain.CurrentDomain.BaseDirectory;
On deployment I need the application to create the database fresh, that doesn't contain the test data I was using during development. So I cannot simply copy the current .db file. Can anyone help with code that checks existence of database, and if not it will create new?
You can use this method:
private static void CreateFreshDb(string dbFilePath)
{
// Create the DB file
SQLiteConnection.CreateFile(dbFilePath);
// Create a table
var connectionString = $"Data Source={dbFilePath};Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string creationScript = "Create Table Person (Id int, Name varchar(20))";
SQLiteCommand command = new SQLiteCommand(creationScript, connection);
command.ExecuteNonQuery();
command.Dispose();
}
}
And call it like that:
string dbFilePath = "C:\\Db\\Database.db";
if (!File.Exists(dbFilePath))
{
CreateFreshDb(dbFilePath);
}
Note that I use the System.Data.SQLite library here.
An appliation that creates databases should be in principle a script that creates databases. If you application has its own business line which requires a database, but it is not intended to create a database at first, better you create it manually outside the code and then simply let the code choose between which database to use between testing and production, via appSettings or similar solution.

Reading MySql binlog

I don't agree that this question was answered effectively: decode mysqlbinlog in C#.
I have, what I think is the same question: I want to read the MySql binlogs from within a c# application, but do not know the format of the file. How can I properly parse these files' data?
First, what I learned:
Most of the source code files for MySql are installed along with the assemblies and generally located in [basedir]\include. For example, a typical install would place the files in Program Files\MySql\MySql 5.6\include.
mysqlbin.cc was NOT in that folder. However, I was easily able to get the file by doing a quick Google search. The file can be found here: https://code.google.com/p/mg-common-utils/source/browse/trunk/myreplicator/src/mysqlbinlog.cc?r=4 . It is well documented and easy to read.
Second, my solution:
As akuzminsky pointed out, the format of MySql's binlog is subject to change. However, the format returned from the mysqlbinlog.exe utility is consistent. This application is typically included in a MySql install and should be located in [basedir]\bin. I now run this application from within a c# Console Application and parse the results. I used the following steps to accomplish this:
Enabled binlogging on the MySql server from within the options file. In MySql Workbench, check 'log-bin' under the logging tab. Or, type 'log-bin=' in the settings file (often located in [basedir]. Might be called 'my.ini' or 'my.cnf' or something else. Generally, with .cnf or .ini extension). A filename is not required. When one is not specified, MySql will automatically create filenames for the logs. However, review MySql documentation on possible issues with this.
From within my client application, I query the server to get the path of each binary log (there could be many). To do this:
query show global variables like 'datadir' //returns the data directory.
query show binary logs //returns the filename of each binary log, along with its file size (helpful for reading).
Parsing these together gets the path for each binary log.
Since mysqlbinlog.exe is located in [basedir]\bin, I query the server to get the path of the base directory:
query show global variables like 'basedir'
Then, I parse the result with '\bin\mysqlbinlog.exe'
I use the Process class to create a new process, execute each binary log using mysqlbinlog.exe, and read each files results into a string variable:
private static string GetLogTexts(Liststring> logfilenames)
{
List<string> _logtexts = new List<string>();
string _basedir = GetBaseDir();
foreach(string logfilename in logfilenames)
{
Process proc = new Process();
proc.StartInfo.FileName = _basedir + "\\bin\\mysqlbinlog";
proc.StartInfo.Arguments = string.Format("\"{0}\"", logfile);
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
_logtexts.Add(proc.StandardOutput.ReadToEnd());
}
return _logtexts;
}
private static string GetBaseDir()
{
string path = "";
using (MySqlConnection conn = new MySqlConnection(RemoteServerConnectionString))
{
conn.Open();
using (MySqlCommand cmd1 = new MySqlCommand("show global variables like 'basedir'", conn))
{
using (MySqlDataReader reader = cmd1.ExecuteReader())
{
while (reader.Read())
{
path = reader.GetString(1);
}
}
}
}
return path;
}
Finally, I parse the results using my own logic (specific for what I am looking for). The results are very easy to read: mysqlbinlog uses regular line breaks and statements are terminated by a delimiter, which is defined prior to the statement (as usual, there can be multiple delimiters).
I hope this helps someone!

DataDirectory Set up project

I am doing a SETUP project for a C# winforms, sqlite application.
Connection string seems to a bit of a problem. The user will put the Database he wants to work with at a location(which v will tell him). In this example it is "C:\\Program Files(x86)\\DefaultCompany\\RSetup"; The user can work his own copy of the DB.
So I am setting the data directory to this path in the Program.cs Main
This is the only way I can think of. If there is a better way thats grt!!.
App.config
<add name="ConnString" connectionString="|DataDirectory|\MySQlite.db;Compress=True;Version=3"
providerName="System.Data.Sqlite" />
Program.cs
Setting the datadirectory to the path of the executable. Currently hard coded the path of the executable
static void Main()
{
AppDomain.CurrentDomain.SetData("DataDirectory","C:\\Program Files(x86)\\DefaultCompany\\RSetup");
This doesn't seem to be working. It doesn't give any error except the data is not blank. Doesn't seem to be working in both set up and the regular project
Thank you
JC
You could ask the user where the database is located, store that path somewhere (such as User Settings) and then you can retrieve it at any time. This would give the user more flexibility of where to put it and multiple users on the same machine could have their own database if desired.
Here is some pseudocode...
string dbLocation = Properties.Settings.Default.DatabaseLocation;
if (string.IsNullOrWhiteSpace(dbLocation)
{
dbLocation = AskUserForLocation();
Properties.Settings.Default.DatabaseLocation = dbLocation;
Properties.Settings.Default.Save();
}
AppDomain.CurrentDomain.SetData("DataDirectory",dbLocation);
Using this approach you could also add a menu option to allow the user to change the location if desired.
It also gives you the ability to retrieve the value anywhere, including where you create a connection, you can append the path to the location between where you read the connection string and you create a new connection.
SQLiteConnection myConnection = new SQLiteConnection;();
myConnection.ConnectionString = Path.Combine(Properties.Settings.Default.DatabaseLocation, myConnectionString);
myConnection.Open();

How to Connect to SQL Server Programmatically in C#?

I have developed a program (C#) which creates a SQL database using this code:
string SQLCreation = "IF NOT EXISTS (SELECT * FROM master..sysdatabases WHERE Name = 'x') CREATE DATABASE x";
SqlConnection PublicSQLDBCreationConnection = new SqlConnection(connectionString);
SqlCommand PublicSQLDBCreation = new SqlCommand(SQLCreation, PublicSQLDBCreationConnection);
try
{
PublicSQLDBCreationConnection.Open();
PublicSQLDBCreation.ExecuteNonQuery();
PublicSQLDBCreationConnection.Close();
}
//'then creates a table and so on
Now I want to have a client application which connects to this database (via LAN) WITHOUT using IP or computer name. How is that possible? Is it possible do this and have a dataset while not mentioning IP Adr. or computer name?
P.S. Don't Worry Guys, I simplified my code just for your view, I have made sure that SQL injection or other attempts won't happen.
Also I have to say that My Reason for not mentioning servername or IP is that I want to mass deploy my Application on many Networks
You could use SqlDataSourceEnumerator to get a list of all Sql Servers that are visible and browsable. This is not a good technique, since you could get an instance that you don't have the right to create a database on it, but you could still try something with that.
var enumerator = SqlDataSourceEnumerator.Instance;
foreach (DataRow row in enumerator.GetDataSources().Rows)
{
var serverName = row["ServerName"];
var instance = row["InstanceName"];
// build a connection string and try to connect to it
}

Creating Sqlite Embedded database from application

I have a winforms app that uses sqlite to store data. Instead of shipping a blank database, can I use scripts to create the tables the first time the user uses the app? Can you point to a C# example?
Update: I want to avoid shipping a blank database. So if a user install the app for 1 user only, only his profile gets a copy. All users profile gets the database if the install is for all users.
Yes, this is possible:
When the application first runs, check if the database file exists.
If it doesn’t, open it with the Sqlite option FailIfMissing=False. This will create a new file.
Then, use SQL commands like CREATE TABLE ... to create the schema structure.
For the second step, I use code that looks something like this:
public DbConnection CreateConnectionForSchemaCreation(string fileName)
{
var conn = new SQLiteConnection();
conn.ConnectionString = new DbConnectionStringBuilder()
{
{"Data Source", fileName},
{"Version", "3"},
{"FailIfMissing", "False"},
}.ConnectionString;
conn.Open();
return conn;
}

Categories