Connect to remote DB [duplicate] - c#

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

Related

This property cannot be set after a connection has been opened

I'm trying to connect to Oracle through .NET Core following this docs:
https://docs.oracle.com/en/database/oracle/oracle-data-access-components/19.3/odpnt/InstallCoreConfiguration.html#GUID-24C963AE-F20B-44B5-800C-594CA06BD24B
But I'm facing this error:
This property cannot be set after a connection has been opened
System.InvalidOperationException: This property cannot be set after a
connection has been opened at
Oracle.ManagedDataAccess.Client.OracleDataSourceCollection.Add(String
tnsName, String tnsDescriptor) at
Infrastructure.Persistence.Factory.ConnectionFactory.SetupOracleConnection()
in
C:\Users\WINDOWS\RiderProjects\TicketsAPI\Infrastructure\Persistence\Factory\ConnectionFactory.cs:line
22
I don't have clue why this is happening, there's my ConnectionFactory:
using System.Data;
using Microsoft.Extensions.Logging;
using Oracle.ManagedDataAccess.Client;
namespace Infrastructure.Persistence.Factory;
public class ConnectionFactory : IConnectionFactory
{
private const string TnsName = "ORCL";
private readonly ILogger<ConnectionFactory> _logger;
public ConnectionFactory(ILogger<ConnectionFactory> logger)
{
_logger = logger;
}
public IDbConnection? Connection => SetupOracleConnection();
private OracleConnection? SetupOracleConnection()
{
OracleConfiguration.OracleDataSources.Add(TnsName,
"(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = DESKTOP-FP8GDE4)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = orcl)))"); // <-- This is the line 22 mentioned in the StackTrace
. . . //Some configs that are in the doc file.
OracleConnection oracleConnection = null!;
try
{
oracleConnection = new OracleConnection($"user id=kevinadmin; password=1234; data source={TnsName}");
oracleConnection.Open();
return oracleConnection;
}
catch (Exception e)
{
_logger.LogError("An error occurred while trying to connect to database {EMessage}", e.Message);
return null;
}
finally
{
oracleConnection?.Close();
}
}
}
[edit:
I may have misunderstood the issue. If the exception is happening on second and subsequent calls to Connection, then this answer might apply]
By declaring your property like
public IDbConnection? Connection => SetupOracleConnection();
you're instructing the { get; } (which is what the => is sugar for) to execute the SetupOracleConnection() every time it is accessed.
You should try to encapsulate that into a singleton instance.
private IDbConnection? _connection = null;
public IDbConnection? Connection => _connection ?? ( _connection = SetupOracleConnection());

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

MySql Connection failed to connect database

I cannot connect to a MySQL database, I am using xampp.
It says this error from the code simple error: "Connection to the server failed!"
namespace Mysql
{
public partial class Form1 : Form
{
private MySqlConnection conn;
private string server;
private string database;
private string uid;
private string password;
public Form1()
{
server = "localhost";
database = "tut1";
uid = "root";
password = "";
string connString;
connString = $"SERVER={server};DATABASE={database};UID={uid};PASSWORD={password};";
conn = new MySqlConnection(connString);
InitializeComponent();
}
OK, so I got it working. I fixed it adding SslMode=none.
Your connection string should be like below
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
below is the structure
server={0};user id={1};password={2};database={3};
You need to specify password as Pwd

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)
{
}
}
}
}

Set Entity Framework connection string at runtime

I have generated entity model from AdventureWorks database; now I want to delete the connection string in app.config and set it at runtime. In the Model1.Context.cs file I have chnaged the constructor to
public AdventureWorksEntities(string str)
: base("name=AdventureWorksEntities")
{
this.Database.Connection.ConnectionString = str;
}
and in the program.cs file
EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
ecsb.Metadata = #"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
ecsb.Provider = #"System.Data.SqlClient";
ecsb.ProviderConnectionString =
#"data source=.\sqlexpress;initial catalog=AdventureWorks;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";
using (var ent = new AdventureWorksEntities(ecsb.ConnectionString))
{
Console.WriteLine(ent.Database.Connection.ConnectionString);
var add = ent.Addresses;
foreach (var ad in add)
{
Console.WriteLine(ad.City);
}
}
Console.ReadKey();
Now it says metadata keyword not found. How to set connectionstring for entityframework at runtime?
This is an example using standard .aspx login information to set the UserID and Password information in the connection string. No connection string settings are stored in the web.config or app.config file.
Modify the Model.Designer.cs page as follows:
public partial class Entities : ObjectContext
{
#region Constructors
public static string getConStrSQL(string UID,string PWD)
{
string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = "res://*",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
{
InitialCatalog = "your_database_name",
DataSource = "your_server",
IntegratedSecurity = false,
UserID = UID,
Password = PWD,
}.ConnectionString
}.ConnectionString;
return connectionString;
}
/// <summary>
/// Initialize a new Entities object.
/// </summary>
public Entities(string UID,string PWD)
: base(getConStrSQL(UID,PWD), "Entities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
......
Then in your code behind page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Mvc;
using System.Web.Security;
public partial class views_html_form : System.Web.UI.Page
{
public void Page_Load()
{
if (currentUser() == null)
{
HttpContext.Current.Response.Redirect("~/login.aspx");
}
}
public static MembershipUser currentUser()
{
MembershipUser currentUser = Membership.GetUser();
return currentUser;
}
public static string UID()
{
string UID = currentUser().UserName;
return UID;
}
public static string PWD()
{
string PWD = currentUser().GetPassword();
return PWD;
}
public static void SelectRecord()
{
YourModel.Entities db = new YourModel.Entities(UID(), PWD());
var query = from rows in db.Table_Name orderby rows.ID select rows;
.....
That's it. No messing around with .config files. Alternatively you could send a database name, for example, as a parameter in the same way.
I'd go with something like:
public AdventureWorksEntities(string server, string databaseName, string user, string password)
:base(new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = "res://*",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
{
InitialCatalog = databaseName,
DataSource = server,
IntegratedSecurity = false,
UserID = user,
Password = password,
}.ConnectionString
}.ConnectionString)
{
}

Categories