I'm trying to set up a login for my project, so I'm using SqlCommand to make the command and then I use SqlDataReader to read the data from the database, but whenever I try to read it the reader appears to be empty.
When I was debugging the app I noticed that the connection wasn't showing the complete version with the password, and I searched around and found out that it doesn't show it for security reasons, so I tried to use Persist Security Info = true but it didn't work.
Here is my connection:
SqlConnection connection = new SqlConnection("Server=.\\SQLEXPRESS;Database=BD_GA;Uid=sa;Pwd=SQL_;Persist Security Info=True");
My code for the login:
connection.Open();
SqlCommand commandLogin = new SqlCommand("select * from Proprietário", connection);
SqlDataReader reader = commandLogin.ExecuteReader();
while (reader.Read())
{
if (reader.GetValue(5).ToString() == txtUser.Text && reader.GetValue(6).ToString() == txtPass.Text)
{
User = txtUser.Text;
tipo = reader.GetBoolean(7);
tssl_Login.Text = "Login feito com sucessso!";
break;
}
}
It should say "Login feito com sucesso" if it works but it doesn't show anything.
Please try these details below
Connection
SqlConnection connection = new SqlConnection("Data Source = .\\SQLEXPRESS;
Database = BD_GA;User ID = sa;Password = SQL_;Integrated Security = true;
Encrypt = False; TrustServerCertificate = True; ApplicationIntent = ReadWrite; MultiSubnetFailover = False");
If there is something wrong with connection it will show the error message.
try
{
connection.Open();
SqlCommand commandLogin = new SqlCommand("select * from Proprietário", connection);
SqlDataReader reader = commandLogin.ExecuteReader();
while (reader.Read())
{
if (reader.GetValue(5).ToString() == txtUser.Text && reader.GetValue(6).ToString() == txtPass.Text)
{
User = txtUser.Text;
tipo = reader.GetBoolean(7);
tssl_Login.Text = "Login feito com sucessso!";
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
Related
So this method is supposed to get the ipaddress of the logged in user from a MySQL Database and print it to a textbox. However, I cant seem to get it right as the program just closes after I execute this method.
public void readIPAddress()
{
string username = GlobalData._sharedUserName;
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "SELECT ipaddress FROM webappdemo.userregistration WHERE username=?username";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("?username", username);
cmd.ExecuteReader();
while (cmd.ExecuteReader().Read())
{
textBoxIPAddress.Text = reader["ipaddress"].ToString();
}
conn.Close();
}
If anyone could point out where I went wrong, I greatly appreciate your help!
Edit: After using try and catch I get this:
MySql.Data.MySqlClient.MySqlException (0x80004005): There is already an open DataReader associated with this Connection which must be closed first.
at MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)
at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex)
at MySql.Data.MySqlClient.MySqlCommand.CheckState()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at ConnectToDataBase.Form2.readIPAddress() in C:\Users\ee\Dropbox\ConnectToDataBase\ConnectToDataBase\Form2.cs:line 95
Quick Fix:
You are executing the command two times, using ExecuteReader that's why you are getting such exception. If you execute the code like this means your code will works fine:
string queryStr = "SELECT ipaddress FROM webappdemo.userregistration WHERE username=#username";
using (MySqlConnection conn = new MySqlConnection(connString))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(queryStr, conn))
{
cmd.Parameters.AddWithValue("#username", username);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
textBoxIPAddress.Text = reader["ipaddress"].ToString();
}
}
}
Smart Fix:
Here you are fetching a single value from the database in such situations you need not to use reader at all. you can simply access those value by using ExecuteScalar() method, which will give you the required object. if so You can use the following code:
using(MySqlConnection conn = new MySqlConnection(connString))
{
using(MySqlCommand cmd= new MySqlCommand(query, conn))
{
cmd.Parameters.Add("#username", username);
conn.Open();
object ipAddress= cmd.ExecuteScalar();
if (ipAddress!= null)
textBoxIPAddress.Text = ipAddress.ToString();
else
textBoxIPAddress.Text = "No data found";
}
}
Hope that you wont forget to add MySql.Data.MySqlClient; to the using section
you are executing reader two times by calling ExecuteReader(), why you need Reader here, if you only need one value from database. use ExecuteScalar that will return first value of the first record from the result. Sample code:
try
{
string query = "SELECT ipaddress FROM webappdemo.userregistration WHERE username = #username";
string connString =ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
using(MySqlConnection connection = new MySqlConnection(connString))
{
using(MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.Add("#username", username);
connection.Open();
object ip= command.ExecuteScalar();
if (ip != null) {
textBoxIPAddress.Text = ip.ToString();
}
}
}
}
catch(MySqlException ex)
{
// do something with the exception
}
Problem:
cmd.ExecuteReader(); //Executing reader and not assigning to anything
while (cmd.ExecuteReader().Read()) //Executing reader again and not assigning to anything again
{
//There is nothing assigned to reader.
textBoxIPAddress.Text = reader["ipaddress"].ToString();
}
Quick Solution:
//assuming reader is defined
reader = cmd.ExecuteReader();
while (reader.Read()) //read from the reader
{
textBoxIPAddress.Text = reader["ipaddress"].ToString();
}
Alternative Solutions using MySql.Data.MySqlClient.MySqlHelper:
try {
object ip = MySqlHelper.ExecuteScalar(connString, query, new MySqlParameter[] {
new MySqlParameter("?username", username)
}));
if (ip != null) {
textBoxIPAddress.Text = ip.ToString();
}
} catch (Exception ex) {
// do something with the exceptio
}
If you insist on using reader:
//assuming reader is defined
reader = MySqlHelper.ExecuteReader(connString, query, new MySqlParameter[] {
new MySqlParameter("?username", username)
}));
while (reader.Read()) //read from the reader
{
textBoxIPAddress.Text = reader["ipaddress"].ToString();
}
Note: the above code is just typed in here and may contain syntax errors. take this a a guideline.
I am trying to connect to the SQL Server database in C#, and check that the database contains an empty table with 3 columns, but I don't know how to check if it is successful or not..
My code:
protected bool checkDB()
{
string ConnectionString = "Server=[serverName];Database=[databaseName];Trusted_Connection=true";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand com = new SqlCommand("SELECT * FROM tableName", con);
// use the connection here
con.Open();
con.Close();
if (success)
{
return true;
}
else
{
return false;
}
}
protected bool checkDB()
{
var connString = #"Server=myServerName\myInstanceName;Database=myDataBase;Integrated Security=true;";
try
{
using (var con = new SqlConnection(connString))
{
con.Open();
using (var com = new SqlCommand("SELECT * FROM tableName", con))
{
// use your query here...
}
}
return true;
}
catch (Exception)
{
return false;
}
}
I want to validate a QR code from a MySQL database. But the QR code is invalid and I want to access it into my program.
How to validate it?
if (decodeStr == null)
{
MessageBox.Show("There is no QR Code!");
}
else
{
player.Play();
ConnectToDatabase();
MySqlCommand cmd = new MySqlCommand("Select Name, LPN From visitors Where password = #password;", conn);
cmd.Parameters.AddWithValue("#password", decodeStr);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if(reader["password"].ToString() == decodeStr){
//this is the problem here..
}
MessageBox.Show("he");
name = reader["Name"].ToString();
lpn = reader["LPN"].ToString();
}
CheckForIllegalCrossThreadCalls = false;
//reader.Close();
videoStream.Stop();
this.Hide(); // closes the Form2 instance.
Application.Run(new VisitorData());
}
Try code below : Place your connection string inside this code.
if (decodeStr == null)
{
MessageBox.Show("There is no QR Code!");
}
else
{
player.Play();
MySqlConnection connection;
string cs = #"server=server ip;userid=username;password=userpass;database=databse";
connection = new MySqlConnection(cs);
connection.Open();
MySqlCommand command = new MySqlCommand();
string SQL = "Select Name, LPN From visitors Where password = #password";
command.CommandText = SQL;
command.Parameters.Add("#password", decodeStr);
command.Connection = connection;
command.ExecuteNonQuery();
connection.Close();
var reader = command.ExecuteReader();
while (reader.Read())
{
MessageBox.Show("he");
name = reader["Name"].ToString();
lpn = reader["LPN"].ToString();
}
CheckForIllegalCrossThreadCalls = false;
//reader.Close();
videoStream.Stop();
this.Hide(); // closes the Form2 instance.
Application.Run(new VisitorData());
}
I am trying to change password option with ms access database....
please help me folks....
here the code:
default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
try
{
OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["vhgroupconnection"].ConnectionString);
myCon.Open();
string userid = txtuserid.Text;
string oldpass = txtoldpass.Text;
string newPass = txtnewpass.Text;
string conPass = txtconfirmpass.Text;
string q = "select user_id,passwd from register where user_id = #userid and passwd = #oldpass";
OleDbCommand cmd = new OleDbCommand(q, myCon);
OleDbDataReader reader = new OleDbDataReader();
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#oldpass", txtoldpass.Text);
reader = cmd.ExecuteReader();
reader.Read();
if (reader["user_id"].ToString() != String.Empty && reader["passwd"].ToString() != String.Empty)
{
if (newPass.Trim() != conPass.Trim())
{
lblmsg.Text = "New Password and old password does not match";
}
else
{
q = "UPDATE register SET passwd = #newPass WHERE user_id =#userid";
cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#newPasss", txtnewpass.Text);
cmd.Parameters.AddWithValue("#userod", txtuserid.Text);
cmd.Parameters.AddWithValue("#passwd", txtoldpass.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
lblmsg.Text = "Password changed successfully";
}
else
{
lblmsg.Text = "password not changed";
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
also check pls.....
Compilation Error Description: An error occurred during the
compilation of a resource required to service this request. Please
review the following specific error details and modify your source
code appropriately.
Compiler Error Message: CS0143: The type
'System.Data.OleDb.OleDbDataReader' has no constructors defined
Source Error:
Line 36: OleDbCommand cmd = new OleDbCommand(q, myCon);
Line 37:
Line 38: OleDbDataReader reader = new OleDbDataReader();
Line 39:
Line 40:
As error message says; OleDbDataReader has no constructor.
From documentation of OleDbDataReader;
To create an OleDbDataReader, you must call the ExecuteReader method
of the OleDbCommand object, instead of directly using a constructor.
You can use ExecuteReader method that returns OleDbDataReader
OleDbDataReader dr = cmd.ExecuteReader();
And you need add your parameter values before you call ExecuteReader method.
Also use using statement to dispose your OleDbConnection, OleDbCommand and OleDbDataReader like;
using(OleDbConnection myCon = new OleDbConnection(conString))
using(OleDbCommand cmd = myCon.CreateCommand())
{
//Define your sql query and add your parameter values.
using(OleDbDataReader dr = cmd.ExecuteReader())
{
//
}
}
And as Steve mentioned, OleDbDataReader.Read method returns boolean value (true of false) and it reads your OleDbDataReader results row by row. You might need to consider to use the result of this method like in a while statement. For example;
while(reader.Read())
{
//Reads your results until the last row..
}
As a final words, I strongly suspect you store your passwords as plain text. Don't do that! Use SHA-512 hash.
As MSDN clearly states, To create an OleDbDataReader, you must call the ExecuteReader method of the OleDbCommand object, instead of directly using a constructor.
You cannot instantiate it using new, which is what you are doing and which is why you get the error. Remove the offending line and change it to this to get rid of the error:
OleDbDataReader reader = cmd.ExecuteReader();
Also, remember to use using blocks to ensure resources get properly disposed.
using(OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["vhgroupconnection"].ConnectionString))
{
OleDbCommand cmd = new OleDbCommand(q, myCon);
//Add parameters etc
OleDbDataReader reader = cmd.ExecuteReader();
//Rest of the processing
}
Problem: You try to make new instance of OleDbDataReader by calling new OleDbDataReader() instead you should create a reader using OleDbCommand.ExecuteReader().
In the following code notice use of using statement (this should ensure connection closing or reader closing for the case of OleDbDataReader).
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string sConnString = ConfigurationManager.ConnectionStrings["vhgroupconnection"].ConnectionString;
using(OleDbConnection myCon = new OleDbConnection(sConnString))
{
myCon.Open();
string userid = txtuserid.Text;
string oldpass = txtoldpass.Text;
string newPass = txtnewpass.Text;
string conPass = txtconfirmpass.Text;
string q = "select user_id,passwd from register where user_id = #userid and passwd = #oldpass";
OleDbCommand cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#oldpass", txtoldpass.Text);
string sUserId = string.Empty;
string sPass = string.Empty;
using(OleDbDataReader reader = cmd.ExecuteReader())
{
if(reader.Read()) //assumption: one record returned
{
sUserId = reader["user_id"].ToString();
sPass = reader["passwd"].ToString();
}
}
if (sUserId != string.Empty && sPass != string.Empty)
{
if (newPass.Trim() != conPass.Trim())
lblmsg.Text = "New Password and old password does not match";
else
{
q = "UPDATE register SET passwd = #newPass WHERE user_id =#userid";
cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#newPass", txtnewpass.Text);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
lblmsg.Text = "Password changed successfully";
else
lblmsg.Text = "password not changed";
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
When debugger is applied the query-line shows no data in textBox1.Text.my code is following:
namespace SeparateConnection
{
class clsGridView
{
Connection co2 = new Connection();
//display our global varaible for connection
SqlConnection myconn3 = new SqlConnection("data source=M-SULEMAN-PC;initial catalog=dbmsLogin;integrated security=sspi");
public void Delete()
{
co2.setconn();
try
{
DialogResult result = MessageBox.Show("Are you sure you want to delete ?", "Message",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
//myconn3.Open();
DataTable table2 = new DataTable();
frmGridView gd = new frmGridView();
SqlDataAdapter myadd2 = new SqlDataAdapter("Delete from tblLogin where UserName ='" + gd.textBox1.Text + "'", myconn3);
myadd2.Fill(table2);
//Sqlcommandbulider to allow changes to database
SqlCommandBuilder mybuild = new SqlCommandBuilder(myadd2);
//Update the database
myadd2.Update(table2);
//Close the connection
myconn3.Close();
}
else
return;
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
----------when I use the same class for calling and defining the method..there is no problem
To delete data you must follow this pattern:
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Delete from tblLogin where UserName = #param";
cmd.Parameters.Add("#param", gd.textBox1.Text);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
why dont you try out something like this
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "delete product where Product_name ='Product6'";
try
{
connection.Open();
adapter.DeleteCommand = connection.CreateCommand();
adapter.DeleteCommand.CommandText = sql;
adapter.DeleteCommand.ExecuteNonQuery();
MessageBox.Show ("Row(s) deleted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}