build mySQL database using c# console app - c#

Alright so I'm trying to make a web app, and I'm trying to use mySQL as my database. I want to use c# (visual studio 2008 SP1) to create functions for interfacing with the database. The syntax of how to do this is no problem but I'm not sure how to get the two to interact whatsoever; I don't understand the relationship. I have downloaded and configured a mySQL server, and through using the "mySQL Command Line Client" I have no problem composing a database using SQL commands. I have also downloaded mySQL for visual studio, and I have no problem using it's interface to add tables and so on. What I'm trying to do is write c# code and SQL statements in the same environment.
For reference my objective is to create a small app so that my friend and I can duel with our custom, physical mtg decks that we have composed. So for example I would like to set up a small c# interface to add, remove, and replace cards based on the changes we'd like to make to our decks out of the cards we already have. So in summation I would like to build a mySQL database through a c# console app.

There are docs for this on mysql.com: https://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
https://dev.mysql.com/doc/connector-net/en/connector-net-programming-mysqlcommand.html
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "mytable";
cmd.Connection = someConnection;
cmd.CommandType = CommandType.TableDirect;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLn(reader[0], reader[1]...);
}

Related

How to connect Microsoft access database to visual studio C#

I am using visual studio Windows forms for a login/sign-up project. So how would I go about connecting my Microsoft access data base to my visual studio project and establishing a connection in the code so I can write out a command.
It uses a connection string similar to SQL.
public string ConnString => $"Provider=Microsoft.ACE.OLEDB.16.0;Data Source = {FilePathHere};"
To persist to the file using ADO.NET, it will look like
private void ExecuteWrite(string sql)
{
try
{
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
OleDbCommand cmd = new OleDbCommand(sql, conn) { CommandType = CommandType.Text };
conn.Open();
_ = cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
Console.WriteLine(e.ToString());
}
}
A couple notes on Access:
Access has its own form of SQL which is very different than what you are used to, for example instead of char varchar you will have types like text. Check the full list of differences here
the SQL string you write must use " to escape things such as problematic column names
Tables cannot exceed 255 columns for some reason. Be ready to create seperate queries to split any massive table that goes over that limit, as Access will straight up refuse to process that query. Its the only db I know that suffers from such a limitation and it was a pain for a project I worked on. I got around it using some LINQ to split up the desired columns, and then crafting the separate CREATE or INSERT queries

Accessing legacy Visual FoxPro database from C#

I have a legacy Visual FoxPro database from which I need to get the data from.
I have DBC, DCT, DCX & FPT files in the database folder.
I installed the Visual FoxPro provider & driver and wrote a short C# program to access the data.
I also made sure the program is running in 32bit mode, since I understood that the VFP driver is 32bit.
However I'm getting the following error:
Additional information: Connectivity error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
I made sure that the driver name ("Microsoft Visual FoxPro Driver") as appears in the Windows ODBC 32bit administration tool is specified in the connection string, but it doesn't seem to help.
The code:
OleDbConnection yourConnectionHandler = new OleDbConnection(
#"Provider=VFPOLEDB.1;DRIVER=Microsoft Visual FoxPro Driver;Data Source=mydatabase.dbc;Mode=Read;Collating Sequence=machine");
// Open the connection, and if open successfully, you can try to query it
yourConnectionHandler.Open();
if (yourConnectionHandler.State == ConnectionState.Open)
{
string mySQL = "select * from tablename";
var command = yourConnectionHandler.CreateCommand();
command.CommandText = mySQL;
var res = command.ExecuteReader(); // throws the error
yourConnectionHandler.Close();
}
I've been stuck on this for a long time, and have tried everything I could find on the net.
Any idea?
You are saying provider and trying to use OleDbConnection (which is right) but defining an ODBC driver within the connection string. In other words, your connection string is wrong.
using (OleDbConnection cn = new OleDbConnection(
#"Provider=VFPOLEDB;Data Source=c:\MyPath\mydatabase.dbc;Mode=Read;Collating Sequence=machine"))
using (OleDbCommand cmd = new OleDbCommand("select * from tablename", cn))
{
cn.Open();
var reader = cmd.ExecuteReader();
// do something with the reader. ie:
// someDataTable.Load(reader);
cn.Close();
}
It works wonderfully well. In connectionstring you don't need to use the database name, you can just use the tables' path as the data source.

Can i make sql Database part of c# Project

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();
}

Using a View from SQL Server 2008 in C# & Asp.net

I have a C#/ASP.net project has included a database that I have developed that includes a nice and convenient View that would be handy to use.
I have the SQL connection setup to a SQL Server 2008 DB I created. It seems as though it is connecting fine, but I don't understand how to actually use the View that I created without hard coding the query into the program (been told this is bad sometimes?).
This is my connection I setup:
SqlConnection conn = null;
conn = new SqlConnection("Data Source=raven\\sqlexpress;Initial Catalog=ucs;Integrated Security=True;Pooling=False");
conn.Open();
SqlCommand command = new SqlCommand(query, conn);
Basically, I need some code to query using this View. I can see the View and look at the results that would be obtained, but not access it in the program!
The view is named "UserView". Help is much appreciated!
You could use something like the following. But it's usually considered evil to put hardcoded SQL commands into .Net code. It's much better and safer to use stored procedures instead.
This should get you started. You can modify it to use stored procedures by
changing the command.CommandType to indicate it's a stored proc call
And adding the proper parameters to the command that your SP needs.
Change command.CommandText to the name of your SP, thus
eliminating the hardcoded SQL.
sample code below:
using (SqlConnection connection = new SqlConnection("Data Source=raven\\sqlexpress;Initial Catalog=ucs;Integrated Security=True;Pooling=False"))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT * from your_view WHERE your_where_clause";
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// process result
reader.GetInt32(0); // get first column from view, assume it's a 32-bit int
reader.GetString(1); // get second column from view, assume it's a string
// etc.
}
}
}
}
Using VS2013 add a new DataSet to your project. Drag your View from the Server Explorer to the DataSet Design Surface.

Connection String Problem Oracle .Net

I am new to oracle and am trying to simply connect to an oracle db, but I am not sure where to find the proper credentials to put in the connection string. I simply downloaded and install oracle express edition on my machine, then installed the .Net references. My simple code is here:
string oradb = "Data Source=XE;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
try
{
conn.Open();
string sql = "SELECT FIRST_NAME FROM EMPLOYEES WHERE EMAIL='SKING'"; // C#
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader(); // C#
dr.Read();
//label1.Text = dr["dname"].ToString(); // C# retrieve by column name
label1.Text = dr.GetString(0).ToString(); // return a .NET data type
//label1.Text = dr.GetOracleString(0).ToString(); // return an Oracle data type
}
catch (OracleException ex)
{
label1.Text = ex.Message;
}
finally
{
conn.Close();
}
I am getting a TNS:could not resolve the connect identifier specified exception. Its probably because my connection string is wrong is what I am guessing. I cannot even go to the Server Explorer dialog in Visual Studio and test a connection correctly to my oracle db.
What steps do I need to take to figure out the proper credentials to plug into my connection string?
Or wording it like this....
If you were going to install oracle express on your machine, then connect to a .Net app what steps would you take to set up the connection string?
Maybe it is looking for a data source defined in a tnsnames.ora file called XE.
Try the Easy Connect naming method in the Express edition. It enables application clients to connect to a database without using any configuration files, simply by specifying the data source attribute through syntax shown below:
user id=hr;password=hr;data source=hr-server
user id=hr;password=hr;data source=hr-server:1521
user id=hr;password=hr;data source=hr-server:1521/XE
Replace hr-server with the dns name or ip of your machine.

Categories