This did not worked when I ran the program!
using MySql.Data;
using MySql.Data.MySqlClient;
namespace MySQL
{
class SqlConnection
{
public SqlConnection() { }
~SqlConnection() { }
private string strConnection = "Server=localhost;Database=database;Port=3306;User ID=root;Password=";
private MySqlConnection connection;
public void OpenConnection()
{
connection = new MySqlConnection();
connection.Open();
}
public void CloseConnection()
{
connection.Close();
connection.Dispose();
}
public string StrConnection
{
set
{
StrConnection = value;
}
get
{
return StrConnection;
}
}
}
}
but it is not working!
ERROR : host 'xxx' is not allowed to connect to this MariaDB sever!
You don't use the connection string property strConnection, when you initialize your connection. Try:
public void OpenConnection()
{
connection = new MySqlConnection(strConnection);
connection.Open();
}
Related
I am trying to connect my xamarin mobile app to mysql but it always throws this exception.
I have installed the MySQL Connector/NET through Package Manager Console window in visual studio Install-Package MySql.Data.
This error shows up after running successfully the project on line connection.open().
Can someone explain to me the reason or help me solve it.
here's my code:
using MySql.Data.MySqlClient;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace tpExam
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class login : ContentPage
{
public login()
{
InitializeComponent();
}
private void ShowToast(string message)
{
DependencyService.Get<IToastNotification>().Show(message);
}
private void Login(Object sender,EventArgs e)
{
MySqlConnection connection = new MySqlConnection("Server=localhost;Database=tpexam;Uid=root;Pwd=;");
string username = txtUsername.Text;
string password = txtpassword.Text;
using(connection)
{
try
{
connection.Open();
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
}
string query= $"SELECT * FROM user WHERE username='{username}' AND password='{password}'";
using(MySqlCommand command = new MySqlCommand(query,connection))
{
using(MySqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
// A match was found, so check whether the user is an admin or not
Navigation.PushAsync(new HomePage());
}
else
{
ShowToast("Invalid username or password");
}
}
}
}
}
private void TapGestureRecognizer_Tapped(object sender,EventArgs e)
{
Navigation.PushAsync(new RegisterPage());
}
}
}
I want to make button enabled, depending on what data is in SQL table. I made table with boolean type column and now I want WPF to read it and make button enabled or disabled. I made class for connection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Windows;
using System.Data.SqlClient;
using System.Configuration;
namespace WpfCalendar.Classes
{
class SQLconnection
{
public static string GetConnectionStrings()
{
string strConString = ConfigurationManager.ConnectionStrings["conString"].ToString();
return strConString;
}
public static string sql;
public static SqlConnection con = new SqlConnection();
public static SqlCommand cmd = new SqlCommand("",con);
public static SqlDataReader rd;
public static DataTable dt;
public static SqlDataAdapter da;
public static void openConnection()
{
try
{
if (con.State == ConnectionState.Closed)
{
con.ConnectionString = GetConnectionStrings();
con.Open();
}
}
catch (Exception ex)
{
MessageBox.Show("Brak połaczenia" + Environment.NewLine + ex.Message.ToString(), "C# WPF connect to SQL server", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public static void closeConnection()
{
try
{
if(con.State == ConnectionState.Open)
{
con.Close();
}
}
catch(Exception)
{
}
}
}
}
And my window xaml.cs
public partial class Kalendarz : Window
{
public Kalendarz()
{
InitializeComponent();
}
private void Sprawdzanko1(object sender, RoutedEventArgs e)
{
DateTime dt = DateTime.Now;
bool klikniente;
SQLconnection.openConnection();
SQLconnection.cmd.CommandText = SQLconnection.sql;
SQLconnection.sql = "Select [Otwarte] FROM Okienka WHERE Dzien LIKE '1';";
SQLconnection.cmd.CommandType = CommandType.Text;
SQLconnection.da = new SqlDataAdapter(SQLconnection.cmd);
klikniente = (bool)SQLconnection.cmd.ExecuteScalar();
if (klikniente == true && dt.Day == 1 && dt.Month == 12)
{
b1.IsEnabled = true;
}
else
{
b1.IsEnabled = false;
}
SQLconnection.closeConnection();
}
I'm making a WPF advent calendar so the idea is to check if the button was clicked before and if date is correct. But the buttons don't react an I'm pretty sure the code isn't even executed...
Ok so I think I got it. It works so I'm fine with it :D
private void Sprawdzanko1()
{
bool klikniente;
using (SQLconnection.con)
{
SQLconnection.openConnection();
SqlCommand cmd = new SqlCommand("Select [Otwarte] FROM Okienka WHERE Dzien LIKE '1';", SQLconnection.con);
klikniente = (bool)cmd.ExecuteScalar();
SQLconnection.closeConnection();
}
if (klikniente == false && dt.Day == 1 && dt.Month == 12)
{
b1.IsEnabled = true;
}
else
{
b1.IsEnabled = false;
}
}
And then you call Sprawdzanko1();
Good day, friends, help to finalize this class, here's the thing:
I'm trying to make it so that if there is no connection to the database, one action will be performed in the form, there will be a connection to the database, we perform another action.
Now the problem is that if you do not connect to the database, there will be terrible lags of the application itself.
using System;
using MySql.Data.MySqlClient;
namespace Launcher.SupportClass
{
public class Web_MysqlDataBase : IDisposable
{
MySqlConnection connection = new MySqlConnection("server=127.0.0.1;port=3306;username=root;password=1234;database=test-test;");
public bool Connection_BD;
public void OpenConnect()
{
if (connection.State == System.Data.ConnectionState.Closed)
{
try
{
connection.Open();
CheckConnect();
}
catch
{
CheckConnect();
}
finally
{
CheckConnect();
closedConnection();
}
}
}
public void closedConnection()
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
public MySqlConnection getConnection()
{
return connection;
}
public void Dispose()
{
Dispose(true);
}
public void CheckConnect()
{
if (connection.State == System.Data.ConnectionState.Open)
{
Connection_BD = true;
}
if (connection.State == System.Data.ConnectionState.Closed)
{
Connection_BD = false;
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Close();
connection = null;
Dispose();
}
}
}
}
}
Next, I want to perform this simple construction, but there are already errors, what am I doing wrong?
Web_MysqlDataBase bd = new Web_MysqlDataBase();
bd.OpenConnect();
string query = "SELECT `text_update` FROM `launcher` WHERE `opened`='1'";
MySqlCommand command = new MySqlCommand(query, bd.getConnection());
if (bd.Connection_BD == true)
{
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
string name = command.ExecuteScalar().ToString();
ScrollingLeable.Text = name;
ScrollingLeable.position = 750;
ScrollsLeable.Visible = true;
ScrollingLeable.Visible = true;
}
else
{
ScrollsLeable.Visible = false;
ScrollingLeable.Visible = false;
}
}
else
{
ScrollsLeable.Visible = false;
ScrollingLeable.Visible = false;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Just 1st student rotating from java to C# here. When we were studying Java we were given this kind of SQL connection manager class thing, which is just basically just bunch of code to make it easier accessing it in different classes (It's written by my danish teacher and has some misspells/inside jokes, not sure):
public class DbConnection
{ //Constants used to get access to the database
//SQL Server
private static final String driver = "nope";
// private static final String driver = "nope";
private static final String databaseName = ";databaseName=nope";
//SQL Server
// private static String userName = ";user=sa";
private static String userName = "; user=nope";
private static String password = ";password=nope";
private DatabaseMetaData dma;
private static Connection con;
// an instance of the class is generetated
private static DbConnection instance = null;
// the constructor is private to ensure that only one object of this class is created
DbConnection()
{
String url = driver + databaseName + userName + password;
try{
//load af driver
//SQL Server
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Load af class ok");
}
catch(Exception e){
System.out.println("Can not find the driver");
System.out.println(e.getMessage());
}//end catch
try{
//connection to the database
con = DriverManager.getConnection(url);
//set autocommit
con.setAutoCommit(true);
dma = con.getMetaData(); // get meta data
System.out.println("Connection to " + dma.getURL());
System.out.println("Driver " + dma.getDriverName());
System.out.println("Database product name " + dma.getDatabaseProductName());
}//end try
catch(Exception e){
System.out.println("Problems with the connection to the database");
System.out.println(e.getMessage());
System.out.println(url);
}//end catch
}//end constructor
//closeDb: closes the connection to the database
public static void closeConnection()
{
try{
con.close();
System.out.println("The connection is closed");
}
catch (Exception e){
System.out.println("Error trying to close the database " + e.getMessage());
}
}//end closeDB
//getDBcon: Get-method, returns the connection to the database
public Connection getDBcon()
{
return con;
}
//this method is used to get the instance of the connection
public static DbConnection getInstance()
{
if (instance == null)
{
instance = new DbConnection();
}
return instance;
}
public static void startTransaction()
{ try{
con.setAutoCommit(false);
}
catch(Exception e){
System.out.println("fejl start transaction");
System.out.println(e.getMessage());
}
}
public static void commitTransaction()
{ try{
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fejl commit transaction");
System.out.println(e.getMessage());
}
}
public static void rollbackTransaction()
{ try{
con.rollback();
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fejl rollback transaction");
System.out.println(e.getMessage());
}
}
}//end DbConnection
So to get used to C# for second year i thought of first of recreating this in C# and first of all: Is it good idea to have it in C#? I see many people just using
using(SqlConnection....){}
thing and I'm not sure how to implement autoCommits/Transaction rollbacks since for example transactions in C# are different classes
So far i made this little class:
class DbConnection
{
private const string DB_USER_ID = "user id=sa;";
private const string DB_USER_PASSWORD = "password=nope;";
private const string DB_SERVER_URL = #"server=localhost\SQLExpress1;";
private const string DB_NAME = "database=test; ";
private const string DB_TIME_OUT = "connection timeout=30";
private const string DB_TRUSTED_CONN = "Trusted_Connection=yes;";
private static SqlConnection myConnection = null;
private static DbConnection instance = null;
// private constructor to ensure that only object of this class is created
private DbConnection()
{
createConnection();
}
// Instantiates SqlConnection object
private void createConnection()
{
Console.WriteLine("Attempting to create connectiong...");
try
{
myConnection = new SqlConnection(DB_USER_ID +
DB_USER_PASSWORD +
DB_SERVER_URL +
DB_TRUSTED_CONN +
DB_NAME +
DB_TIME_OUT);
}
catch (Exception e)
{
Console.WriteLine("Problems with the connection to the database");
Console.WriteLine(e.Message);
}
}
private void openConnection()
{
try{
myConnection.Open();
Console.WriteLine("Connection succesfful!");
} catch(Exception e) {
Console.WriteLine(e.StackTrace);
}
}
public static void closeConnection()
{
try
{
myConnection.Close();
Console.WriteLine("Connection closed");
}
catch (Exception e)
{
Console.WriteLine("Problem closing connection");
Console.WriteLine(e.Message);
}
}
public SqlConnection getDBcon()
{
return myConnection;
}
public static DbConnection getInstance()
{
if (instance == null)
{
instance = new DbConnection();
}
return instance;
}
}
Man, that DbConnection class is bad stuff. Throw it away. In VB the author would have used ON ERROR RESUME NEXT.
The main problem is that errors are just thrown away. The program continues in a bad state.
Next problem is a static (globally shared) connection object. That's not thread-safe and if the connection ever breaks (network issue) it permanently breaks.
.NET has connection pooling. This class is something you don't need. Maybe you can write yourself a little helper to open a connection:
static SqlConnection CreateConnection() {
...
}
using (var conn = CreateConnection()) {
}
How much more simple can it be?
I am new to C# and I started studying just yesterday.
I have created class to connect to SQL Server:
namespace Exchange_Ofiice.Classes
{
public class sqlConn
{
public void connectionMethod()
{
SqlConnection myConnection = new SqlConnection("user id=ID;password=PASS;server=SERVER;database=DB;");
try
{
myConnection.Open();
}
catch
{
MessageBox.Show("Невозможно подключиться к Базе данных. Пожалуйста обратитесь к программистам!", "Ошибка подключения к Базе данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
myConnection.Close();
}
}
}
}
and another class for user authentification:
namespace Exchange_Ofiice.Classes
{
public class auth:sqlConn
{
public void authMethod()
{
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
}
}
}
How to get (use) SQL connection result (myConnection) in second class?
P.S. line SqlCommand myCommand = new SqlCommand("Command String", myConnection); does not work.
P.S.S. Sorry, if I have mistake, my english is not perfect.
Try this. So you have the SQLConnection in the class and not in the function.
If you declare something in a function it will only be accessible in that function.
public class sqlConn
{
public SqlConnection myConnection;
public void connectionMethod()
{
myConnection = new SqlConnection("user id=ID;password=PASS;server=SERVER;database=DB;");
try
{
myConnection.Open();
}
catch
{
MessageBox.Show("Невозможно подключиться к Базе данных. Пожалуйста обратитесь к программистам!", "Ошибка подключения к Базе данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
myConnection.Close();
}
}
}
Oh you might want to consider making the SQLConnection private
private SqlConnection myConnection;
And then make a function to retrieve the value.
public SqlConnection GetConnection()
{
return myConnection;
}
And in the other class it will be:
SqlCommand myCommand = new SqlCommand("Command String", GetConnection());
First of all, connection should be public field of your class, not function variable. And secondly, you're closing your connection in finally, so you have no chance to make it working later.
public class sqlConn
{
public SqlConnection myConnection = new SqlConnection("user id=ID;password=PASS;server=SERVER;database=DB;");
public void connectionMethod()
{
try
{
myConnection.Open();
}
catch
{
//Here goes error handling...
}
}
}
And, surely, in your authMethod you should make checks for connection state, to prevent exceptions, if connection was not initialized.
Also, as good practice, make sure you're implementing IDisposable interface (http://msdn.microsoft.com/en-us/library/system.idisposable.aspx) for your connection class, otherwise you might have some troubles later.