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.
Related
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;
Hello can someone please help me? when i am trying to get a string value from a table on my sql server database table it says that i can not convert string to int, but i dont want to convert the value to int. as the values in the table are "Admin" and "General User".
by the way i am using sql server 2014
the variable that i use to capture the string is cap and i declared it as a string.
and when i write the code.
conn.Open();
string query_inicio = "select * from usuarios where USU_Usuario = '" + txtusuario.Text + "' AND USU_Contra ='" + txtcontra.Text + "'";
SqlCommand exe_query_inicio = new SqlCommand(query_inicio, conn);
SqlDataReader leer_exe;
try
{
leer_exe = exe_query_inicio.ExecuteReader();
if (leer_exe.Read())
{
cap = leer_exe.GetString("Admin");
MessageBox.Show("CONECTADO");
if (cap.Equals("Admin"))
{
Reporte_Detallado IB = new Reporte_Detallado();
IB.Show(this);
this.Hide();
}
}
else if (leer_exe.Read() == false)
{
MessageBox.Show("Inicio Fallido, Verifique Conexion");
}
it underlines the cap = leer_exe.GetString("Admin"); and says that i can't convert string to int.
i have the same code using a mysql datbase and it works. now i am trying to do it with microsoft sql server. so the only thing i changed from the mysql version was instead of mysqlconection and those database code lines to sqlconnection and the other variations.
here is my complete code. i hope someone can help me.
by the way i am coding in c#.
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 System.Data.SqlClient;
namespace ClimateReports
{
public partial class Login : Form
{
SqlConnection conn = ConexionBD.ObtenerConexion();
string cap;
public Login()
{
InitializeComponent();
}
private void btncancelar_Click(object sender, EventArgs e)
{
this.Dispose();
}
private void btniniciar_Click(object sender, EventArgs e)
{
conn.Open();
string query_inicio = "select * from usuarios where USU_Usuario = '" + txtusuario.Text + "' AND USU_Contra ='" + txtcontra.Text + "'";
SqlCommand exe_query_inicio = new SqlCommand(query_inicio, conn);
SqlDataReader leer_exe;
try
{
leer_exe = exe_query_inicio.ExecuteReader();
if (leer_exe.Read())
{
cap = leer_exe.GetSqlString("Admin");
MessageBox.Show("CONECTADO");
if (cap.Equals("Admin"))
{
Reporte_Detallado IB = new Reporte_Detallado();
IB.Show(this);
this.Hide();
}
}
else if (leer_exe.Read() == false)
{
MessageBox.Show("Inicio Fallido, Verifique Conexion");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
}
}
The problem is this line:
cap = leer_exe.GetString("Admin");
GetString takes an int32 as its argument.
If you want to access a column by its name, you should use Item instead:
cap = leer_exe["Admin"] as string;
Or, if you know what column "Admin" is, you can replace it with its position index. If it's the 4th column in the resultset, you'd use index 3 (because it's base 0):
cap = leer_exe.GetString(3);
The code does connect to the database and actually check the username(number) and then exception runs when it has to get to verifying the password and a null reference is thrown
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Intellicell_CallCentreConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT COUNT(*) FROM Debtors WHERE MobilePhone='" + txtMobilePhone.Text + "'";
SqlCommand cmd = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string CheckPasswordQuery = "SELECT IDNumber from Debtors WHERE MobilePhone='" + txtPassword.Text + "'";
SqlCommand passCmd = new SqlCommand(CheckPasswordQuery, conn);
string password = passCmd.ExecuteScalar().ToString().Replace(" ","");
conn.Close();
if (password == txtPassword.Text)
{
Session["New"] = txtMobilePhone.Text;
Response.Write("Password is correct!");
Response.Redirect("Home.aspx");
}
else
{
Response.Write("Password is not correct!");
}
}
else
{
Response.Write("Please Provide valid Login details!");
}
}
}
it is on line
string password = passCmd.ExecuteScalar().ToString().Replace(" ","");
that it breaks.
I suggest you if you want write sql adhoc, use string.format
It's clean
string checkuser = string.Format("SELECT COUNT(*) FROM Debtors WHERE MobilePhone={0},txtMobilePhone.Text);
Secondly, you can use using syntax , in order to clean your connection properly
I think, In the second sql you are using txtPassword.Text instead of txtMobilePhone.Text
The question is why are you getting the null execption, see this: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
In summary ExecuteScaler returns a null (not a DBNull) if no rows are found, whence passCmd.ExecuteScalar().ToString().Replace(" ",""); null refences as its null.ToString()
You global logic looks flawed so hard to suggest exactly what to do, but passCmd.ExecuteScalar()?.ToString().Replace(" ","") will suppress the exeception.
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();
}
}
}
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.