error while connecting to mysql in C# asp.net - c#

I have an error while connecting my project into mysql database so i have added the code bellow to my button to fetch all rows and display it in a gridView
protected void Button1_Click(object sender, EventArgs e)
{
MySqlConnection myconn = new MySqlConnection("server=localhost;uid=root;password=;database=y;");
string strSQL = "select * from welcome";
myconn.Open();
MySqlDataAdapter mydata = new MySqlDataAdapter(strSQL, myconn);
MySqlCommandBuilder cBuilder = new MySqlCommandBuilder(mydata);
System.Data.DataSet ds = new System.Data.DataSet();
mydata.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
myconn.Close();
}
When running the the app it shows an error in myconn.Open();
An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: The host localhost does not support SSL connections.
and it pointed to myconn.Open();

change myconn to :
MySqlConnection myconn = new MySqlConnection("server=localhost;uid=root;password=;database=y;sslmode=none");
Make sure that you are adding sslmode=none in myconn

better try with Entity Frame work
Add ADO.NET Entity model,If will ask to connect db and give some name(ex :userentities)
Then, use below code in your coding
userentities context = new userentities();
protected void Button1_Click(object sender, EventArgs e)
{
using (var dbTransactionContext = context.Database.BeginTransaction())
{
//then do the operation
}
}
It's really easy
or other wise follow these steps
1. add your connection string in web config
<add name="UserContext" connectionString="server=localhost;User Id=root;password='';database=databasename;convert zero datetime=True" providerName="MySql.Data.MySqlClient" />
Add follow codes in your code
private MySqlConnection con;
con = new MySqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["UserContext"].ConnectionString;
con.Open();

Related

SQL Server EXPRESS: Error: 26 - Error Locating Server/Instance Specified after setup

(C#/ .Net Framework4.0 / VS2017).
made a c# windows form with sqlcon expressconnection database,but rly not sure how to create a setup for other client...
i have made a windows form application with a database with sqlconnection in it. im using advance installer to create a setup so i can put the .mdf and .idf files with prerequsites easily.
added connection string as:
public static class DAL
{
public static DataTable ExecSP(string spName, List<SqlParameter> sqlParams = null)
{
string strConnect = "Server=PC\\SQLEXPRESS;Database=MyLoginApp;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection();
DataTable dt = new DataTable();
try
{
//Connect to the database
conn = new SqlConnection(strConnect);
conn.Open();
//Build an sql command / query
SqlCommand cmd = new SqlCommand(spName, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(sqlParams.ToArray());
//Execute command
SqlCommand command = conn.CreateCommand();
SqlDataReader dr = cmd.ExecuteReader();
//fill datatable with the results
dt.Load(dr);
}
catch (Exception ex)
{
throw ex;
}
finally
{
//No matter what happends this will run
conn.Close();
}
return dt;
}
}
When it trying to execute the following code:
private void btnLogin_Click(object sender, EventArgs e)
{
List<SqlParameter> sqlParams = new List<SqlParameter>();
sqlParams.Add(new SqlParameter("Username", TxtUsername.Text));
sqlParams.Add(new SqlParameter("Password", txtPassword.Text));
DataTable dtLoginResults = DAL.ExecSP("ValidateLogin", sqlParams);
string eUser;
string ePass;
eUser = TxtUsername.Text;
ePass = txtPassword.Text;
if (dtLoginResults.Rows.Count == 1)
{
//We know login is valid
string user = dtLoginResults.Rows[0]["Username"].ToString();
MessageBox.Show(user + " Berhasil Masuk!");
this.Hide();
ListMeja lm = new ListMeja();
lm.ShowDialog();
}
else
{
//invalid login
MessageBox.Show("Password Salah");
}
}
gets an error popup window in other client after run the .exe program
Unhandled exception has occured in your application. if you click Continue, the application will ignore this error and and attempt to continue. A network -related or instance-specific error occured while establish a connection to SQL server.The server was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified).
what im doing wrong here ?
Please try to Connect SQL Server With SSMS from Your system.
After Successfully Login Please Edit your string strConnect = "Server=PC\\SQLEXPRESS;Database=MyLoginApp;Trusted_Connection=True;"; connection string as per SSMS Connected.
well.. this is the solution
SqlConnection con = new SqlConnection(#"Data Source = .\SQLEXPRESS;" +
#"AttachDbFilename=|DataDirectory|\MyLoginApp.mdf;Integrated Security = True;User Instance=True");
private void Form1_Load(object sender, EventArgs e)

How to solve the connection when the login failed during C# programming in database?

I did some coding on connecting data using Azure database on Windows Form and when I tried to retrieve the data, I received the following error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll.
Also in addition, I received a Login failed for user ''. When I tried to retrieve the data and located at myConnection.Open();
private void btnRetrieve_Click(object sender, EventArgs e)
{
//Create a connection calling the App.config
string conn = ConfigurationManager.ConnectionStrings["NYPConnection"].ConnectionString;
//The query to use
string query = "SELECT * FROM Users";
SqlConnection myconnection = new SqlConnection(conn);
//Create a Data Adapter
SqlDataAdapter dadapter = new SqlDataAdapter(query, myconnection);
//Create the dataset
DataSet ds = new DataSet();
//Open the connection
******myconnection.Open();******
//Fill the Data Adapter
dadapter.Fill(ds, "Users");
myconnection.Close();
//Bind the datagridview with the data set
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Users";
}
Print out the value of conn, using the following code:
string conn = ConfigurationManager.ConnectionStrings["NYPConnection"].ConnectionString;
Debug.WriteLine("conn= " + conn);
Have a look in the output window and you will probably find that conn is set to an empty string or maybe does not have the user name specified.

Trying to run a SQL query from a text box and display in a gridview

I've got the code below and am getting the error
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
SqlConnection vid = new SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\\Users\\jlm\\Desktop\\Wk5ex01vbMills\\AdventureWorksDW_Data.mdf;Integrated Security=True;Connect Timeout=30");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string str = TextBox1.Text;
SqlCommand xp = new SqlCommand(str, vid);
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
vid.Close();
}
catch (Exception c)
{
Label1.Text = (c.Message);
}
}
}
}
You need to escape \ in your connection string in a part (LocalDB)\v11.0. Should be localdb)\\v11.0.
That said - it's really risky to allow entering raw SQL to be executed against your DB. Even if you take all precautions not to allow dangerous commands - there's always a chance that something can slip thru.
public partial class _Default : Page
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\rinka.sai\\Desktop\\WebApplication1\\App_Data\\Database1.mdf;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = new SqlCommand(TextBox1.Text,conn);
SqlDataReader sdr = cmd.ExecuteReader() ;
GridView1.DataSource = sdr;
GridView1.DataBind();
sdr.Close();
conn.Close();
}
}

