C# connection with MySQL Database - c#

once again im not really getting any further by just using google and searching through the forum, so here we go:
Im trying to establish a connection with C# and a MySQL Database (which is running on phpmyadmin).
This is the Code I got so far:
using System;
using System.Data;
using MySql.Data.MySqlClient;
using MySql.Data;
namespace csharpdatabasefinal
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("C#: Connect to MySQL Database using localhost." + Environment.NewLine);
string connectionString = "server=localhost;user=csharptest;database=csharptest;port=3306;password=123";
MySqlConnection conn = new MySqlConnection(connectionString);
try
{
conn.Open();
Console.WriteLine("Connection is " + conn.State.ToString() + Environment.NewLine);
conn.Close();
Console.WriteLine("Connection is " + conn.State.ToString() + Environment.NewLine);
}catch(MySql.Data.MySqlClient.MySqlException ex)
{
Console.WriteLine("Error: " + ex.Message.ToString());
}
Console.WriteLine("Press any key to exit..");
Console.Read();
}
}
}
And this is the Error I get, I guess it has something to do with the References but im not really sure..
I added as reference "MySql.Data.dll" & "System.Security.Permissions.dll".
I added the Systen.Security.Permission.dll because in a previous error he asked for it.
And this is the Error I get:
Click me!(Error-Image)
Here the full Error Code:
System.TypeInitializationException
HResult=0x80131534
Message=The type initializer for 'MySql.Data.MySqlClient.Replication.ReplicationManager' threw an exception.
Source=MySql.Data
StackTrace:
at MySql.Data.MySqlClient.Replication.ReplicationManager.IsReplicationGroup(String groupName)
at MySql.Data.MySqlClient.MySqlConnection.Open()
at csharpdatabasefinal.Program.Main(String[] args) in C:\Users\anonym\source\repos\csharpdatabasefinal\csharpdatabasefinal\Program.cs:line 19
Inner Exception 1:
FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.

Enable "native code debugging" in Project -> Properties -> Debug
If that does't work, try adding the MySQL dll via nuget:
Install-Package MySql.Data -Version 8.0.20

Related

System.TypeInitializationException error on opening mysql connection

I just recently started experiencing with ASP.net by using the MVC pattern.
What im trying to do is create a login form with users from a Local phpmyadmin database, now my problem is that when im trying to open the MySqlConnection _mscCon.Open(); it gives me an error:
System.TypeInitializationException: 'The type initializer for 'MySql.Data.MySqlClient.Replication.ReplicationManager' threw an exception.'
FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.
Now im not understanding what this error means and how i am able to fix it, i tried changing the port of my WAMPSERVER and the port of my ASP.NET Localhost and this doesnt seem to work.
private MySqlConnection _mscCon = new MySqlConnection("Server=localhost;Port=3306;Database=asptest;Uid=root;Pwd=;");
public bool CheckCredentials(string username, string password)
{
_mscCon.Open();
if (_mscCon.State == ConnectionState.Open)
{
MySqlCommand mscCommand = new MySqlCommand("SELECT ID FROM users WHERE Username = " + username + " AND Password = " + password + ";", _mscCon);
using (MySqlDataReader reader = mscCommand.ExecuteReader())
{
if (reader.HasRows)
{
return true;
}
}
}
return false;
}
Does anyone know what i might be missing?
This issue may be resolved if you install MySQL Connector/NET (choose your version)
https://dev.mysql.com/downloads/connector/net/8.0.html

Unhandled Exception: C# Sqlite

