C# MySql Exception Thrown - c#

I'm trying to create a login and register forum and store all of the usernames and passwords in a MySQL database. I found a free MySQL hosting site and instead of just having your databases listed I have the user name listed and then that users tables. I'm not really sure if doing it through a user is causing the problem or not. Here is the error I get.
Project Royal.vshost.exe Error: 0 : Unable to connect to any of the specified MySQL hosts.
Exception thrown: 'MySql.Data.MySqlClient.MySqlException' in MySql.Data.dll
And also here is my code.
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 MySql.Data.MySqlClient;
namespace Project_Royal
{
public partial class Login : Form
{
private MySqlConnection conn;
private string server;
private string database;
private string uid;
private string password;
public Login()
{
server = "82.197.130.215";
database = "2190559_users";
uid = "2190559_users";
password = "";
string connString;
connString = $"SERVER={server};DATABASE={database};UID={uid};PASSWORD={password};";
conn = new MySqlConnection(connString);
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string user = textBox1.Text;
string pass = textBox2.Text;
if (Register(user, pass))
{
MessageBox.Show($"User {user} has been created!");
}
else
{
MessageBox.Show($"User {user} has not been created!");
}
}
private void button1_Click(object sender, EventArgs e)
{
string user = textBox1.Text;
string pass = textBox2.Text;
if (IsLogin(user, pass))
{
MessageBox.Show($"Welcome {user}!");
}
else
{
MessageBox.Show($"{user} does not exist or password is incorrect!");
}
}
public bool Register(string user, string pass)
{
string query = $"INSERT INTO Whitelisted (id, username, password) VALUE ('', '{user}', '{pass}');";
try
{
if (OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, conn);
try
{
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
return false;
}
}
else
{
conn.Close();
return false;
}
}
catch (Exception ex)
{
conn.Close();
return false;
}
}
public bool IsLogin(string user, string pass)
{
string query = $"SELECT * FROM Whitelisted WHERE username = '{user}' AND password = '{pass}');";
try
{
if (OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
reader.Close();
conn.Close();
return true;
}
else
{
reader.Close();
conn.Close();
return false;
}
}
else
{
conn.Close();
return false;
}
}
catch (Exception ex)
{
conn.Close();
return false;
}
}
private bool OpenConnection()
{
try
{
conn.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Connection to server failed!");
break;
case 1045:
MessageBox.Show("Server username or password is incorrect!");
break;
}
return false;
}
}
}
}

Related

Can't insert data into database with ASP.NET/C#

I've been trying to create a simple registration page and connecting it with database, but when I click on the button to register a new user it returns the following message:
at MappingDatabase.Connection () [0x00016] in <bea5b5103c9f4cfba42ba460a8c4180f>:0
at PersonDatabase.Insert (Person p) [0x00002] in <bea5b5103c9f4cfba42ba460a8c4180f>:0
Here's the code:
using System.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
public static class MappingDatabase
{
public static IDbConnection Connection()
{
MySqlConnection connection = new MySqlConnection(ConfigurationManager.AppSettings["databaseConnection"]);
connection.Open();
return connection;
}
public static IDbCommand Command(string sqlQuery, IDbConnection connection)
{
IDbCommand runCommand = connection.CreateCommand();
runCommand.CommandText = sqlQuery;
return runCommand;
}
public static IDbDataAdapter Adapter(IDbCommand command)
{
IDbDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = command;
return adapter;
}
public static IDbDataParameter Parameter(string parameterName, object value)
{
return new MySqlParameter(parameterName, value);
}
}
public static class PersonDatabase
{
public static int Insert(Person p)
{
try
{
IDbConnection dbConnection = MappingDatabase.Connection();
IDbCommand dbCommand;
string sql = #"INSERT INTO PER_PERSON VALUES(0, ?name, ?email, ?password);";
dbCommand = MappingDatabase.Command(sql, dbConnection);
dbCommand.Parameters.Add(MappingDatabase.Parameter("?name", p.Name));
dbCommand.Parameters.Add(MappingDatabase.Parameter("?email", p.Email));
dbCommand.Parameters.Add(MappingDatabase.Parameter("?password", p.Password));
dbCommand.ExecuteNonQuery();
dbConnection.Close();
dbCommand.Dispose();
dbConnection.Dispose();
return 0;
}
catch(Exception e)
{
Console.WriteLine(e.StackTrace);
return -1;
}
}
}
Here's the repository on GitHub
It worked before on a computer running Windows 10.
Could it be a problem with the connector file (MySql.Data.dll)? How can I fix that?
Note: I use Linux Ubuntu 20.04
You can fix this error by downloading the right connector in the hyperlink below:
Download Connector

