I have a code that I use to login.
I call the data I get from textbox with a method and check the records with select query in the
database.
I call to relevant method , when I press the button.
private void btnGiris_Click(object sender, EventArgs e)
{
LoginBilgiler lb = new LoginBilgiler();
bool sonuc = lb.GirisKontrol(txtAd.Text, txtSifre.Text);
}
But I encounter errors in cmd.ExecuteReader the below.
public bool GirisKontrol(string ad,string sifre)
{
using (OracleConnection con = new OracleConnection(connectionString))
{
string query = String.Format("SELECT count(*) from Z_LABEL_USER where USERNAME=({0}) and PASSWORD=({1})", ad,sifre);
OracleCommand cmd = new OracleCommand(query, con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
kAdi = ad;
con.Close();
return true;
}
else
con.Close();
return false;
}
}
The table I use for the select query.
Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01722: invalid
number'
Please, don't hardcode parameters in SQL; parametrize it instead:
public bool GirisKontrol(string ad, string sifre) {
//DONE: validate public methods' input
if (string.IsNullOrEmpty(ad))
return false; // or throw exception
else if (string.IsNullOrEmpty(sifre))
return false; // or throw exception
using (OracleConnection con = new OracleConnection(connectionString)) {
con.Open();
//DONE: no need to count all the entires, just check if there's at least one
//DONE: keep query readable
//DONE: paramterize queries
string query =
#"select 1
from Z_LABEL_USER
where USERNAME = :prm_UserName
and PASSWORD = :prm_Password";
using (OracleCommand cmd = new OracleCommand(query, con)) {
//TODO: this syntax can vary from library to library you use to work with Oracle
cmd.Parameters.Add(":prm_UserName", OracleType.VarChar).Value = ad;
cmd.Parameters.Add(":prm_Password", OracleType.VarChar).Value = sifre;
using (OracleDataReader dr = cmd.ExecuteReader()) {
if (dr.Read()) {
//TODO: Side effect : it changes instance's state. Do you really want it?
kAdi = ad;
return true;
}
}
}
}
return false;
}
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 have the following code in C#-
private void sendnotificationmail(string enqid)
{
try
{
connection.Open();
List<string> maillist = new List<string>();
string sql = "SELECT TrussLog.repmail, TrussLog.branchemail, TrussEnquiry.DesignerEmail FROM TrussLog FULL OUTER JOIN TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID where TrussEnquiry.Enquiry_ID = '" + enqid + "'";
SqlCommand cmd = new SqlCommand(sql);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (!string.IsNullOrEmpty(reader[0].ToString()))
{
maillist.Add(reader[0].ToString());
}
if (!string.IsNullOrEmpty(reader[1].ToString()))
{
maillist.Add(reader[1].ToString());
}
if (!string.IsNullOrEmpty(reader[2].ToString()))
{
maillist.Add(reader[2].ToString());
}
}
connection.Close();
if (result != DialogResult.Cancel)
{
processmail(maillist);
}
}
catch (Exception)
{
}
}
I am getting the value of the variable enqid from a combobox on my Windows form.The contents of the combobox are retrieved from the database. On form load, the combobox displays the first enquiryID retrieved from the database. When I run my program the data reader skips the loop. However if I select a different enquiry in the combobox, the data reader works properly
It seems that you've forgot to associate Command with the Connection:
// SendNotificationMail is more readable then sendnotificationmail
private void sendnotificationmail(string enqid) {
// put IDisposable into using...
using (SqlConnection con = new SqlConnection("ConnectionStringHere")) {
con.Open();
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = con; // <- You've omitted this
// have SQL readable
cmd.CommandText =
#"SELECT TrussLog.repmail,
TrussLog.branchemail,
TrussEnquiry.DesignerEmail
FROM TrussLog FULL OUTER JOIN
TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID
WHERE TrussEnquiry.Enquiry_ID = #prm_Id";
// use parametrized queries
cmd.Parameters.AddWithValue("#prm_Id", enqid);
using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
...
}
}
}
}
}
And never, never after write code alike
catch (Exception)
{
}
which means "just ignore all the errors and continue".
I want to call the ID of the row because I want to delete the row.
Here is my code:-
private void DeleteAttachment(string ID)
{
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
connection.Open();
string sql = "DELETE FROM EMP_ATTACHED_DOCUMENTS WHERE mkey= #ID";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
}
protected void GrdTraining_DeleteCommand(object sender, Obout.Grid.GridRecordEventArgs e)
{
if (Session["dt10"] != null)
{
dt10 = (DataTable)Session["dt10"];
}
else
{
BindDatatable();
}
DeleteAttachment(ID);
DataRow[] grdTrain = dt10.Select("SR_NO=" + Convert.ToString(e.Record["SR_NO"]));
dt10.Rows.Remove(grdTrain[0]);
AddToViewState("GrdTraining");
}
but I am unable to delete the row. When I tried to debug it, at ID, I was getting _Page.
The error message:
Error converting data type nvarchar to numeric
Please, suggest a way to call a dynamic ID.
Based on your comments I think you need to do something like the following
private void DeleteAttachment(string ID)
{
decimal numericId;
if(!decimal.TryParse(ID, out numericId))
{
// The ID is not a valid decimal determine what to do in that case.
}
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
connection.Open();
string sql = "DELETE FROM EMP_ATTACHED_DOCUMENTS WHERE mkey= #ID";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("#ID", SqlDbType.Decimal).Value = numericId;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
}
Alternatively you could change the ID argument to the DeleteAttachment method to be a decimal and do the parsing outside the method.
within the DeleteAttachment I would simply put:
decimal temp;
if (!Decimal.TryParse(ID, out temp)) { return; }
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;
}
}
I have a ListView. It has 6 columns:
question_id | question_text | start_time | end_time | status | repeat
respectively. Right now I am able to display the data from the database. This is my code:
private void Voting_Editor_Tool_Load(object sender, EventArgs e)
{
GetData();
}
public void GetData()
{
try
{
now = DateTime.Now;
String time_date = now.ToString();
myConnection = new SqlConnection(#"User ID=sa;Password=password123;Initial Catalog=dishtv;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
//myConnection.Open();
//SqlDataReader dr = new SqlCommand("SELECT question_text,question_id FROM otvtbl_question ", myConnection).ExecuteReader();
// listView1.Columns.Clear();
listView1.Items.Clear();
myConnection.Open();
String MyString1 = string.Format("SELECT question_id,question_text,start_time,end_time,status,repeat FROM otvtbl_question");
com = myConnection.CreateCommand();
com.CommandText = MyString1;
dr = com.ExecuteReader();
ListViewItem itmX;
//Adding the Items To The Each Column
while (dr.Read())
{
itmX = new ListViewItem();
itmX.Text = dr.GetValue(0).ToString();
var word = itmX.Text;
for (int i = 1; i < 6; i++)
{
itmX.SubItems.Add(dr.GetValue(i).ToString());
}
if (dr.GetDateTime(2) < now && dr.GetDateTime(3) > now)
{
itmX.SubItems[4].Text = "Broadcasting";
}
else if (dr.GetDateTime(3) < now)
{
string a=Convert.toString(dr.GetDateTime(3));
itmX.SubItems[4].Text = "Expired";
String broadcast = string.Format("UPDATE otvtbl_question SET status='EXPIRED' where start_time='{6}'",a );
//Execute the SqlCommand
com = new SqlCommand(broadcast, myConnection);
com.ExecuteNonQuery();
}
else
{
itmX.SubItems[4].Text = "Not Expired";
}
listView1.Items.Add(itmX);
}
dr.Close();
myConnection.Close();
}
catch (Exception ex)
{
//Error Message While Fetching
MessageBox.Show("Error While Fetching the data From the DataBase" + ex);
}
finally
{
//Closing The Connection
if (dr != null)
dr.Close();
if (myConnection.State == ConnectionState.Open)
myConnection.Close();
}
}
In this code the status column has to be updated every time the user load the form. While the form is loading it has to check the whether the start_time is greater than current time. If it is greater than the status column has to display NOT EXPIRED otherwise it has to show EXPIRED. The problem is that I am able to show the EXPIRED and NOT EXPIRED values in Status column by comparing the time, but I want to save the EXPIRED and NOT EXPIRED values in the database while it shows the values in the status column. I have tried to update it using following command:
String broadcast = string.Format("UPDATE otvtbl_question SET status='EXPIRED' where start_time='{6}'",a );
//Execute the SqlCommand
com = new SqlCommand(broadcast, myConnection);
com.ExecuteNonQuery();
But it says:
DataReader has to be closed before Updating the data.
I even tried to close the datareader and tried to update and it says different errors as:
Index (zero based) must be greater than or equal to zero and less than size of the argument list
Any suggestions?
You should implement the using statement. This will resolve the issue. Following are the blocks where the using statement should be implemented.
Sql Connection
DataReader
Moreover we should use parameterized queries. Below is the sample code.
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string")) {
con.Open();
SqlCommand cmd = new SqlCommand();
string expression = "Parameter value";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your Parameter Name",
SqlDbType.VarChar).Value = expression;
cmd.Connection = con;
using (IDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
}
}
}
Here is the IDisposable example as requested by you.
IDisposable