Beginner requests Help with Mysql and C# - c#

I'm trying to build a program that uses a C# to work with a MySQL DB. I get the C# syntax, and can write the language, but I don't have much experience with the libraries, and I feel a bit lost.
Could someone post examples of how a program would be built (in technical terms, syntax would be nice, but pseudo code is fine, too)?
I understand the theory of how it works, but need a hands on approach to it.
Thank you.
EDIT
I forgot to add that I want to learn how to do it with the .NET v.2.0 framework / VS2005 / MySQL v5.0 combination.
EDIT # 2
2.0 .NET will only be supported. =)

Here is tutorial for Entity Framework + MySQL.
There are lots of other ways to operate with DB, depending on what you need:
If you need execute raw sql queries against DB - use OdbcConnection + OdbcCommand
Need to manipulate items in DB as objects - use ORM (EntityFramework, NHibernate, Linq2Sql)
Like old-style DB interop? - DataSets is your choice.
I really like EF. Easy thing to start with.
PS: And before mixing UI and DB-interop, please read about Separation of concerns. MVC is interesting to read about too. About "libraries": create another project in your solution and add DB-interop logics there. Don't mix it in one assembly, because when your project becomes bigger than "Hello DataBase!" application it will create a big mess in code and logics, really.
UPDATE:
Using VS2005 and .net 2.0 is mysterious idea, really. Lots of tools and assemblies where made since 2.0 release. Linq, Orm-s, etc. Live without them is hard and all the benefits of C# are lost. I highly recommend to use latest techniques, if there is no strict reasons to use 2.0.
If using SqlServer - ObdcCommand and OdbcConnection can be replaced to SqlCommand and SqlConnection. (thanks #Abe Miessler comment)

Here is an example swiped from MSDN:
public void InsertRow(string connectionString, string insertSQL)
{
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OdbcCommand command = new OdbcCommand(insertSQL, 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.
}
}
If you want to read records in a DB, look at this example:
public static void ReadData(string connectionString)
{
string queryString = "SELECT DISTINCT CustomerID FROM Orders";
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
OdbcCommand command = new OdbcCommand(queryString, connection);
connection.Open();
// Execute the DataReader and access the data.
OdbcDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("CustomerID={0}", reader[0]);
}
// Call Close when done reading.
reader.Close();
}
}
FYI i am just copy/pasting these directly from MSDN. I highly recommend reading over their documentation and looking at their examples if you are just getting started.
http://msdn.microsoft.com/en-us/library/system.data.odbc.odbcdatareader.aspx

Here is a blog post getting you started with MySql and C#.
http://blog.bobcravens.com/2010/06/the-repository-pattern-with-linq-to-fluent-nhibernate-and-mysql/
Hope that gets you started.
Bob

Related

AdsConnection throws EntryPointNotFoundException on second connection but works the first time

I have a piece of code that I reuse that helps me connect to an adt database and read the data.
using Advantage.Data.Provider;
...
protected DataTable FillTable(string tableName)
{
DataTable table = new DataTable();
using (var conn = new AdsConnection(connectionString))
using (var adapter = new AdsDataAdapter())
using (var cmd = new AdsCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select * from " + tableName;
adapter.SelectCommand = cmd;
conn.Open();
adapter.Fill(table);
conn.Close();
}
return table;
}
This code works perfectly the first time I go through it, but gives the following exception the second time I call it with a different table name.
System.EntryPointNotFoundException: 'Unable to find an entry point named 'AdsIsConnectionAlive' in DLL 'ace32.dll'.'
I would like an explanation.
I've tried to read up on this error, but all the possible scenario's I've found don't explain why it works the first time. They mention problems with the DLL like it being the wrong version or some incompatability with the .NET version, ...
If I change the order of the calls the code still fails on the second time, so I know the problem isn't with the name of the table or the way I call my code. The problem is probably with me not closing the connection correctly. I've tried adding more braces just to make sure that that part runs correctly and I've debugged to make sure that the first conn.Close(); is executed correctly.
I could place all my code within this code and only use one connection that I keep open as long as I need it. That would bypass my problem, but I would like to avoid that and to understand what I'm doing wrong.
This is most likely caused by loading an older version of ace32.dll from a newer version of the ado.net components. The AdsIsConnectionAlive was introduced in a later version of the DLL - not sure about the exact version probably 6.0 or later.
The first time the connection was made, the ado.net component knows that the connection was not alive so there was no need to call the IsAlive entry point. The second time around, since there was already a connection made to the same connection path, it would try to reuse it by checking to see if it is still alive. I think that there is a way to disable the connection caching but do not remember the detail. A better solution would be to make sure that the advantage DLLs are matching version.