Connect to remote DB [duplicate]

New to C# programming, I'd like to be able to access MySQL Databases.
I know MySQL connector/NET and MySQL for Visual Studio are required for C# development.
Do I need to install them into my app?
Is it possible I can just release the connector DLL with the program?
Update:
Are both of them required for the end-user or just the connector?
Is there anything else they would need?
Install Oracle's MySql.Data NuGet package.
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Data
{
public class DBConnection
{
private DBConnection()
{
}
public string Server { get; set; }
public string DatabaseName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
private MySqlConnection Connection { get; set;}
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if (_instance == null)
_instance = new DBConnection();
return _instance;
}
public bool IsConnect()
{
if (Connection == null)
{
if (String.IsNullOrEmpty(databaseName))
return false;
string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
Connection = new MySqlConnection(connstring);
Connection.Open();
}
return true;
}
public void Close()
{
Connection.Close();
}
}
}
Example:
var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
//suppose col0 and col1 are defined as VARCHAR in the DB
string query = "SELECT col0,col1 FROM YourTable";
var cmd = new MySqlCommand(query, dbCon.Connection);
var reader = cmd.ExecuteReader();
while(reader.Read())
{
string someStringFromColumnZero = reader.GetString(0);
string someStringFromColumnOne = reader.GetString(1);
Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
}
dbCon.Close();
}
You can use Package Manager to add it as a package and it is the easiest way. You don't need anything else to work with a MySQL database.
Or you can run this command in Package Manager Console:
PM> Install-Package MySql.Data
NuGet MySql.Data
You must to download MySQLConnection NET from here.
Then you need add MySql.Data.DLL to MSVisualStudio like this:
Open menu project
Add
Reference
Browse to C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.12\Assemblies\v4.5.2
Add MySql.Data.dll
If you want to know more visit: enter link description here
To use in the code you must import the library:
using MySql.Data.MySqlClient;
An example with connectio to Mysql database (NO SSL MODE) by means of Click event:
using System;
using System.Windows;
using MySql.Data.MySqlClient;
namespace Deportes_WPF
{
public partial class Login : Window
{
private MySqlConnection connection;
private string server;
private string database;
private string user;
private string password;
private string port;
private string connectionString;
private string sslM;
public Login()
{
InitializeComponent();
server = "server_name";
database = "database_name";
user = "user_id";
password = "password";
port = "3306";
sslM = "none";
connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);
connection = new MySqlConnection(connectionString);
}
private void conexion()
{
try
{
connection.Open();
MessageBox.Show("successful connection");
connection.Close();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message + connectionString);
}
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
conexion();
}
}
}
Looking at the code below, I tried it and found:
Instead of writing DBCon = DBConnection.Instance(); you should put DBConnection DBCon - new DBConnection(); (That worked for me)
and instead of MySqlComman cmd = new MySqlComman(query, DBCon.GetConnection()); you should put MySqlCommand cmd = new MySqlCommand(query, DBCon.GetConnection()); (it's missing the d)
Another library to consider is MySqlConnector, https://mysqlconnector.net/. Mysql.Data is under a GPL license, whereas MySqlConnector is MIT.
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "U`enter code here`ID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}

CS7069 C# Reference to type 'Component' claims it is defined in 'System', but it could not be found

I am building winForm application,
and i try to make a connection function for mssql Server
but SqlConnection open/close always show
"CS7069 C# Reference to type 'Component' claims it is defined in 'System', but it could not be found"
how could I fix this issue?
public class SQLAPI
{
SqlConnection cn;
Boolean openConnect()
{
bool rtn = false;
try
{
cn = new SqlConnection("server=localhost;database=testDB;UID=ad;PWD=1234");
cn.Open();
}
catch (Exception e)
{
}
return rtn;
}
void closeConnect()
{
try {
cn.Close();
}
catch (Exception e)
{ }
}
}

Test SQL connection from C# ASP WEB application

I am a newbie to C# programming, and am trying to get a REST API working. For some reason it is not connecting from iOS, and I wanted to test the SQL connection in order to troubleshoot the connection from that point first. How can I go about testing it? I tried to figure it out, but my understanding of C# is still quite limited.
Here is the code below:
Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<connectionStrings>
<add name="conString" connectionstring="Data Source=10.0.0.1;Initial Catalog=DBName;Password=Password;User ID=UserID;Integrated Security=True;" providername="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
IServiceAPI.CS
using System.Data;
namespace RESTWebAPI
{
// This interface declare the methods need to be implement.
public interface IServiceAPI
{
void CreateNewAccount(string username, string password);
DataTable Getmembers(string username);
bool UserAuthentication(string username, string passsword);
}
}
ServiceAPI.CS
using System;
using System.Data;
using System.Data.SqlClient;
using Web.config;
namespace RESTWebAPI
{
public static bool IsServerConnected(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
return true;
}
catch (SqlException)
{
return false;
}
}
}
public class ServiceAPI : IServiceAPI
{
SqlConnection dbConnection;
public ServiceAPI()
{
dbConnection = DBConnect.getConnection();
}
public void CreateNewAccount(string username, string password)
{
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "INSERT INTO members VALUES ('" + username + "','" + password + "');";
SqlCommand command = new SqlCommand(query, dbConnection);
command.ExecuteNonQuery();
dbConnection.Close();
}
public DataTable Getmembers(string username)
{
DataTable membersTable = new DataTable();
membersTable.Columns.Add(new DataColumn("username", typeof(String)));
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "SELECT username FROM members WHERE username='" + username + "';";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
membersTable.Rows.Add(reader["username"]);
}
}
reader.Close();
dbConnection.Close();
return membersTable;
}
public bool UserAuthentication(string username, string passsword)
{
bool auth = false;
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "SELECT id FROM members WHERE username='" + username + "' AND password='" + passsword + "';";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
auth = true;
}
reader.Close();
dbConnection.Close();
return auth;
}
}
}
DBConnect.cs
using System.Configuration;
using System.Data.SqlClient;
namespace RESTWebAPI
{
// This class is used to connect to sql server database
public class DBConnect
{
private static SqlConnection NewCon;
private static string conStr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
public static SqlConnection getConnection()
{
NewCon = new SqlConnection(conStr);
return NewCon;
}
public DBConnect()
{
}
}
}
Handler1.ashx.cs
using JsonServices;
using JsonServices.Web;
namespace RESTWebAPI
{
public class Handler1 : JsonHandler
{
public Handler1()
{
this.service.Name = "RESTWebAPI";
this.service.Description = "JSON API for mobile application";
InterfaceConfiguration IConfig = new InterfaceConfiguration("RestAPI", typeof(IServiceAPI), typeof(ServiceAPI));
this.service.Interfaces.Add(IConfig);
}
}
}
your IsServerConnected method is static, Note: if connection be open and you try to open it then for sure you'll get an exception, I mean for an open connection connection.Open(); raises an exception, so you need a finally block to close the connection after opening it, if the IsServerConnected method is only for checking the connection:
public static bool IsServerConnected(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
return true;
}
catch (SqlException)
{
return false;
}
finally
{
try
{
connection.Close();
}
catch (Exception ex)
{
}
}
}
}

ServiceStack OrmLite update

Below Code works fine.
public static void UpdateCategory(Category category) {
var dbFactory = new OrmLiteConnectionFactory(connString, SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection()) {
try{
db.Update<Category>(category);
}
catch (Exception e) {
throw new Exception(string.Format("Error within {0}", e.Message));
}
}
}
Below code does not?
public static int UpdateRowInTable<T>(object value) {
var dbFactory = new OrmLiteConnectionFactory(connString, SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection()) {
try {
result = db.Update<T>(value);
}
catch (Exception e) {
throw new Exception(string.Format("Error within {0}", e.Message));
}
}
}
thanks

Categories