csharp mysql compile error CS0246 under powershell - c#

I am attempting to compile a simple C# program to do a select on one of the tables in the MySQL database on my windows 10 laptop. When I attempt to compile the code under Developer PowerShell for VS 2019 using the following command:
csc mysql1.cs
I get the error message error CS0246: The type or namespace name 'MySql' could not be found
I checked under the directory C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.18\Assemblies\v4.5.2 and I did indeed have the file MySql.Data.dll
All the articles I found with google stated that I had to "add a reference" to my project. I do not have a project, this is just a command line compile.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is a MySQL Test");
string mysql_info = "Persist Security Info=False;server=localhost;database=myschema;uid=root;password=mypassword";
MySql.Data.MySqlClient.MySqlConnection dbConn =
new MySql.Data.MySqlClient.MySqlConnection(mysql_info);
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT user_id from hockey_users WHERE username ='someone'";
try
{
dbConn.Open();
} catch (Exception erro) {
MessageBox.Show("Error" + erro);
this.Close();
}
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
idnumber = reader.ToString();
Console.WriteLine("id = " + idnumber);
}
}
}
}

Related

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

How do I access MySql database in C#.NET with WPF? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
Please advise me. I am trying to develop Windows Application in WPF with Mysql server database.
Which approach I have to use to create connection establish on the Mysql database?
1) Entity Framework
OR
2) ADO.NET
OR
3) Other one
The Admin computer need to install mysql database on his computer and then access the mysql database to another (10 or more) client systems which are under network connected.
Here, just one MySql database inside admin computer only. And all other client machines are accessing MySql database by admin's computer IP address. The IP connection string is like this:-
#"Data Source=10.0.0.101
One of other matter is, the customer demanding that, when installing .exe file on client machine, then should have to automatically install mysql server database (ie, xampp or other ect..) also.
How can I do this?
I have tried, ADO.NET C# instead EF to connect mysql for wpf windows application. like that :-
public void AddUserList( UserSetUp user)
{
dbConnection.Open();
string query = "INSERT INTO Tble_UserSetUp (FirstName, SurName, Email, PhoneNumber, UserName, Password,Computer_Name,IP_Address,CreatedBy, CreatedDate,IsActive,Function,Department) VALUES (#FirstName, #SurName, #Email, #PhoneNumber, #UserName, #Password,#Computer_Name,#IP_Address,#CreatedBy, #CreatedDate,#IsActive,#Function,#Department)";
MySqlCommand insertSQL = new MySqlCommand(query, (MySqlConnection)dbConnection);
insertSQL.Parameters.AddWithValue("#FirstName", user.FirstName);
insertSQL.Parameters.AddWithValue("#SurName", user.SurName);
insertSQL.Parameters.AddWithValue("#Email", user.Email);
insertSQL.Parameters.AddWithValue("#PhoneNumber", user.PhoneNumber);
insertSQL.Parameters.AddWithValue("#UserName", Encrypt(user.UserName));
insertSQL.Parameters.AddWithValue("#Password", Encrypt(user.Password));
insertSQL.Parameters.AddWithValue("#Computer_Name", user.Computer_Name);
insertSQL.Parameters.AddWithValue("#IP_Address", user.IP_Address);
insertSQL.Parameters.AddWithValue("#CreatedBy", user.CreatedBy);
insertSQL.Parameters.AddWithValue("#CreatedDate", user.CreatedDate);
insertSQL.Parameters.AddWithValue("#IsActive", user.IsActive);
insertSQL.Parameters.AddWithValue("#Function", user.Function);
insertSQL.Parameters.AddWithValue("#Department", user.Department);
try
{
insertSQL.ExecuteNonQuery();
dbConnection.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
Is it a bad idea instead of use Entity Framework or another one?
public partial class MainWindow : Window
{
/*mysql
*
* 1. add nuget mysql.data.dll(desktop application)
* 2. using MySql.Data.MySqlClient;
* 3. code like bellow , you can try
*/
private StringBuilder sb = new StringBuilder();
public MainWindow()
{
InitializeComponent();
mysql();
tbx.Text = sb.ToString();
}
private void mysql()
{
try
{
var connstr = "Server=localhost;Uid=root;Pwd=123456;database=world";
using (var conn = new MySqlConnection(connstr))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from city where countryCode= #ID";
cmd.Parameters.AddWithValue("#ID", "100");
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var ii = reader.FieldCount;
for (int i = 0; i < ii; i++)
{
if (reader[i] is DBNull)
sb.AppendLine("null");
else
sb.AppendLine(reader[i].ToString());
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Reference: Official MySQL documentation - Introduction to Connector/NET Programming
Step 0: Setup MySql and Create a database
Step 1: Create WPF Project
Step 2: Install MySql.Data package using Nuget package manager
(Visual Studio) Project> (click) Manage NuGet packages
Select Browse tab> search Mysql.data > Select Mysql.data package> Install
Step 3: In my case I created the connection within MainWindow.xaml.cs file.
To consume MySql.Data and MySql.Data.MySqlClient
using MySql.Data;
using MySql.Data.MySqlClient;
Full Code (relevent to the question): MainWindow.xaml.cs file
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace EAppartments
{
public partial class MainWindow : Window
{
string connStr = "server=localhost;user=root;database=YourDBName;password=yourpassword";
//Connect to MySql when app starts
//you can use OnStartUp event as well
public MainWindow()
{
InitializeComponent();
connectToMySql();
}
private void connectToMySql()
{
MySqlConnection conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
//close connection if you want
conn.Close();
Console.WriteLine("Done.");
}
}
}
Useful resources:
Execute MySql commands using WPF app
Lifecycle of WPF application

System.Data.OleDb.OleDbException' occurred in System.Data.dll

Hey Members i am new to C# Language and Visual Studio Platform recently i am learning how to connect access Database with visual Studio and first time with same code i have connected with database but after some time when i compiled again then there is error given in Title.
why this is happening ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Clinic_Management_System
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users
\Hassan Gillani\Documents\Clinic Management System.accdb; Persist Security Info = False; ";
connection.Open();
label1.Text = "Connected to Clinic Management System Database";
connection.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error " + exp);
}
}
}
}
please visit given like to view screen short
http://s33.postimg.org/5ltm4dtnj/Error.png
Using the verbatim character (#) and splitting your path in the middle in not a good idea.
Spaces counts in paths so the filename used for your connection is
C:\Users \Hassan Gillani\Documents\Clinic Management System.accdb;
If you try to use File.Exists on this string you get false as result.
Do not split your connection string in the middle of the path
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\Hassan Gillani\Documents\Clinic Management System.accdb;
Persist Security Info = False; ";

Is this the correct way for connecting database (.mdf file) to visual studio project?

for this i am not getting any output thought there is not any error or warning... i guess the problem is with connection string but not sure, is it?? i have created a database name RV(.mdf file) in SQL server data tool and connected it to this project in visual studio.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Configuration;
namespace student_TableConnectTry1
{
class Program
{
static void Main(string[] args)
{
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =#"Data Source=(local);Integrated Security=SSPI;" +"Initial Catalog=RV";
cn.Open();
string strSQL = "Select * From student";
SqlCommand myCommand = new SqlCommand(strSQL, cn);
using (SqlDataReader myDataReader = myCommand.ExecuteReader())
{
// Loop over the results.
while (myDataReader.Read())
{
Console.WriteLine("-> usn: {0}, name: {1}.",
myDataReader["usn"].ToString(),
myDataReader["name"].ToString()
);
}
}
Console.ReadLine();
}
}
}
}
You can use following connection string and try:
Integrated Security=SSPI;Persist Security Info=False;User ID=youruserid;Initial Catalog=databasename;Data Source=.\SQLEXPRESS
Also see the following link for connectionstring:
http://www.connectionstrings.com/sql-server/
I hope it will help you. :)
Let me know if it does not help you.

Categories