SQLite Viewers/Browsers prevention in c#

I need to know how to secure my sqlite database file from being edited or adding records to by sqlite viewers/browsers, I am using c#
You could use the SQLite Encryption Extension the database could then not be opened as an SQLite database without the key.
An alternative would be to simulate how SEE works. That is that the data stored on the disk is always fully encrypted by your favourite encryption method and that the database is decrypted to a temporary file and then opened (obviously only when the correct key is provided) when accessing the database, it then being encrypted and written when done with.
Another alternative would be to utilise SQLCipher
I worked around it and used System.Data.Sqlite to encrypt the database using these methods
void EncryptDB()
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("Data Source=Test.db;Password="))
{
conn.Open();
conn.ChangePassword("password");
conn.Close();
}
}
void DecryptDB()
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("Data Source=Test.db;Password=password"))
{
conn.Open();
conn.ChangePassword("");
conn.Close();
}
}
I call the DecryptDB() method before I connect to the database with sqlite-net-pcl and I call EncryptDB() after the connection is closed.
If you are asking why I didn't use System.Data.Sqlite instead of sqlite-net-pcl, that is because I found that sqlite-net-pcl is neat and less code is needed to perform the task which makes it easier to read and document.
#MikeT Thank you for your answer it really guided me and helped me reach this solution.

Mono can't open sqlite database

I'm attempting to do a very basic connection to a sqlite v3 database and I'm using monodevelop 3.0 and Mono 2.10 and am unable to get connected to the database. I can make the app create the database, but then it immediately fails attempting to connect to it. Any suggestions? I had started with a different database, but then decided to have my app attempt to create a database empty and then connect to it. This still seems to fail.
SqliteConnection.CreateFile("db\\DataWorksProg.s3db");
SqliteConnection conn = new SqliteConnection("Data Source=file:db\\DataWorksProg.s3db");
conn.Open();
This small piece of code fails with an error about not being able to open the database file.
Mono.Data.Sqlite.SqliteException: Unable to open the database file
Permissions look OK and I have the Sqlite3.dll in the project, and it seems to be working OK. Have I missed anything obvious? I'm pretty good on the Visual Studio side, but still fairly fresh working in a Mono/Monodevelop environment.
What platform?
I don't believe you need to create a file. If it's not found, iirc, it'll make the database file.
Fwiw, on a Mac, I'm doing (note URI to a pretty standard path; I haven't used Data Source)...
using System;
using System.Data;
using Mono.Data.Sqlite;
namespace test
{
class MainClass
{
public static void Main (string[] args)
{
IDbConnection conTemp = null;
IDbCommand cmdTemp = null;
conTemp = (IDbConnection)new SqliteConnection ("URI=file:/Users/userName/mnmh.db");
conTemp.Open ();
cmdTemp = conTemp.CreateCommand ();
cmdTemp.CommandText = "SELECT * FROM employee";
IDataReader drTemp = cmdTemp.ExecuteReader ();
while (drTemp.Read()) {
Console.WriteLine (drTemp.GetString (0));
}
}
}
}
etc etc
Check the obvious -- you've referenced all the stuff you're using, etc.
Figured out my problem here. Apparently instead of using
"Data Source=file:db\\DataWorksProg.s3db"
I should have been using
"URI=file:db\\DataWorksProg.s3db"
Switched to the URI and it works as expected. I had thought from reading the docs that under the 2.0 profile, the DataSource part was needed instead of the URI, but I got the results I'm looking for.

Update table (rows) Access 2007 and C# 2010

So this is probably the most naive question but that is what questions are for I guess;
Then, my issue is that I have no idea on how to connect Visual C# Express 2010 to Access 2007 and do the typical insert, update, delete, search in an application in C#, I have just learned the basics (finished a console tutorial, which I believe is more than enought, having previous background of VB6 using access 97), and I have been searching here and in the web, but the only thing I could find where the msdn tutorials which I dind't find really clear.
So in my app I just need to link comboboxes, query those values to obtain new ones, do calculations and then store in arrays (and maybe show these in datagrids as well as edit them from said datagrids, which is a bit more complicated I guess) and finally store them in various tables, but I haven't really found a strong (or most likely simple) manual that will guide me to create the typical app insert, update, delete using winforms.
Do you guys have any good links in order to do this?
Thanks.
You can try with this code
Here link about string connection : http://www.connectionstrings.com/access-2007
var query = "...";
var connectionString = "...";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
using(var command = new OleDbCommand(query))
{
// 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.
}
}

Connecting a MS Access (.mdb) Database to a MVC3 Web Application

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.
}
}

Categories

Resources