Track Database Status Change sql server

I want to Track database status changed in sql server . in my solution ,I have a database that is offline due to restore from primary server .
i want to get hint in my application(C#) when database is offline and when is online. (like sql notification event) .
Thanks .
One way is to check the state of the database using a timer from your application
private void timer1_tick(object sender,EventArgs e)
{
if(CheckDatabaseState() == "ONLINE")
MessageBox.Show("db is online");
else
MessageBox.Show("db is NOT online");
}
Public string CheckDatabaseState()
{
string Constr = #"Data Source=.\SQLEXPRESS;Integrated Security=True;Initial Catalog=master;";
string sql = string.Format("SELECT Name, state_desc FROM sys.databases where name = '{0}'", dbName);
SqlConnection conn;
SqlCommand comm;
SqlDataAdapter adapter;
DataSet ds = new DataSet();
conn = new SqlConnection(Constr);
comm = new SqlCommand(sql, conn);
adapter = new SqlDataAdapter(comm);
adapter.Fill(ds);
return ds.Tables[0]["state_desc"].ToString();
}
Let me know if this helps,

Connecting C# to a remote MySQL database

I am trying to connect a C# application to my MySQL database located in a remote server. When I try to execute this simple program, I get the following error: sqlException was unhandled
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("user id=student_abdo;password=XXXXXX;server=178.239.167.XXX;Trusted_Connection=yes;database=student_sms;connection timeout=30");
SqlCommand com = new SqlCommand("UPDATE `sms` SET `id`=23 WHERE `sms`='hi'",con);
com.CommandType = CommandType.Text;
con.Open();
com.ExecuteNonQuery();
con.Close();
}
The SqlClient namespace is for connecting to Microsoft SqlServer databases. If you want to work with MySql, you'll need to find an ADO.NET implementation (3rd party) or determine if there is a way to make it work with OleDb/Odbc.
UPDATE
Apparently, MySql provides its own ADO.NET driver for getting the job done.
As Brian pointed out, you are using the wrong provider. Also, your connection string is wrong. It should read
"Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
You can reference this site for all of the different connection string types for mysql
Here is what you need to download
Keep in mind that Classes for working with MySql in .NET are mostley the same as working with MSSQL with exception that they have My... prefix
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("userid=student_abdo;password=XXXXXX;server=178.239.167.XXX;Trusted_Connection=yes;database=student_sms;connection timeout=30");
MySqlCommand com = new MySqlCommand("UPDATE `sms` SET `id`=23 WHERE `sms`='hi'",con);
com.CommandType = CommandType.Text;
con.Open();
com.ExecuteNonQuery();
con.Close();
}
first of all, you know what is forms of connect string and then established the connection with the database.
bb rec
private void btnretrive_Click(object sender, EventArgs e)
{
string cs = "server=localhost;user id=root;database=world;";
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd = new SqlCommand("select * from world;",conn);
SqlDataReader reader = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
dataGridView1.DataSource = table;
conn.Close();
}

Categories

Resources