How do I connect to a MariaDB MySQL Database with ASP.NET in C# and VB.NET? Print

  • 2

Here is an example code for connecting to a MySQL database using ASP.NET and C#:

csharp
using System; using MySql.Data.MySqlClient; namespace MyNamespace { public class MySQLConnection { public MySqlConnection GetConnection() { string connectionString = "Server=myServerAddress;Database=myDatabase;Uid=myUsername;Pwd=myPassword;"; MySqlConnection connection = new MySqlConnection(connectionString); try { connection.Open(); Console.WriteLine("Connection successful!"); } catch (Exception ex) { Console.WriteLine("Error connecting to database: " + ex.Message); } return connection; } } }

Replace the placeholders myServerAddress, myDatabase, myUsername, and myPassword with your own MySQL server address, database name, username, and password respectively. This code creates a MySqlConnection object and attempts to open the connection. If the connection is successful, it will print "Connection successful!" to the console. If not, it will print an error message with the exception message. You can then use the MySqlConnection object to execute SQL commands and retrieve data from the database.

 

 

Here's an example code on how to connect to a MySQL database with ASP.NET using VB.NET:

vbnet
Imports MySql.Data.MySqlClient Public Class MySqlConnectionHelper Public Shared Function GetConnectionString() As String Dim server As String = "localhost" Dim database As String = "mydatabase" Dim user As String = "myuser" Dim password As String = "mypassword" Dim connectionString As String = "server=" & server & ";user id=" & user & ";password=" & password & ";database=" & database Return connectionString End Function Public Shared Function ExecuteQuery(query As String) As DataTable Dim connectionString As String = GetConnectionString() Dim dataTable As New DataTable() Using connection As New MySqlConnection(connectionString) connection.Open() Using command As New MySqlCommand(query, connection) Dim dataAdapter As New MySqlDataAdapter(command) dataAdapter.Fill(dataTable) End Using connection.Close() End Using Return dataTable End Function End Class

To use this class, you can call the ExecuteQuery function and pass in your SQL query. The function will return a DataTable with the results of the query.

Here's an example usage:

vbnet
Dim query As String = "SELECT * FROM users" Dim dataTable As DataTable = MySqlConnectionHelper.ExecuteQuery(query) For Each row As DataRow In dataTable.Rows ' Do something with each row Next
 

Was this answer helpful?

« Back