Connecting c#.net To phpmyadmin database(MysqL) - c#

I have .NET program written in C# that connects to my website's phpmyadmin which is in cpanel. My problem is that when I'm at the office I can connect to my phpmyadmin server, but when i'm, for example in my house, I can not connect to the server.
I've already included my ISP (www.whatismyip.com/www.speedtest.net) IP in my remoteMySQL in cpanel, but for some reason it only works at the office. Do you think that maybe it is because they are the one hosting the website that I'm connecting to?
My Connection is something like this:
string connection = "SERVER=MyWebsite.com; Database=databse_pcc; Uid=mywebuser; Pwd=password;";
con9.Open();
MySqlCommand cmd9 = new MySqlCommand("Select * from biometrics_tbl LIMIT 1", con9);
cmd9.CommandType = CommandType.Text;
cmd9.Connection = con9;
MySqlDataReader rdr9 = cmd9.ExecuteReader();
while (rdr9.Read())
{
MessageBox.Show(rdr9.GetString(2));
}
con9.Close();
Note this style of connection is working only at the office :(

First off, you're connecting to a database server, namely MySQL not PHPMyAdmin which is a web client for MySQL.
Second assuming what you've said is correct and you have in fact allowed your IP to login to the MySQL database using the login provided, you'll still need to make sure your company allows remote MySQL connections (not likely if they value security).

using MySql.Data.MySqlClient;
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;
namespace WindowsFormsApp3
{
public partial class Form1: Form
{
MySqlConnection conn = new MySqlConnection(#"Data Source = localhost;port=3306;Initial Catalog=loginandregister; User Id=root;password=''");
public Form1()
{
InitializeComponent();
}
bool _regiter()
{
int retval = 0;
try
{
string SQLS = string.Empty;
SQLS += "INSERT tb_user SET ";
SQLS += "fullname='" + textBox1.Text + "'";
SQLS += ",user='" + textBox2.Text + "'";
SQLS += ",password='" + textBox3.Text + "'";
conn.Open();
using (MySqlCommand com = new MySqlCommand(SQLS, conn))
{
retval = com.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally { conn.Close(); }
return retval > 0;
}
private void button1_Click(object sender, EventArgs e)
{
_regiter();
MessageBox.Show("Register Success");
Form2 oRegisterrr = new Form2();
oRegisterrr.ShowDialog();
this.Close();
}
}
}
using MySql.Data.MySqlClient;
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;
namespace WindowsFormsApp3
{
public partial class Form2 : Form
{
MySqlConnection conn = new MySqlConnection(#"Data Source = localhost;port=3306;Initial Catalog=loginandregister; User Id=root;password=''");
public Form2()
{
InitializeComponent();
}
private void LoginProcess()
{
if (login(textBox1.Text, textBox2.Text))
{
MessageBox.Show("Welcome " + textBox1.Text);
this.Hide();
//Form_Menu oFormMenu = new Form_Menu();
// oFormMenu.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Login Fail");
}
}
private Boolean login(string sUsername, string sPassword)
{
string SQL = "SELECT user,password FROM tb_user";
conn.Open();
MySqlCommand cmd = new MySqlCommand(SQL, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if ((sUsername == reader.GetString(0)) && (sPassword == reader.GetString(1)))
{
conn.Close();
return true;
}
}
conn.Close();
return false;
}
private void button1_Click(object sender, EventArgs e)
{
LoginProcess();
}
}
}

Related

Set a Label text in 1st winform page to display on 2nd form page

Im fairly new to C# so please forgive me if my terminology isn't to par. In my winform application I want to grab a name from a MySQL database # login and display the name on a second page(home.cs). Im currently getting an error which is "An Object Reference is required for the non static field. In login.cs im trying to add something like -> Home.bunifuCustomLabel2.Text = "test"; to set the label in home.cs basically... Login.cs is my 1st loading page and Home.cs is my 2nd page which loads after successful login. I would like to query the database while the connection is open and eventually set the label text for home.cs to display something like Welcome, Name
LOGIN.CS:
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 Firemax
{
public partial class Login : Form
{
MySqlConnection con = new MySqlConnection(#"Data Source=xyz.com;port=3333;Initial Catalog = test_db;User Id = fml;password=imscrewed");
int i;
public Login()
{
InitializeComponent();
this.CenterToScreen();
}
private void BunifuMaterialTextbox1_OnValueChanged(object sender, EventArgs e)
{
}
private void BunifuMaterialTextbox2_OnValueChanged(object sender, EventArgs e)
{
bunifuMaterialTextbox2.isPassword = true;
}
private void BunifuFlatButton1_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from users where username='" + bunifuMaterialTextbox1.Text + "' and password='" + bunifuMaterialTextbox2.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i==0)
{
bunifuCustomLabel3.Text = "You have entered either a wrong Username and/or Password";
Home.bunifuCustomLabel2.Text = "test";
}
else
{
this.Hide();
Home fm = new Home();
fm.Show();
fm.Location = this.Location;
}
con.Close();
}
private void BunifuMaterialTextbox1_OnValueChanged_1(object sender, EventArgs e)
{
}
private void BunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
HOME.CS:
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 Firemax
{
public partial class Home : Form
{
public Home()
{
InitializeComponent();
this.CenterToScreen();
}
private void BunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Welcome to C# world! Changing code of logic.cs to following will eliminate the problem you are facing.
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 Firemax
{
public partial class Login : Form
{
MySqlConnection con = new MySqlConnection(#"Data Source=xyz.com;port=3333;Initial Catalog = test_db;User Id = fml;password=imscrewed");
int i;
public Login()
{
InitializeComponent();
this.CenterToScreen();
}
private void BunifuMaterialTextbox1_OnValueChanged(object sender, EventArgs e)
{
}
private void BunifuMaterialTextbox2_OnValueChanged(object sender, EventArgs e)
{
bunifuMaterialTextbox2.isPassword = true;
}
private void BunifuFlatButton1_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from users where username='" + bunifuMaterialTextbox1.Text + "' and password='" + bunifuMaterialTextbox2.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
Home fm = new Home();
if (i==0)
{
bunifuCustomLabel3.Text = "You have entered either a wrong Username and/or Password";
fm.bunifuCustomLabel2.Text = "test";
}
else
{
this.Hide();
fm.Show();
fm.Location = this.Location;
}
con.Close();
}
private void BunifuMaterialTextbox1_OnValueChanged_1(object sender, EventArgs e)
{
}
private void BunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Your code needs improvements. I would highly recommend investing 70 minutes in C# video series by Mosh.
Maybe this can help you
In your first activity
public static string myText= "";
myText=myLabel.Text;
In your second activity Form_Load
seconLabel.Text = Form3.myText;

use connection with different forms c#

I have a form say form1 in C# the user has to put database name username password in the textboxes of form1. Once the connection is established form2 will open which will display data with predefined sqls. Also additional forms are needed to use the same connection string.How can i achieve this.
I am using ODAC to connect to oracle database.
This is the 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 Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
namespace Sparrow1
{
public partial class connectform : Form
{
public connectform()
{
InitializeComponent();
}
private OracleConnection conn = new OracleConnection();
private void button1_Click(object sender, EventArgs e)
{
conn.ConnectionString = "User Id=" + username.Text +
";Password=" + password.Text +
";Data Source=" + dataSource.Text + ";";
try
{
conn.Open();
button1.Enabled = false;
statuslabel.Text = "Success";
this.Hide();
overviewform oviewform = new overviewform();
oviewform.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
statuslabel.Text = "Failed";
}
finally
{
conn.Dispose();
}
}
}
}
create a public static string variable named connectionString in Form1.cs
public static string connectionString
get its value from other forms by Form1.connectionString;
Form1.connectionString;

C# how to insert data to mysql using C#?

Im very new on C#
I Only create 1 Form that Can insert Data to Mysql Database. My code not have Error, but data cant enter the Database. I m so confused.
this my code
Koneksi.cs
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Drawing;
using System.Windows.Forms;
namespace timbangan
{
public class Koneksi
{
public MySqlConnection konek;
//string konfigKoneksi = "server=localhost; database=timbangan; uid=root; pwd=";
string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public void bukaKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
var temp = konek.State.ToString();
if (temp == "Open")
{
MessageBox.Show(#"Connection working.");
}
else {
MessageBox.Show(#"Please check connection string");
}
}
public void tutupKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Close();
}
}//end of koneksi
}//end namespace
Isidata.cs File
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace timbangan
{
public class Isidata
{
MySqlDataAdapter adapter;
MySqlCommand komand;
Koneksi classKoneksi;
DataTable tabel;
string sql = "";
public DataTable tambahData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
classKoneksi = new Koneksi();
sql = "insert into tb_timbang(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT) values (" + berat_filter + ",'" + qty + "','" + nama_barang + "','" + dari + "','" + shift + "')";
//MessageBox.Show(sql);
tabel = new DataTable();
try
{
classKoneksi.bukaKoneksi();
komand = new MySqlCommand(sql);
adapter = new MySqlDataAdapter(sql, classKoneksi.konek);
adapter.Fill(tabel);
}
catch (Exception)
{
MessageBox.Show("error");
}
return tabel;
}
}//end of issdata
}//end of timbangan
Form1.cs File
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
namespace timbangan
{
public partial class Form1 : Form
{
public DataTable tabel;
public string status = "";
public string berat_filter, qty, nama_barang, dari, shift;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Isidata isi = new Isidata();
tabel = isi.tambahData(tbBerat.Text, tbQty.Text, tbNama.Text, tbDari.Text, tbShift.Text);
MessageBox.Show("Berhasil");
}
}
}
Can Anyone Help me to Fix this? or Advice me to have more short code to Insert data?
Thanks in advance
You could redesign your classes to something like this
namespace timbangan
{
public static class Koneksi
{
public static MySqlConnection konek;
private static string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public static MySqlConnection GetConnection()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
}
}//end of koneksi
public class Isidata
{
public int InsertData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
sql = #"insert into tb_timbang
(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT)
values (#berat_filter,#qty,#nama_barang,#dari,#shift)";
try
{
using(MySqlConnection cnn = Koneksi.GetConnection())
using(MySqlCommand cmd = new MySqlCommand(sql, cnn))
{
cmd.Parameters.Add("#berat_filter", MySqlDbType.VarChar).Value = berat_filter;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = qty;
cmd.Parameters.Add("#name_barang", MySqlDbType.VarChar).Value = nama_barang;
cmd.Parameters.Add("#dari", MySqlDbType.VarChar).Value = dari;
cmd.Parameters.Add("#shift", MySqlDbType.VarChar).Value = shift;
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("error " + ex.Message);
return -1;
}
}
}
}//end of issdata
}//end of timbangan
In this design there are no more global variables around. The same Koneski class could be totally removed and your MySqlConnection could be created on the spot (reading the connectionstring from an external source like your config file). Don't think this is less efficient than keeping a global connection object already created and always open. There is an ADO.NET Connection Pooling infrastructure (link is for Sql Server but it is the same for MySql) that runs very efficiently to handle your connections
The important thing is the Using Statement (that closes and dispose the command and the connection when no more needed freeing valuable resources) and the parameters used to fill the command sent to the server. If you need to use an Adapter for other aspect of your work you could add other methods like this to your Isidata class
As a last note, notice that all parameters are of string type. This could work but it is best to have parameters of the same type of the field type on the database (and of course your variables should be of the correct datatype). This is particularly important with datetime fields that when are treated as strings could give a good headache to let them work correctly) See MySqlDbType enum
Make a class named DBClass.cs and write the below code-
class DBClass
{
MySqlCommand odcmd = new MySqlCommand();
MySqlConnection odcon = new MySqlConnection();
MySqlDataAdapter oda = new MySqlDataAdapter();
public DBClass()
{
}
public void OpenConnection()
{
odcon.ConnectionString = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
if (odcon.State == ConnectionState.Closed)
odcon.Open();
oda.SelectCommand = odcmd;
odcmd.Connection = odcon;
}
public void CloseConnection()
{
if (odcon.State == ConnectionState.Open)
odcon.Close();
}
public DataTable Select(string sql)
{
DataTable dt = new DataTable();
odcmd.CommandText = sql;
oda.Fill(dt);
return dt;
}
public int ModiFy(string sql)
{
odcmd.CommandText = sql;
return odcmd.ExecuteNonQuery();
}
}
On your form, Now you can fire your query like-
DbclassObject.Modify(Your_Insert_Update_Delete_Query);
DataTable dt= DbclassObject.Select(Your_Select_Query);

Arithmetic operation resulted in an overflow error c#

Hello i'm using c# to build an application to connect to remote mysql server.
Here is the 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 login
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (tryLogin(textBox1.Text, textBox2.Text) == true)
{
MessageBox.Show("Authed!");
}
else
{
MessageBox.Show("Auth Failure.");
}
}
public bool tryLogin(string username, string password)
{
MySqlConnection con = new MySqlConnection("host=myhostname;user=myusername;password=mypassword;database=mydatabase;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM test WHERE username = '" + username + "' AND password = '" + password + "';");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}
}
}
It shows the following error:
"OverflowException was unhandled
Arithmetic operation resulted in an overflow "
I'm not using any arithmetic operations here. Any help ???
Check the test table in mysql server.
Make sure that all fields have valid values in the username and password columns.
UPDATE
try to include the option "Use Pipe=false;",with your connection string.Then it will opens the connection just fine.
I hope this will help to you.

Null reference on SQL connection object

I am new to C#. I have created the login screen.I this one am not able to check the username and password.This is my code.Can anyone help me please.Thanks in advance.Please don't hesitate to copy the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
namespace Voting_Editor_Tool
{
public partial class Form1 : Form
{
SqlConnection cn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
string username = txtusername.Text;
string password = txtpassword.Text;
if (ValidateUserNamePassword(username, password))
{
// move to next form or do whatever you need to do after a successfull login
}
else
{
MessageBox.Show("Invalid user name or password", "Invalid Login");
return;
}
}
public bool ValidateUserNamePassword(string _username, string _password)
{
// string connectionString = "Data Source=[servername];Initial Catalog=[databaseName];User ID=[Admin Login];Password=[Admin Password];";
using (SqlConnection cn= new SqlConnection(#"User ID=sa;Password=password123;Initial Catalog=dish_tv;Data Source=ENMEDIA-CCDDFE5\ENMEDIA"));
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "tsp_GetUserNameAndPassword";
SqlParameterCollection sqlParams = cmd.Parameters;
sqlParams.AddWithValue("#username", _username);
sqlParams.AddWithValue("#password", _password);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (dr.Read())
{
// this will return true if a row matching the username and password is found.
// this means that the user's input is valid
return true;
}
else
{
return false;
}
dr.Close();
cn.Close();
}
}
}
}
Remove your using clause and put that piece of code into Try.. catch block. Catch the exception object and read its stacktrace. Check the connection string carefully for any typo mistakes. This should give you much more details to debug than generic error like "Object reference not set to an instance of an object"
You have a semi-colon at the end of your using statement, therefore terminating the using. Remove the semi-colon and it will work.

Categories

Resources