I want to store values of SqlCommand in string variable and print it on label. Here is my C# code
String sq="select fullname,emailId from Registration where RgId= '"+Session["RgId"]+"'";
SqlCommand cmd1 = new SqlCommand(sq, con);
con.Open();
SqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
while(rdr.Read())
{
string fname = (string)rdr["fullname"];
string femail=(string)rdr["emailId"];
Label4.Text = fname;
label5.Text=femail;
}
if(rdr!= null)
{
rdr.Close();
}
con.Close();
but instead of printing value it doesn't show value on label. What to do? Is there anything wrong in code?
I would recommend using using statements when dealing with db access. Things get cleaned up better this way. Since your not using a try/catch in the code provided I would assume your using it in an outer layer or something so I would:
if (Session["RgId"] == null)
throw new NullReferenceException("RgId");
using (var con = new SqlConnection())
{
const string sql = "select fullname,emailId from Registration where RgId = #RgId";
using (var cmd1 = new SqlCommand(sql, con))
{
cmd1.Parameters.Add(new SqlParameter("RdId", SqlDbType.Int) {Value = Session["RgId"]});
con.Open();
using (var rdr = cmd1.ExecuteReader(CommandBehavior.CloseConnection))
{
if (rdr.Read())
{
Label4.Text = (string) rdr["fullname"];
label5.Text = (string) rdr["emailId"];
}
else
{
//handle registration not found
}
rdr.Close();
}
}
}
To make SQL queries, not concatenate a string, this is very dangerous for your system facilitating SQL injections.
Validate your values before attempting to query and validate the query returns.
if (Session["RgId"] != null && !String.IsNullOrEmpty(Session["RgId"].ToString()))
{
String sq = "select fullname,emailId from Registration where RgId = #RgId";
SqlCommand cmd1 = new SqlCommand(sq, con);
cmd1.Parameters.Add("#RgId", Convert.ToInt32(Session["RgId"].ToString()));
con.Open();
SqlDataReader rdr = cmd1.ExecuteReader();
if (rdr != null)
{
while (rdr.Read())
{
if (rdr["fullname"] != DBNull.Value && rdr["emailId"] != DBNull.Value)
{
Label4.Text = rdr["fullname"].ToString();
label5.Text = rdr["emailId"].ToString();
}
}
}
if (rdr != null)
{
rdr.Close();
}
con.Close();
}
Regards,
Andrew
Related
I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}
Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}
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;
}
I Have a question regarding SQL commands. I could not seems to get the while loop running under the "while(dr.read())". Below Are my sample code in C# Windows Form.
Thank You.
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM network";
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
string datasource = dr[1].ToString();
string datadestination = dr[2].ToString();
if (source == datasource && destination == datadestination)
{
int newcounter;
newcounter = Convert.ToInt32(dr[4]) + 1;
cmd.CommandText = "UPDATE network set counter = #nnnewcounter";
cmd.Parameters.AddWithValue("#nnnewcounter", newcounter);
}
else
{
cmd.CommandText = "INSERT INTO network(source,destination,length,counter) VALUES (#sssource,#dddestination,#lllength,#cccounter)";
cmd.Parameters.AddWithValue("#sssource", source);
cmd.Parameters.AddWithValue("#dddestination", destination);
cmd.Parameters.AddWithValue("#lllength", length);
cmd.Parameters.AddWithValue("#cccounter", 1);
}
}
You have a few issues with this first you’re reusing the same command and using different parameters at which point you should clear them. It is also not clear if your are Opening the connection for the datareader. I would therefore move the insert and update outside the SQLDataReader as it would make the code easier to read.
using (SqlConnection connection = new SqlConnection(ConnString))
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT * FROM network";
cmd.Connection.Open();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
if (dr .HasRows)
{
while (dr.Read())
{
string datasource = dr[1].ToString();
string datadestination = dr[2].ToString();
if (source == datasource && destination == datadestination)
{
int newcounter;
newcounter = Convert.ToInt32(dr[4]) + 1;
Updateddos_network(newcounter);
}
else
{
Savedoss_network(source,destination, length, 1);
}
}
else
{
//No rows found
}
}
}
}
Then outside the method in the same class you could have.
private void Updateddos_network(int newcounter)
{
using (SqlConnection connection = new SqlConnection(ConnString))
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "UPDATE ddos_network set counter = #nnnewcounter";
cmd.Parameters.AddWithValue("#nnnewcounter", newcounter);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
private void Insertddos_network(string source, string destination, int length, int counter)
{
using (SqlConnection connection = new SqlConnection(ConnString))
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "INSERT INTO ddos_network(source,destination,length,counter) VALUES (#sssource,#dddestination,#lllength,#cccounter)";
cmd.Parameters.AddWithValue("#sssource", source);
cmd.Parameters.AddWithValue("#dddestination", destination);
cmd.Parameters.AddWithValue("#lllength", length);
cmd.Parameters.AddWithValue("#cccounter", counter);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
If you were to refactor your code further you could have a Save method for your ddos_network object which could then be used to demine if your object is being updated or inserted based upon if the current object has an Id for example.
I have a form and I want to retrieve data from a sql table and show it in the form's fields depending on the ?id I enter in the url, but I always get this error:
Procedure or function 'GetAppForm' expects parameter '#id', which was
not supplied.
Note: GetAppForm is the stored procedure.
Here's my code, please help me:
try
{
if (String.IsNullOrEmpty(Request.QueryString["id"]))
{
sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("GetAppForm", sqlConn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter id = cmd.Parameters.Add("#id", SqlDbType.Int);
id.Direction = ParameterDirection.Input;
id.Value = Request.QueryString["id"];
SqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dataReader.Read())
{
OwnerField.Text = dataReader["Owner"].ToString();
OdBookNoField.Text = dataReader["OD"].ToString();
PdLocField.Text = dataReader["pd"].ToString();
StatementNoField.Text = dataReader["Statmnt"].ToString();
ApplicationNoField.Text = dataReader["AppNo"].ToString();
AppDateField.Text = dataReader["AppDate"].ToString();
areaField.Text = dataReader["Area"].ToString();
areaNoField.Text = dataReader["AreaNo"].ToString();
blockNoField.Text = dataReader["BlockNo"].ToString();
streetNoField.Text = dataReader["StreetNo"].ToString();
}
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("No Connection!!");
}
finally
{
sqlConn.Close();
}
Change
if (String.IsNullOrEmpty(Request.QueryString["id"]))
to
if (!String.IsNullOrEmpty(Request.QueryString["id"]))
I think you just forgot to negate the String.IsNullOrEmpty condition:
try
{
if (!String.IsNullOrEmpty(Request.QueryString["id"]))
{
Please note, your code is prone to injection.
try
{
if (!String.IsNullOrEmpty(Request.QueryString["id"]))
{
sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("GetAppForm", sqlConn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", Request.QueryString["id"]);
SqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
//SqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.SingleRow);
while (dataReader.Read())
{
OwnerField.Text = dataReader["Owner"].ToString();
OdBookNoField.Text = dataReader["OD"].ToString();
PdLocField.Text = dataReader["pd"].ToString();
StatementNoField.Text = dataReader["Statmnt"].ToString();
ApplicationNoField.Text = dataReader["AppNo"].ToString();
AppDateField.Text = dataReader["AppDate"].ToString();
areaField.Text = dataReader["Area"].ToString();
areaNoField.Text = dataReader["AreaNo"].ToString();
blockNoField.Text = dataReader["BlockNo"].ToString();
streetNoField.Text = dataReader["StreetNo"].ToString();
}
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("No Connection!!");
}
finally
{
sqlConn.Close();
}
I am trying to create a list as below and updating it with values from the datareader. I need help in writing the code to update this list from the data reader.
internal IList<FilingDto> LoadStatusDtofromReader(IDataReader reader)
{
IList<FilingDto> filingstatus = new List<FilingDto>();
while (reader !=null && reader.Read())
{
var dto = new FilingDto();
var Year = (Decimal)reader["Year"];
dto = new FilingDto()
{
Controllerid = (Guid)reader["Collectorid"],
Status = DBNull.Value.Equals(reader["Status"]) ? string.Empty : reader["Status"].ToString(),
Year = Convert.ToInt32(Year),
Level = DBNull.Value.Equals(reader["Level"]) ? string.Empty : reader["ServiceLevel"].ToString()
};
filingstatus.Add(dto);
}
return status;
}
The code to read from the datareader is as below but i am stuck in between please help me complete this
DataTable FilingStatus = new DataTable("FilingStatus");
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString);
sqlcon.Open();
SqlCommand cmd = new SqlCommand("select Collectorid, Status, Year, Level from dbo.abc", sqlcon);
using (IDataReader dr =
You should invoke ExecuteReader on SqlCommand object
SqlCommand cmd = new SqlCommand("select Collectorid, Status, Year, Level from dbo.abc", sqlcon);
SqlDataReader reader = cmd.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
I suggest to use ORM like Entity framework instead ADO.NET
Try this,
DataTable FilingStatus = new DataTable("FilingStatus");
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["CentralW2Database"].ConnectionString);
sqlcon.Open();
SqlCommand cmd = new SqlCommand("select CollectorGuid, FileStatus,FilingYear, ServiceLevel from dbo.FilingRequestQueue", sqlcon);
using (var dr = cmd.ExecuteReader())
{
IList<FilingDto> list = LoadStatusDtofromReader(dr);
}
internal IList<FilingDto> LoadStatusDtofromReader(IDataReader reader)
{
var filingstatus = new List<FilingDto>();
while (reader != null && reader.Read())
{
var dto = new FilingDto
{
Controllerid = (Guid)reader["Collectorid"],
Status = DBNull.Value.Equals(reader["Status"]) ? string.Empty : reader["Status"].ToString(),
Year = Convert.ToInt32((Decimal)reader["Year"]),
Level = DBNull.Value.Equals(reader["Level"]) ? string.Empty : reader["ServiceLevel"].ToString()
};
filingstatus.Add(dto);
}
return filingstatus;
}
If you can reuse the original function just do
using (DataReader dr = cme.ExecuteReader())
{
IList<FilingDto> list = LoadStatusDtofromReader(dr);
}