I just started to use SQLite. Doesn't seem to look like MySQL and SQL Server and MS Access that I use. I sought for several information online, nothing I could really find as well I decided to post here.
It connects well, and the libraries are present in the folder, but when I try to insert into the database, it throws an exception to the console.
My code looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.SQLite;
namespace sqliteInsert
{
class Program
{
static void Main(string[] args)
{
string constring = "Data Source=C:\\Users\\DornellPC\\Desktop\\people_db.db;Version=3;New=False;Compress=True;";
using (SQLiteConnection con = new SQLiteConnection(constring))
{
try
{
string sql = "insert into people_data (first_name,last_name,tel,email) values ('Jack','Darwin','0966358936','j_darwin#fsmail.net')";
con.Open();
Console.WriteLine("Connection open!");
using (SQLiteCommand cmd = new SQLiteCommand(sql,con))
{
cmd.ExecuteNonQuery();
Console.WriteLine("Success!");
Console.ReadLine();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}
and no information has been inserted into the database as it throws this exception:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or ass embly 'System.Data.SQLite, Version=1.0.105.2, Culture=neutral, PublicKeyToken=db 937bc2d44ff139' or one of its dependencies. The system cannot find the file specified.
at sqliteInsert.Program.Main(String[] args)

Can't connect to MySQL Database with C#; Error state: 18

Below is the code I used to try to connect to a remote MySQL server. I've connected to this server with a Python script using pymysql but I am unable to connect to it with Visual Studios. The application is "fully trusted" in visual studios. When I run this, I get System.InvalidOperationException stating an internal connection fatal error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine("Hello, world!!");
SqlConnection myConnection = new SqlConnection("User ID={UserID};" +
"password={Password};Data Source=sql9.freesqldatabase.com, 3306;" +
"Trusted_Connection=yes;" +
"Initial Catalog=sql9159612; " +
"connection timeout=30");
try
{
myConnection.Open();
Console.WriteLine("Opened connection");
}
catch(Exception e)
{
Console.WriteLine("Can't open connection");
Console.WriteLine(e.ToString());
}
}
}
}
First, you'll want to download the MySql.Data package from Nuget.
Then take out ",3306" from the Data Source, and also remove the Trusted_Connection element...
var myConnection = new MySqlConnection("User ID={UserId};" +
"password={Password};Data Source=sql9.freesqldatabase.com;" +
"Initial Catalog={database}; " +
"connection timeout=30");
(I remove some of the sensitive information, fyi...)

Issue with C# reading table on SQL Anywhere DB

using System;
using System.Data.OleDb;
using System.Diagnostics;
namespace PullData
{
class Program
{
static void Main(string[] args)
{
OleDbConnection connLocal = new OleDbConnection("Provider=SAOLEDB.10;Data Source=dental;Persist Security Info=True;User ID=dba;PWD=sql;Location=1.2.3.4");
OleDbCommand cmdLocal = new OleDbCommand("SELECT tran_num, amount, tran_date FROM transactions", connLocal);
try
{
connLocal.Open();
}catch (Exception connerr) { Debug.WriteLine(connerr.Message);}
OleDbDataReader readLocal = cmdLocal.ExecuteReader();
while (readLocal.Read())
{
Console.WriteLine(readLocal.GetString(0), readLocal.GetString(1), readLocal.GetString(2));
}
readLocal.Close();
connLocal.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
Above is the code I am attempting to run in Visual Studio 2015, I'm trying to connect to an old SQL Anywhere 10 DB, the connection string is directly from VS2015's Database Explorer that is connected and viewing tables (with the exception of my adding the PWD). This is just a stepping stone to view the table contents so I can later have the query written to a CSV or text.
The error I'm receiving when attempting to debug/run is:
An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.dll
Additional information: Specified cast is not valid.
Which points to:
Console.WriteLine(readLocal.GetString(0), readLocal.GetString(1), readLocal.GetString(2));
Seems like it's not recognizing the reader. Anyone have any advice? Thanks!

Error Opening Access Database with C# Application

I'm updating a C# (.NET 3.5) application to interact with an Access database, but I keep getting this error:
ERROR: Unrecognized database format
This is the code I'm using to open a connection to the database:
String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=" + filePath;
try
{
this.conn = new OleDbConnection(connectionString);
this.conn.Open();
}
catch (Exception e)
{
Console.WriteLine("ERROR: " + e.Message);
Console.WriteLine(e.ToString());
}
I know that the file path is correct. I suspect that the Provider=Microsoft.Jet.OLEDB.4.0; is incorrect. How do I find out what the database format is? I did not make the database in question, but I do have read-access to it. Thanks.
You must add Data Source , user/password parametters . You can see http://connectionstrings.com/access

Categories